diff --git a/src/main/java/io/floci/aws/services/emr/ApacheDistribution.java b/src/main/java/io/floci/aws/services/emr/ApacheDistribution.java new file mode 100644 index 0000000000..77bb7c96aa --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/ApacheDistribution.java @@ -0,0 +1,205 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.core.common.docker.RetryingTarCopier; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.zip.GZIPInputStream; + +/** + * An Apache project's binary distribution, for the image of a cluster that installs an application no AWS image + * carries: downloaded from the first of its URLs that gives it whole with its checksum, and written as the archive of + * the folder the cluster's image keeps it in, as its {@link Layout} says. Pig's is one ({@link PigDistribution}). + */ +final class ApacheDistribution { + + private static final int BUFFER_BYTES = 64 * 1024; + + /** + * Where an application's distribution goes in a cluster's image, and what of it: under {@code name} in + * {@code folder}, in place of the distribution's own top folder, its {@code folders}, but the paths under them that + * start with one of {@code leftOut}, and of its top level the {@code files} named so and, where {@code topJars}, + * its jars; then {@code written}, files of Floci's own by their path under {@code name}, each readable by everyone. + */ + record Layout(String folder, String name, Set folders, Set files, boolean topJars, + List leftOut, Map written) { + + /** The folder the application runs from. */ + String home() { + return folder + "/" + name; + } + + /** + * A path of the distribution, its own folder first, under {@link #name}, or null for one the application does + * not run from, or that leaves the folder. + */ + String kept(String path) { + if (path == null || path.startsWith("/")) { + return null; + } + int slash = path.indexOf('/'); + if (slash < 0) { + return null; + } + String rest = path.substring(slash + 1); + for (String segment : rest.split("/")) { + if (segment.equals("..")) { + return null; + } + } + if (rest.isEmpty()) { + return name + "/"; + } + int folderEnd = rest.indexOf('/'); + boolean kept = folderEnd < 0 + ? files.contains(rest) || topJars && rest.endsWith(".jar") + : folders.contains(rest.substring(0, folderEnd)) && leftOut.stream().noneMatch(rest::startsWith); + return kept ? name + "/" + rest : null; + } + } + + private final String application; + private final Layout layout; + private final List urls; + private final String algorithm; + private final String checksum; + private final String checksumSetting; + private final Duration connectTimeout; + private final Duration readTimeout; + private final Path downloads; + + /** + * The distribution of {@code application}, as messages name it, laid out as {@code layout}, from {@code urls}, the + * download's {@code algorithm} digest {@code checksum}, which the setting named {@code checksumSetting} gives; + * downloads that connect within {@code connectTimeout}, stall for no longer than {@code readTimeout}, and go into + * {@code downloads}. + */ + ApacheDistribution(String application, Layout layout, List urls, String algorithm, String checksum, + String checksumSetting, Duration connectTimeout, Duration readTimeout, Path downloads) { + this.application = application; + this.layout = layout; + this.urls = urls.stream().map(String::trim).filter(url -> !url.isEmpty()).map(URI::create).toList(); + this.algorithm = algorithm; + this.checksum = checksum.trim(); + this.checksumSetting = checksumSetting; + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + this.downloads = downloads; + } + + /** What the image's name says it holds: the distribution, by its checksum. */ + String identity() { + return layout.name() + " " + checksum.toLowerCase(); + } + + /** + * Downloads the distribution to a temporary file, which the caller deletes, from the first URL that gives it whole + * with its checksum: one that cannot be reached, answers otherwise, stalls for the read timeout or gives another + * checksum passes to the next, so nothing goes into an image before it has been checked. + */ + Path download() throws IOException { + List failures = new ArrayList<>(); + for (URI url : urls) { + Path file = Files.createTempFile(downloads, "floci-" + layout.name() + "-", ".tar.gz"); + try { + fetch(url, file); + return file; + } catch (IOException e) { + Files.deleteIfExists(file); + failures.add(url + ": " + e.getMessage()); + } + } + throw new IOException("Could not download " + application + ": " + (failures.isEmpty() ? "no URL is set" + : String.join("; ", failures))); + } + + private void fetch(URI url, Path file) throws IOException { + MessageDigest digest = digest(); + HttpURLConnection connection = (HttpURLConnection) url.toURL().openConnection(); + connection.setConnectTimeout((int) connectTimeout.toMillis()); + connection.setReadTimeout((int) readTimeout.toMillis()); + try { + int status = connection.getResponseCode(); + if (status != HttpURLConnection.HTTP_OK) { + throw new IOException("answered " + status); + } + try (InputStream in = new DigestInputStream(connection.getInputStream(), digest); + OutputStream out = Files.newOutputStream(file)) { + in.transferTo(out); + } + } finally { + connection.disconnect(); + } + String found = HexFormat.of().formatHex(digest.digest()); + if (!found.equalsIgnoreCase(checksum)) { + throw new IOException("has the " + algorithm + " " + found + ", not the " + checksum + " " + + checksumSetting + " names"); + } + } + + private MessageDigest digest() { + try { + return MessageDigest.getInstance(algorithm); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** + * Writes the folders and files {@code layout} keeps of the gzipped archive {@code download} to {@code out}, as an + * archive of the layout's folder, under its name in place of the distribution's own folder, owned by root, and the + * files it writes of its own after them. + */ + static void write(Layout layout, Path download, OutputStream out) throws IOException { + try (InputStream raw = Files.newInputStream(download); + GZIPInputStream gzip = new GZIPInputStream(raw, BUFFER_BYTES); + TarArchiveInputStream in = new TarArchiveInputStream(gzip); + TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) { + TarArchiveEntry entry; + while ((entry = in.getNextEntry()) != null) { + String path = layout.kept(entry.getName()); + if (path == null || entry.isLink() && layout.kept(entry.getLinkName()) == null) { + continue; + } + entry.setName(path); + if (entry.isLink()) { + entry.setLinkName(layout.kept(entry.getLinkName())); + } + entry.setIds(0, 0); + entry.setNames("root", "root"); + tar.putArchiveEntry(entry); + in.transferTo(tar); + tar.closeArchiveEntry(); + } + for (Map.Entry written : layout.written().entrySet()) { + TarArchiveEntry file = new TarArchiveEntry(layout.name() + "/" + written.getKey()); + byte[] content = written.getValue().getBytes(StandardCharsets.UTF_8); + file.setSize(content.length); + file.setMode(0644); + file.setIds(0, 0); + file.setNames("root", "root"); + tar.putArchiveEntry(file); + tar.write(content); + tar.closeArchiveEntry(); + } + } + } +} diff --git a/src/main/java/io/floci/aws/services/emr/PigDistribution.java b/src/main/java/io/floci/aws/services/emr/PigDistribution.java index 24a0b1ad33..4e3ef4bdc7 100644 --- a/src/main/java/io/floci/aws/services/emr/PigDistribution.java +++ b/src/main/java/io/floci/aws/services/emr/PigDistribution.java @@ -1,30 +1,16 @@ package io.floci.aws.services.emr; import io.floci.aws.config.EmulatorConfig; -import io.floci.aws.core.common.docker.RetryingTarCopier; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; -import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Duration; -import java.util.ArrayList; -import java.util.HexFormat; import java.util.List; +import java.util.Map; import java.util.Set; -import java.util.zip.GZIPInputStream; /** * Apache Pig for the image of a cluster that installs it, when {@code floci.services.emr.pig.enabled} is on: no AWS @@ -50,30 +36,25 @@ public class PigDistribution { * path it was run by, so a link would lead it to {@code /usr} instead. */ static final String COMMAND = "#!/bin/bash\nexec " + HOME + "/bin/" + NAME + " \"$@\"\n"; - // What Pig runs from: its launcher, its configuration, its jars and its licence. The docs, the sources, the tests, - // the jars of Pig on Spark, which EMR does not run, the Hadoop it bundles for a machine without one, and its Tez and - // the protobuf that Tez needs stay out, as does a pig-env.sh, Floci writing its own. - private static final Set KEPT_FOLDERS = Set.of("bin", "conf", "lib"); - private static final List LEFT_OUT = List.of("lib/spark/", "lib/hadoop2-runtime/", "lib/hadoop3-runtime/", - "lib/h3/tez-", "lib/protobuf-java-", "conf/pig-env.sh"); /** * Pig's {@code conf/pig-env.sh}, which its launcher reads before it builds its class path: the image's Tez, with * its protobuf 2.5, then the class path a cluster's {@code pig-env} sets, whose exports come first. */ static final String ENVIRONMENT = "export PIG_CLASSPATH=\"/usr/lib/tez/*:/usr/lib/tez/lib/*" + "${PIG_CLASSPATH:+:$PIG_CLASSPATH}\"\n"; - private static final String ENVIRONMENT_FILE = NAME + "/conf/pig-env.sh"; - private static final Set KEPT_FILES = Set.of("LICENSE.txt", "NOTICE.txt"); + // What Pig runs from: its launcher, its configuration, its jars and its licence. The docs, the sources, the tests, + // the jars of Pig on Spark, which EMR does not run, the Hadoop it bundles for a machine without one, and its Tez + // and the protobuf that Tez needs stay out, as does a pig-env.sh, Floci writing its own (ENVIRONMENT). + private static final ApacheDistribution.Layout LAYOUT = new ApacheDistribution.Layout(FOLDER, NAME, + Set.of("bin", "conf", "lib"), Set.of("LICENSE.txt", "NOTICE.txt"), true, + List.of("lib/spark/", "lib/hadoop2-runtime/", "lib/hadoop3-runtime/", "lib/h3/tez-", "lib/protobuf-java-", + "conf/pig-env.sh"), + Map.of("conf/pig-env.sh", ENVIRONMENT)); private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(30); // A download that sends nothing for this long has stalled, and the next URL is tried. private static final Duration READ_TIMEOUT = Duration.ofSeconds(60); - private static final int BUFFER_BYTES = 64 * 1024; - private final List urls; - private final String sha256; - private final Duration connectTimeout; - private final Duration readTimeout; - private final Path downloads; + private final ApacheDistribution distribution; @Inject public PigDistribution(EmulatorConfig config) { @@ -83,61 +64,21 @@ public class PigDistribution { PigDistribution(List urls, String sha256, Duration connectTimeout, Duration readTimeout, Path downloads) { - this.urls = urls.stream().map(String::trim).filter(url -> !url.isEmpty()).map(URI::create).toList(); - this.sha256 = sha256.trim(); - this.connectTimeout = connectTimeout; - this.readTimeout = readTimeout; - this.downloads = downloads; + this.distribution = new ApacheDistribution("Apache Pig", LAYOUT, urls, "SHA-256", sha256, + "floci.services.emr.pig.sha256", connectTimeout, readTimeout, downloads); } /** What the image's name says it holds: the distribution, by its checksum. */ String identity() { - return "pig " + sha256.toLowerCase(); + return distribution.identity(); } /** * Downloads the distribution to a temporary file, which the caller deletes, from the first URL that gives it whole - * with its SHA-256: one that cannot be reached, answers otherwise, stalls for {@link #READ_TIMEOUT} or gives another - * checksum passes to the next, so nothing goes into an image before it has been checked. + * with its SHA-256 ({@link ApacheDistribution#download}). */ Path download() throws IOException { - List failures = new ArrayList<>(); - for (URI url : urls) { - Path file = Files.createTempFile(downloads, "floci-pig-", ".tar.gz"); - try { - fetch(url, file); - return file; - } catch (IOException e) { - Files.deleteIfExists(file); - failures.add(url + ": " + e.getMessage()); - } - } - throw new IOException("Could not download Apache Pig: " + (failures.isEmpty() ? "no URL is set" - : String.join("; ", failures))); - } - - private void fetch(URI url, Path file) throws IOException { - MessageDigest digest = sha256Digest(); - HttpURLConnection connection = (HttpURLConnection) url.toURL().openConnection(); - connection.setConnectTimeout((int) connectTimeout.toMillis()); - connection.setReadTimeout((int) readTimeout.toMillis()); - try { - int status = connection.getResponseCode(); - if (status != HttpURLConnection.HTTP_OK) { - throw new IOException("answered " + status); - } - try (InputStream in = new DigestInputStream(connection.getInputStream(), digest); - OutputStream out = Files.newOutputStream(file)) { - in.transferTo(out); - } - } finally { - connection.disconnect(); - } - String found = HexFormat.of().formatHex(digest.digest()); - if (!found.equalsIgnoreCase(sha256)) { - throw new IOException("has the SHA-256 " + found + ", not the " + sha256 - + " floci.services.emr.pig.sha256 names"); - } + return distribution.download(); } /** @@ -146,69 +87,12 @@ public class PigDistribution { * {@link #ENVIRONMENT} as its {@code pig-env.sh}. */ static void write(Path download, OutputStream out) throws IOException { - try (InputStream raw = Files.newInputStream(download); - GZIPInputStream gzip = new GZIPInputStream(raw, BUFFER_BYTES); - TarArchiveInputStream in = new TarArchiveInputStream(gzip); - TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) { - TarArchiveEntry entry; - while ((entry = in.getNextEntry()) != null) { - String path = kept(entry.getName()); - if (path == null || entry.isLink() && kept(entry.getLinkName()) == null) { - continue; - } - entry.setName(path); - if (entry.isLink()) { - entry.setLinkName(kept(entry.getLinkName())); - } - entry.setIds(0, 0); - entry.setNames("root", "root"); - tar.putArchiveEntry(entry); - in.transferTo(tar); - tar.closeArchiveEntry(); - } - TarArchiveEntry environment = new TarArchiveEntry(ENVIRONMENT_FILE); - byte[] lines = ENVIRONMENT.getBytes(StandardCharsets.UTF_8); - environment.setSize(lines.length); - environment.setMode(0644); - environment.setIds(0, 0); - environment.setNames("root", "root"); - tar.putArchiveEntry(environment); - tar.write(lines); - tar.closeArchiveEntry(); - } - } - - private static MessageDigest sha256Digest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } + ApacheDistribution.write(LAYOUT, download, out); } // A path of the distribution, its own folder first, under NAME, or null for one Pig does not run from, or that // leaves the folder. static String kept(String path) { - if (path == null || path.startsWith("/")) { - return null; - } - int slash = path.indexOf('/'); - if (slash < 0) { - return null; - } - String rest = path.substring(slash + 1); - for (String segment : rest.split("/")) { - if (segment.equals("..")) { - return null; - } - } - if (rest.isEmpty()) { - return NAME + "/"; - } - int folderEnd = rest.indexOf('/'); - boolean kept = folderEnd < 0 - ? KEPT_FILES.contains(rest) || rest.endsWith(".jar") - : KEPT_FOLDERS.contains(rest.substring(0, folderEnd)) && LEFT_OUT.stream().noneMatch(rest::startsWith); - return kept ? NAME + "/" + rest : null; + return LAYOUT.kept(path); } } diff --git a/src/test/java/io/floci/aws/services/emr/ApacheDistributionTest.java b/src/test/java/io/floci/aws/services/emr/ApacheDistributionTest.java new file mode 100644 index 0000000000..4319313a36 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/ApacheDistributionTest.java @@ -0,0 +1,172 @@ +package io.floci.aws.services.emr; + +import com.sun.net.httpserver.HttpServer; +import io.floci.aws.testing.ParallelLocks; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.zip.GZIPOutputStream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +// It serves its downloads on a loopback port of its own. +@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) +class ApacheDistributionTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(5); + // A layout that keeps no top-level jar and writes two files of its own, as ZooKeeper's and HBase's will. + private static final ApacheDistribution.Layout LAYOUT = new ApacheDistribution.Layout("/usr/lib", "zookeeper", + Set.of("bin", "lib"), Set.of("LICENSE.txt"), false, List.of("lib/skipped/"), written()); + + @TempDir + Path downloads; + private HttpServer server; + private byte[] distribution; + + @BeforeEach + void serve() throws IOException { + distribution = gzippedTar(Map.of("zookeeper-3.9.3/bin/zkServer.sh", "#!/bin/sh", + "zookeeper-3.9.3/lib/zookeeper.jar", "classes", "zookeeper-3.9.3/lib/skipped/old.jar", "old", + "zookeeper-3.9.3/top.jar", "jar", "zookeeper-3.9.3/docs/index.html", "docs", + "zookeeper-3.9.3/LICENSE.txt", "licence")); + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/zookeeper.tar.gz", exchange -> { + exchange.sendResponseHeaders(200, distribution.length); + try (OutputStream body = exchange.getResponseBody()) { + body.write(distribution); + } + }); + server.start(); + } + + @AfterEach + void stop() { + server.stop(0); + } + + @Test + void aDistributionIsCheckedWithTheDigestItsProjectPublishes() throws Exception { + Path downloaded = distribution(sha512(distribution)).download(); + + try { + assertArrayEquals(distribution, Files.readAllBytes(downloaded)); + } finally { + Files.deleteIfExists(downloaded); + } + } + + @Test + void anotherDigestFailsTheDownloadNamingItsAlgorithmAndSetting() { + String expected = "0".repeat(128); + + IOException failed = assertThrows(IOException.class, () -> distribution(expected).download()); + + assertEquals("Could not download Apache ZooKeeper: " + url() + ": has the SHA-512 " + sha512(distribution) + + ", not the " + expected + " example.sha512 names", failed.getMessage()); + } + + @Test + void theImageNamesItByItsChecksum() { + assertEquals("zookeeper " + "ab".repeat(64), distribution("AB".repeat(64)).identity()); + } + + @Test + void aLayoutKeepsItsFoldersAndFilesAloneThenWritesItsOwnFiles(@TempDir Path folder) throws Exception { + Path download = folder.resolve("zookeeper.tar.gz"); + Files.write(download, distribution); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + ApacheDistribution.write(LAYOUT, download, out); + + // No top-level jar, no docs and nothing under a folder left out; Floci's files after the distribution's. + Map entries = entries(out.toByteArray()); + assertEquals(List.of("zookeeper/LICENSE.txt", "zookeeper/bin/zkServer.sh", "zookeeper/lib/zookeeper.jar", + "zookeeper/conf/zoo.cfg", "zookeeper/conf/java.env"), List.copyOf(entries.keySet())); + assertEquals("tickTime=2000\n", entries.get("zookeeper/conf/zoo.cfg")); + assertEquals("/usr/lib/zookeeper", LAYOUT.home()); + } + + private ApacheDistribution distribution(String sha512) { + return new ApacheDistribution("Apache ZooKeeper", LAYOUT, List.of(url()), "SHA-512", sha512, + "example.sha512", TIMEOUT, TIMEOUT, downloads); + } + + private String url() { + return "http://127.0.0.1:" + server.getAddress().getPort() + "/zookeeper.tar.gz"; + } + + private static Map written() { + Map written = new LinkedHashMap<>(); + written.put("conf/zoo.cfg", "tickTime=2000\n"); + written.put("conf/java.env", "export JVMFLAGS=-Xmx512m\n"); + return written; + } + + private static String sha512(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-512").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + // A gzipped tar of files, by path, in a stable order. + private static byte[] gzippedTar(Map files) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (TarArchiveOutputStream tar = new TarArchiveOutputStream(new GZIPOutputStream(bytes))) { + for (String path : files.keySet().stream().sorted().toList()) { + byte[] content = files.get(path).getBytes(StandardCharsets.UTF_8); + TarArchiveEntry entry = new TarArchiveEntry(path); + entry.setSize(content.length); + tar.putArchiveEntry(entry); + tar.write(content); + tar.closeArchiveEntry(); + } + } + return bytes.toByteArray(); + } + + // What an archive holds, by path, in its order, each entry owned by root and Floci's readable by everyone. + private static Map entries(byte[] archive) throws IOException { + Map entries = new LinkedHashMap<>(); + try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) { + TarArchiveEntry entry; + while ((entry = in.getNextEntry()) != null) { + assertEquals("root", entry.getUserName()); + if (entry.getName().startsWith("zookeeper/conf/")) { + assertEquals(0644, entry.getMode() & 0777); + } + assertTrue(entry.getName().startsWith("zookeeper/"), entry.getName()); + entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } + } + return entries; + } +}