| 
 | 1 | +/*  | 
 | 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one  | 
 | 3 | + * or more contributor license agreements. Licensed under the "Elastic License  | 
 | 4 | + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side  | 
 | 5 | + * Public License v 1"; you may not use this file except in compliance with, at  | 
 | 6 | + * your election, the "Elastic License 2.0", the "GNU Affero General Public  | 
 | 7 | + * License v3.0 only", or the "Server Side Public License, v 1".  | 
 | 8 | + */  | 
 | 9 | + | 
 | 10 | +package org.elasticsearch.gradle.internal.dependencies.patches.hdfs;  | 
 | 11 | + | 
 | 12 | +import org.gradle.api.artifacts.transform.CacheableTransform;  | 
 | 13 | +import org.gradle.api.artifacts.transform.InputArtifact;  | 
 | 14 | +import org.gradle.api.artifacts.transform.TransformAction;  | 
 | 15 | +import org.gradle.api.artifacts.transform.TransformOutputs;  | 
 | 16 | +import org.gradle.api.artifacts.transform.TransformParameters;  | 
 | 17 | +import org.gradle.api.file.FileSystemLocation;  | 
 | 18 | +import org.gradle.api.provider.Provider;  | 
 | 19 | +import org.gradle.api.tasks.Classpath;  | 
 | 20 | +import org.gradle.api.tasks.Input;  | 
 | 21 | +import org.gradle.api.tasks.Optional;  | 
 | 22 | +import org.jetbrains.annotations.NotNull;  | 
 | 23 | +import org.objectweb.asm.ClassReader;  | 
 | 24 | +import org.objectweb.asm.ClassVisitor;  | 
 | 25 | +import org.objectweb.asm.ClassWriter;  | 
 | 26 | + | 
 | 27 | +import java.io.File;  | 
 | 28 | +import java.io.FileOutputStream;  | 
 | 29 | +import java.io.IOException;  | 
 | 30 | +import java.io.InputStream;  | 
 | 31 | +import java.util.Enumeration;  | 
 | 32 | +import java.util.HashMap;  | 
 | 33 | +import java.util.List;  | 
 | 34 | +import java.util.Locale;  | 
 | 35 | +import java.util.Map;  | 
 | 36 | +import java.util.function.Function;  | 
 | 37 | +import java.util.jar.JarEntry;  | 
 | 38 | +import java.util.jar.JarFile;  | 
 | 39 | +import java.util.jar.JarOutputStream;  | 
 | 40 | +import java.util.regex.Pattern;  | 
 | 41 | + | 
 | 42 | +import static java.util.Map.entry;  | 
 | 43 | +import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES;  | 
 | 44 | +import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS;  | 
 | 45 | + | 
 | 46 | +@CacheableTransform  | 
 | 47 | +public abstract class HdfsClassPatcher implements TransformAction<HdfsClassPatcher.Parameters> {  | 
 | 48 | + | 
 | 49 | +    record JarPatchers(String artifactTag, Pattern artifactPattern, Map<String, Function<ClassWriter, ClassVisitor>> jarPatchers) {}  | 
 | 50 | + | 
 | 51 | +    static final List<JarPatchers> allPatchers = List.of(  | 
 | 52 | +        new JarPatchers(  | 
 | 53 | +            "hadoop-common",  | 
 | 54 | +            Pattern.compile("hadoop-common-(?!.*tests)"),  | 
 | 55 | +            Map.ofEntries(  | 
 | 56 | +                entry("org/apache/hadoop/util/ShutdownHookManager.class", ShutdownHookManagerPatcher::new),  | 
 | 57 | +                entry("org/apache/hadoop/util/Shell.class", ShellPatcher::new),  | 
 | 58 | +                entry("org/apache/hadoop/security/UserGroupInformation.class", SubjectGetSubjectPatcher::new)  | 
 | 59 | +            )  | 
 | 60 | +        ),  | 
 | 61 | +        new JarPatchers(  | 
 | 62 | +            "hadoop-client-api",  | 
 | 63 | +            Pattern.compile("hadoop-client-api.*"),  | 
 | 64 | +            Map.ofEntries(  | 
 | 65 | +                entry("org/apache/hadoop/util/ShutdownHookManager.class", ShutdownHookManagerPatcher::new),  | 
 | 66 | +                entry("org/apache/hadoop/util/Shell.class", ShellPatcher::new),  | 
 | 67 | +                entry("org/apache/hadoop/security/UserGroupInformation.class", SubjectGetSubjectPatcher::new),  | 
 | 68 | +                entry("org/apache/hadoop/security/authentication/client/KerberosAuthenticator.class", SubjectGetSubjectPatcher::new)  | 
 | 69 | +            )  | 
 | 70 | +        )  | 
 | 71 | +    );  | 
 | 72 | + | 
 | 73 | +    interface Parameters extends TransformParameters {  | 
 | 74 | +        @Input  | 
 | 75 | +        @Optional  | 
 | 76 | +        List<String> getMatchingArtifacts();  | 
 | 77 | + | 
 | 78 | +        void setMatchingArtifacts(List<String> matchingArtifacts);  | 
 | 79 | +    }  | 
 | 80 | + | 
 | 81 | +    @Classpath  | 
 | 82 | +    @InputArtifact  | 
 | 83 | +    public abstract Provider<FileSystemLocation> getInputArtifact();  | 
 | 84 | + | 
 | 85 | +    @Override  | 
 | 86 | +    public void transform(@NotNull TransformOutputs outputs) {  | 
 | 87 | +        File inputFile = getInputArtifact().get().getAsFile();  | 
 | 88 | + | 
 | 89 | +        List<String> matchingArtifacts = getParameters().getMatchingArtifacts();  | 
 | 90 | +        List<JarPatchers> patchersToApply = allPatchers.stream()  | 
 | 91 | +            .filter(jp -> matchingArtifacts.contains(jp.artifactTag()) && jp.artifactPattern().matcher(inputFile.getName()).find())  | 
 | 92 | +            .toList();  | 
 | 93 | +        if (patchersToApply.isEmpty()) {  | 
 | 94 | +            outputs.file(getInputArtifact());  | 
 | 95 | +        } else {  | 
 | 96 | +            patchersToApply.forEach(patchers -> {  | 
 | 97 | +                System.out.println("Patching " + inputFile.getName());  | 
 | 98 | + | 
 | 99 | +                Map<String, Function<ClassWriter, ClassVisitor>> jarPatchers = new HashMap<>(patchers.jarPatchers());  | 
 | 100 | +                File outputFile = outputs.file(inputFile.getName().replace(".jar", "-patched.jar"));  | 
 | 101 | + | 
 | 102 | +                patchJar(inputFile, outputFile, jarPatchers);  | 
 | 103 | + | 
 | 104 | +                if (jarPatchers.isEmpty() == false) {  | 
 | 105 | +                    throw new IllegalArgumentException(  | 
 | 106 | +                        String.format(  | 
 | 107 | +                            Locale.ROOT,  | 
 | 108 | +                            "error patching [%s] with [%s]: the jar does not contain [%s]",  | 
 | 109 | +                            inputFile.getName(),  | 
 | 110 | +                            patchers.artifactPattern().toString(),  | 
 | 111 | +                            String.join(", ", jarPatchers.keySet())  | 
 | 112 | +                        )  | 
 | 113 | +                    );  | 
 | 114 | +                }  | 
 | 115 | +            });  | 
 | 116 | +        }  | 
 | 117 | +    }  | 
 | 118 | + | 
 | 119 | +    private static void patchJar(File inputFile, File outputFile, Map<String, Function<ClassWriter, ClassVisitor>> jarPatchers) {  | 
 | 120 | +        try (JarFile jarFile = new JarFile(inputFile); JarOutputStream jos = new JarOutputStream(new FileOutputStream(outputFile))) {  | 
 | 121 | +            Enumeration<JarEntry> entries = jarFile.entries();  | 
 | 122 | +            while (entries.hasMoreElements()) {  | 
 | 123 | +                JarEntry entry = entries.nextElement();  | 
 | 124 | +                String entryName = entry.getName();  | 
 | 125 | +                // Add the entry to the new JAR file  | 
 | 126 | +                jos.putNextEntry(new JarEntry(entryName));  | 
 | 127 | + | 
 | 128 | +                Function<ClassWriter, ClassVisitor> classPatcher = jarPatchers.remove(entryName);  | 
 | 129 | +                if (classPatcher != null) {  | 
 | 130 | +                    byte[] classToPatch = jarFile.getInputStream(entry).readAllBytes();  | 
 | 131 | + | 
 | 132 | +                    ClassReader classReader = new ClassReader(classToPatch);  | 
 | 133 | +                    ClassWriter classWriter = new ClassWriter(classReader, COMPUTE_FRAMES | COMPUTE_MAXS);  | 
 | 134 | +                    classReader.accept(classPatcher.apply(classWriter), 0);  | 
 | 135 | + | 
 | 136 | +                    jos.write(classWriter.toByteArray());  | 
 | 137 | +                } else {  | 
 | 138 | +                    // Read the entry's data and write it to the new JAR  | 
 | 139 | +                    try (InputStream is = jarFile.getInputStream(entry)) {  | 
 | 140 | +                        is.transferTo(jos);  | 
 | 141 | +                    }  | 
 | 142 | +                }  | 
 | 143 | +                jos.closeEntry();  | 
 | 144 | +            }  | 
 | 145 | +        } catch (IOException ex) {  | 
 | 146 | +            throw new RuntimeException(ex);  | 
 | 147 | +        }  | 
 | 148 | +    }  | 
 | 149 | +}  | 
0 commit comments