|
| 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.hdfs.patch; |
| 11 | + |
| 12 | +import org.objectweb.asm.ClassReader; |
| 13 | +import org.objectweb.asm.ClassVisitor; |
| 14 | +import org.objectweb.asm.ClassWriter; |
| 15 | + |
| 16 | +import java.io.File; |
| 17 | +import java.nio.file.Files; |
| 18 | +import java.nio.file.Path; |
| 19 | +import java.nio.file.Paths; |
| 20 | +import java.util.Map; |
| 21 | +import java.util.function.Function; |
| 22 | +import java.util.jar.JarEntry; |
| 23 | +import java.util.jar.JarFile; |
| 24 | + |
| 25 | +public class HdfsClassPatcher { |
| 26 | + static final Map<String, Function<ClassWriter, ClassVisitor>> patchers = Map.of( |
| 27 | + "org/apache/hadoop/util/ShutdownHookManager.class", |
| 28 | + ShutdownHookManagerPatcher::new, |
| 29 | + "org/apache/hadoop/util/Shell.class", |
| 30 | + ShellPatcher::new |
| 31 | + ); |
| 32 | + |
| 33 | + public static void main(String[] args) throws Exception { |
| 34 | + String jarPath = args[0]; |
| 35 | + Path outputDir = Paths.get(args[1]); |
| 36 | + |
| 37 | + try (JarFile jarFile = new JarFile(new File(jarPath))) { |
| 38 | + for (var patcher : patchers.entrySet()) { |
| 39 | + JarEntry jarEntry = jarFile.getJarEntry(patcher.getKey()); |
| 40 | + if (jarEntry == null) { |
| 41 | + throw new IllegalArgumentException("path [" + patcher.getKey() + "] not found in [" + jarPath + "]"); |
| 42 | + } |
| 43 | + byte[] classToPatch = jarFile.getInputStream(jarEntry).readAllBytes(); |
| 44 | + |
| 45 | + ClassReader classReader = new ClassReader(classToPatch); |
| 46 | + ClassWriter classWriter = new ClassWriter(classReader, 0); |
| 47 | + classReader.accept(patcher.getValue().apply(classWriter), 0); |
| 48 | + |
| 49 | + Path outputFile = outputDir.resolve(patcher.getKey()); |
| 50 | + Files.createDirectories(outputFile.getParent()); |
| 51 | + Files.write(outputFile, classWriter.toByteArray()); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments