feat(emr): run s3-dist-cp steps (#7192)

In the docker runner mode an s3-dist-cp step, the Release Guide's way of
moving data "from Amazon S3 into HDFS where it can be processed by
subsequent steps", between buckets or back to S3, was FAILED without
running, and on the default TERMINATE_CLUSTER it ended its cluster with
errors. The EMR Serverless image steps run in has neither s3-dist-cp nor
the MapReduce it runs on.

Now a command-runner.jar step whose first argument is s3-dist-cp runs
Floci's own S3DistCp: a Python program, emr/s3-dist-cp.py, which the step's
command writes into the container and runs through spark-submit, copying
through Hadoop's file systems in Spark's JVM. The command wrapper gives it
what a Spark step gets: S3 paths in Floci's S3 and hdfs:// paths, and
those without a scheme, in the cluster's HDFS. It takes the options of
the Release Guide's table, --name=value or --name value, and -D
property=value:

- --src and --dest, a source folder's files keeping their folders;
- --srcPattern and --groupBy matched against the whole path; --groupBy
  concatenates the files whose groups give the same name into one file
  named by them, and refuses an expression with no group, as the guide
  says S3DistCp does; --targetSize breaks a larger group into parts
  numbered before the extension ("myfile0.gz, myfile1.gz"); without
  --outputCodec a group keeps the compression its files share, named
  with that codec's extension, or has none when they differ, each file
  decompressed so the group is one stream;
- --outputCodec (gzip, gz, lzo, lzop, snappy, none) through Hadoop's
  codecs, each source decompressed by its own extension;
- --deleteOnSuccess, deleting the files but not their folders, as AWS's
  "Seven tips for using S3DistCp" says;
- --outputManifest, --previousManifest, --requirePreviousManifest and
  --copyFromManifest, the manifest gzipped JSON lines of path, baseName,
  srcDir and size, as that post shows them;
- --s3ServerSideEncryption, --storageClass, --disableMultipartUpload and
  --multipartUploadChunkSize as S3A's settings; --numberFiles,
  --startingIndex, --srcPrefixesFile and --appendToLastFile, the last
  through a copy renamed over the file, as neither S3 nor the cluster's
  HDFS appends in place. The copy has a name of its own and goes if the
  writing fails, and the file steps aside, under a name of its own too,
  until the copy has taken its place, coming back if it cannot, so a
  failed append leaves it as it was. --s3Endpoint is ignored, S3 being
  Floci's.

--requirePreviousManifest takes true or false, after = or as the next
argument, and alone is true, its default. A --srcPrefixesFile line ending
in / names that folder alone, its slash kept though Hadoop's Path drops
it; any other is a prefix as S3 lists one, logs/day taking in
logs/day-old/.

A bucket name with an underscore fails the step, as S3DistCp "does not
support" one, and so does a copy Hadoop fails, leaving what was copied.
A copy that would write two files to the same path, the manifest
included (a.log and a.log.gz with --outputCodec=gzip), a file over one
of its own sources, as with the same --src and --dest, or a file outside
--dest, through a .. in a manifest's baseName or in --outputManifest
(Hadoop's paths resolve it), or a file with no name, from a --groupBy
whose groups matched nothing say, fails before it writes anything. emr.md
says what is Floci's own reading: the grouped file's folder,
--numberFiles' naming, a group's compression without --outputCodec and
that refusal.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-01 10:10:13 -06:00
1 parent beef71e8eb
commit a74a9b0ffc
7 files changed
+973 -14

No files matched your search

+39 -3
View File
@@ -120,9 +120,9 @@ but for its bootstrap actions and its storage.
`spark-submit`, with the JAR and the step's `Args`. Any other `command-runner.jar` step runs its
command, its first argument, with the rest, and a `script-runner.jar` step (by name, or by its
`s3://<region>.elasticmapreduce/libs/script-runner/script-runner.jar` URI) its script, as the Release
Guide's "Run commands and scripts on an Amazon EMR cluster" describes them. `hive-script`,
`pig-script`, `hadoop-streaming`, `hadoop-lzo` and `s3-dist-cp`, which the image does not have, are
`FAILED` without running.
Guide's "Run commands and scripts on an Amazon EMR cluster" describes them. An `s3-dist-cp` step runs
Floci's own S3DistCp (see **S3DistCp**). `hive-script`, `pig-script`, `hadoop-streaming` and
`hadoop-lzo`, which the image does not have, are `FAILED` without running.
* **Commands and scripts**: they run as the image's `hadoop` user in `/home/hadoop`, with `bash`, Python
3, Java, `curl` and the AWS CLI v2, which reaches Floci through `AWS_ENDPOINT_URL`. A
`script-runner.jar` step's script is fetched from S3 with the AWS CLI and the step's credentials, then
@@ -151,6 +151,42 @@ but for its bootstrap actions and its storage.
`hdfs://` path naming a host is not served, `hadoop fs -ls /` fails ("URI scheme is not "file""), where
`-ls -d /` and a folder below it do not, and `hadoop fs` does not reach S3, as its classpath has no AWS
SDK v2 and the image's EMRFS is not pointed at Floci (`aws s3 cp` does). `/tmp` is each container's own.
* **S3DistCp**: the image has neither `s3-dist-cp` nor MapReduce, so a `command-runner.jar` step whose
first argument is `s3-dist-cp`, the Release Guide's form, runs Floci's own program instead, through
`spark-submit` in the step's container, copying through Hadoop's file systems: `--src` and `--dest` take
S3 paths in Floci's S3, the cluster's HDFS (`hdfs:///output`, or a path without a scheme) or a file of
the container, a source folder's files keeping their folders under `--dest`. It takes the Release
Guide's options, `--name=value` or `--name value`, and `-D property=value`. `--srcPattern` and
`--groupBy` match the whole source path, as Python regular expressions, which share Java's common
syntax. `--groupBy` concatenates the files whose groups give the same name, which is the groups' text,
into the folder of the first of them, and refuses a regular expression with no group, as S3DistCp does;
`--targetSize` breaks a group larger than it into parts named with a number before the extension.
`--outputCodec` (`gzip`, `gz`, `lzo`, `lzop`, `snappy`, or `none` to decompress) decompresses each
source by its own extension and replaces that extension with the codec's; without it a file's
compression stays as it is, and a group keeps the compression its files share, named with that codec's
extension, or has none when they differ, each file decompressed so that the group is one stream.
`--deleteOnSuccess` deletes the copied files, but not their folders, once
all are copied. `--outputManifest` writes gzipped JSON lines (`path`, `baseName`, `srcDir`, `size`) to
`--dest`; `--previousManifest` leaves out the files it names by `baseName`, and fails the step when it
is not there unless `--requirePreviousManifest` is `false` (`=false` or `false` after it);
`--copyFromManifest` copies the files it names. `--srcPrefixesFile` copies the files under each of its
lines instead of listing `--src`, a line ending in `/` naming that folder alone and any other a prefix as
S3 lists one (`logs/day` takes in `logs/day-old/`).
`--s3ServerSideEncryption`, `--storageClass`, `--disableMultipartUpload` and
`--multipartUploadChunkSize` set S3A's matching settings; `--s3Endpoint` is ignored, as S3 is Floci's. A
bucket name with an underscore fails the step, as S3DistCp "does not support" one, and so does a copy
Hadoop fails, leaving what was copied, as S3DistCp does. `--appendToLastFile` puts the new data after
what a destination file holds, through a copy renamed over it, as neither S3 nor the cluster's HDFS, a
folder, appends in place. The copy has a name of its own and goes if the writing fails; the file steps
aside, under a name of its own too, until the copy has taken its place, and comes back if it cannot, so a
failed append leaves it as it was. A copy that would write two files to the same path, the manifest included
(`a.log` and `a.log.gz` with `--outputCodec=gzip`, say), a file over one of its own sources, as with the
same `--src` and `--dest`, a file outside `--dest`, through a `..` in a manifest's `baseName` or in
`--outputManifest`, or a file with no name, from a `--groupBy` whose groups matched nothing, say, fails
before it writes anything. A step's log has one line saying what was copied.
Floci's own readings, as no source says: the grouped file's folder, `--numberFiles` putting the number
straight before the file's name, a group's compression without `--outputCodec`, and failing a copy that
would write over its own output or source, or outside `--dest`.
* **HTTPS**: with [TLS](../configuration/tls.md) on, each step's container, and the bootstrap actions'
one, also gets Floci's CA bundle as a Java trust store, which every JVM in it uses, as an
[EMR Serverless job run](emr-serverless.md#running-spark-job-runs)'s do, so Java code reaches Floci
@@ -7,6 +7,10 @@ import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -19,13 +23,13 @@ import java.util.Set;
* {@code spark-submit}, as the Management Guide's Spark steps are written, and a custom JAR step, whose main
* class {@code spark-submit} runs with the JAR on its class path. Any other {@code command-runner.jar} step
* runs its command, and a {@code script-runner.jar} step its script, as the Release Guide's "Run commands
* and scripts on an Amazon EMR cluster" describes them.
* and scripts on an Amazon EMR cluster" describes them; an {@code s3-dist-cp} one runs Floci's own S3DistCp.
*/
final class EmrSparkSteps {
// No source gives AWS's wording for these; they are Floci's.
static final String NOT_RUN = "Floci does not run this step: hive-script, pig-script, hadoop-streaming,"
+ " hadoop-lzo and s3-dist-cp are not in the image steps run in.";
static final String NOT_RUN = "Floci does not run this step: hive-script, pig-script, hadoop-streaming and"
+ " hadoop-lzo are not in the image steps run in.";
static final String INTERRUPTED = "Floci stopped while the step was running.";
private static final String COMMAND_RUNNER = "command-runner.jar";
@@ -46,9 +50,13 @@ final class EmrSparkSteps {
// Spark puts a spark.hadoop. setting in the Hadoop configuration its Hive client reads, ahead of hive-site.xml.
private static final String SPARK_HADOOP_PREFIX = "spark.hadoop.";
// The Release Guide's command-runner.jar tools that the EMR Serverless image does not have; its hadoop
// has no HDFS to run streaming or the LZO indexer against.
// has no MapReduce to run streaming or the LZO indexer.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("hive-script", "pig-script", "hadoop-streaming",
"hadoop-lzo", "s3-dist-cp");
"hadoop-lzo");
private static final String S3_DIST_CP = "s3-dist-cp";
static final String S3_DIST_CP_RESOURCE = "emr/s3-dist-cp.py";
// The line that ends the program where the command writes it out.
static final String S3_DIST_CP_END = "FLOCI_S3_DIST_CP";
// script-runner.jar fetches its script from S3 with the step's credentials, the image's AWS CLI reaching
// Floci's S3, and runs it with its arguments; a path that is not in S3 is run as it is, a bare name from
// the working directory when a file there has it, as exec would otherwise look for it on the PATH only.
@@ -105,7 +113,8 @@ final class EmrSparkSteps {
/**
* The command a step that is not a Spark step runs, or null for one Floci does not run: a
* {@code command-runner.jar} step's arguments, its command first, unless it names a tool the image does
* not have; a {@code script-runner.jar} step's script, the first of its arguments, with the rest.
* not have; Floci's S3DistCp with the arguments of an {@code s3-dist-cp} one; a {@code script-runner.jar}
* step's script, the first of its arguments, with the rest.
*/
static List<String> command(EmrStep step) {
String jar = step.getJar();
@@ -114,6 +123,11 @@ final class EmrSparkSteps {
return null;
}
if (named(jar, COMMAND_RUNNER)) {
if (S3_DIST_CP.equals(args.getFirst())) {
List<String> command = new ArrayList<>(List.of("bash", "-c", S3DistCp.COMMAND, S3_DIST_CP));
command.addAll(args.subList(1, args.size()));
return command;
}
return named(args.getFirst(), SPARK_SUBMIT) || UNAVAILABLE_TOOLS.contains(args.getFirst())
? null : List.copyOf(args);
}
@@ -211,6 +225,32 @@ final class EmrSparkSteps {
return kept;
}
/**
* Floci's S3DistCp: the image has neither {@code s3-dist-cp} nor MapReduce, so the command writes Floci's
* program into the container and runs it through {@code spark-submit}, which the command wrapper gives
* Floci's S3 and the cluster's HDFS. Read once, when the first {@code s3-dist-cp} step comes.
*/
private static final class S3DistCp {
static final String COMMAND = String.join("\n",
"program=\"${TMPDIR:-/tmp}/floci-s3-dist-cp.py\"",
"cat > \"$program\" <<'" + S3_DIST_CP_END + "'",
program(),
S3_DIST_CP_END,
"exec spark-submit --conf spark.ui.enabled=false \"$program\" \"$@\"");
private static String program() {
try (InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(S3_DIST_CP_RESOURCE)) {
if (in == null) {
throw new IllegalStateException(S3_DIST_CP_RESOURCE + " is missing from the classpath");
}
return new String(in.readAllBytes(), StandardCharsets.UTF_8).stripTrailing();
} catch (IOException e) {
throw new UncheckedIOException("Could not read " + S3_DIST_CP_RESOURCE, e);
}
}
}
// command-runner.jar is named alone; a path such as /usr/bin/spark-submit names spark-submit too.
private static boolean named(String path, String name) {
return path.equals(name) || path.endsWith("/" + name);
+3 -1
View File
@@ -66,7 +66,8 @@ quarkus:
# catalog (sagemaker/instance-type-catalog.yaml), KMS reads its AWS managed
# key catalog (kms/aws-managed-keys.yaml), AppSync's GraphQL
# parser reads its message bundles, Lambda Web Functions copy their
# runtime (lambdaweb/index.mjs) into each environment, EC2 security group enforcement builds
# runtime (lambdaweb/index.mjs) into each environment, EMR writes its S3DistCp program
# (emr/s3-dist-cp.py) into a step's container, EC2 security group enforcement builds
# its helper image from docker/*.Dockerfile, and API Gateway's Velocity
# engine reads its default properties at runtime via
# ClassLoader#getResourceAsStream. Quarkus's static resource analysis
@@ -82,6 +83,7 @@ quarkus:
- ui/*.html
- appsync/*.mjs
- lambdaweb/*.mjs
- emr/*.py
- ec2/*.yaml
- docker/*.Dockerfile
- sagemaker/*.yaml
+457
View File
@@ -0,0 +1,457 @@
"""Floci's s3-dist-cp, for an EMR step in the docker runner mode.
The EMR Serverless image a step runs in has neither s3-dist-cp nor MapReduce, so this copies through Hadoop's
FileSystem API in the step's container, under spark-submit, where S3 paths reach Floci's S3 and hdfs:// paths,
and paths without a scheme, the cluster's HDFS, as they do for a Spark step. It takes the options of the Release
Guide's "S3DistCp options" table and the generic -D option; planning what goes where is kept apart from the
copying, so it runs without Spark.
"""
import gzip
import json
import re
import sys
import uuid
VALUE_OPTIONS = {"src", "dest", "srcPattern", "groupBy", "targetSize", "outputCodec", "multipartUploadChunkSize",
"startingIndex", "outputManifest", "previousManifest", "s3Endpoint", "storageClass",
"srcPrefixesFile"}
FLAG_OPTIONS = {"appendToLastFile", "s3ServerSideEncryption", "deleteOnSuccess", "disableMultipartUpload",
"numberFiles", "copyFromManifest", "requirePreviousManifest"}
# The codecs --outputCodec takes, by the class Hadoop knows each by; none decompresses.
OUTPUT_CODECS = {
"gzip": "org.apache.hadoop.io.compress.GzipCodec",
"gz": "org.apache.hadoop.io.compress.GzipCodec",
"lzo": "com.hadoop.compression.lzo.LzopCodec",
"lzop": "com.hadoop.compression.lzo.LzopCodec",
"snappy": "org.apache.hadoop.io.compress.SnappyCodec",
"none": None,
}
STORAGE_CLASSES = {"STANDARD", "REDUCED_REDUNDANCY"}
MIB = 1024 * 1024
class UsageError(Exception):
pass
def parse(argv):
"""The options, as a dict, and the -D Hadoop settings, as a list of pairs."""
options = {}
settings = []
i = 0
while i < len(argv):
arg = argv[i]
if arg == "-D" or (arg.startswith("-D") and not arg.startswith("--")):
setting = argv[i + 1] if arg == "-D" and i + 1 < len(argv) else arg[2:]
i += 2 if arg == "-D" else 1
key, equals, value = setting.partition("=")
if not equals or not key:
raise UsageError("-D takes a property=value setting, not " + setting)
settings.append((key, value))
continue
if not arg.startswith("--"):
raise UsageError("Unexpected argument " + arg)
name, equals, value = arg[2:].partition("=")
if name in FLAG_OPTIONS and name not in VALUE_OPTIONS:
if name == "requirePreviousManifest":
# True or false, in either form; alone it is true, its default.
if not equals and i + 1 < len(argv) and argv[i + 1].lower() in ("true", "false"):
i += 1
value, equals = argv[i], "="
if equals and value.lower() not in ("true", "false"):
raise UsageError("--requirePreviousManifest takes true or false, not " + value)
options[name] = not equals or value.lower() == "true"
elif equals:
raise UsageError("--" + name + " takes no value")
else:
options[name] = True
i += 1
elif name in VALUE_OPTIONS:
if not equals:
if i + 1 >= len(argv):
raise UsageError("--" + name + " takes a value")
value = argv[i + 1]
i += 1
options[name] = value
i += 1
else:
raise UsageError("Unknown option --" + name)
for required in ("src", "dest"):
if not options.get(required):
raise UsageError("--" + required + " is required")
if "outputCodec" in options and options["outputCodec"].lower() not in OUTPUT_CODECS:
raise UsageError("--outputCodec takes gzip, gz, lzo, lzop, snappy or none, not " + options["outputCodec"])
if "storageClass" in options and options["storageClass"] not in STORAGE_CLASSES:
raise UsageError("--storageClass takes STANDARD or REDUCED_REDUNDANCY, not " + options["storageClass"])
for number in ("targetSize", "multipartUploadChunkSize", "startingIndex"):
if number in options and not re.fullmatch(r"\d+", options[number]):
raise UsageError("--" + number + " takes a whole number, not " + options[number])
if "groupBy" in options and re.compile(options["groupBy"]).groups == 0:
raise UsageError("The --groupBy regular expression " + options["groupBy"]
+ " has no parenthetical group to name the concatenated files by")
for location in (options["src"], options["dest"]):
bucket = s3_bucket(location)
if bucket is not None and "_" in bucket:
raise UsageError("S3DistCp does not support Amazon S3 bucket names that contain the underscore"
" character: " + location)
return options, settings
def s3_bucket(location):
match = re.match(r"(?i)s3[an]?://([^/]*)", location)
return match.group(1) if match else None
def prefix_start(prefix, path):
"""What a file's path starts with to be under a --srcPrefixesFile line, from the line and the path Hadoop's Path
makes of it, which drops a trailing slash: a line ending in one names that folder alone, so the slash comes
back; any other is a prefix as S3 lists one, which logs/day-old/ matches as logs/day/ does."""
return path.rstrip("/") + "/" if prefix.endswith("/") else path
def split_name(name, extension):
"""A file name as its stem and the codec extension it ends in, if it does."""
if extension and name.endswith(extension) and len(name) > len(extension):
return name[:-len(extension)], extension
return name, ""
def plan(files, options, extensions, output_extension):
"""What the copy writes: a list of outputs, each a target path relative to --dest and the source files that
go into it, in order. files are (path, relative path, size) triples, relative to --src; extensions maps a
source's path to the extension of the codec its name ends in ("" for none); output_extension is
--outputCodec's extension, "" for none, or None when it is not given, which leaves each file's compression
as it is and gives a group the one its files share (see group_extension)."""
pattern = re.compile(options["srcPattern"]) if "srcPattern" in options else None
files = [f for f in sorted(files, key=lambda f: f[1]) if pattern is None or pattern.fullmatch(f[0])]
outputs = []
if "groupBy" in options:
group_by = re.compile(options["groupBy"])
groups = {}
for f in files:
match = group_by.fullmatch(f[0])
if match:
groups.setdefault("".join(g or "" for g in match.groups()), []).append(f)
target_size = int(options["targetSize"]) * MIB if "targetSize" in options else None
for name, members in groups.items():
folder = members[0][1].rpartition("/")[0]
parts = split_parts(members, target_size)
extension = group_extension(members, extensions, output_extension)
# A name that ends in the extension already keeps one, the part's number before it.
name = split_name(name, extension)[0]
for index, part in enumerate(parts):
stem = name + (str(index) if len(parts) > 1 else "")
outputs.append((join(folder, stem + extension), part))
else:
for f in files:
folder, _, name = f[1].rpartition("/")
if output_extension is not None:
name = split_name(name, extensions.get(f[0], ""))[0] + output_extension
outputs.append((join(folder, name), [f]))
if options.get("numberFiles"):
start = int(options.get("startingIndex", "0"))
numbered = []
for index, (target, sources) in enumerate(outputs):
folder, _, name = target.rpartition("/")
numbered.append((join(folder, str(start + index) + name), sources))
outputs = numbered
return outputs
def check_targets(outputs, dest, manifest, qualify):
"""Refuses a copy that would lose data before it writes anything: an output, the manifest included, outside
--dest, through a .. in a manifest's baseName say, which Hadoop's paths resolve; one with no file name; two at
the same path, the second replacing the first; or one over one of its own sources, which creating it would empty
before it is read. qualify gives a location as its file system names it."""
sources = {qualify(f[0]) for _, files in outputs for f in files}
targets = [(target, ", ".join(f[1] for f in files)) for target, files in outputs]
if manifest is not None:
targets.append((manifest, "the manifest"))
written = {}
for target, what in targets:
if ".." in target.split("/"):
raise UsageError(target + " leads out of --dest " + dest)
if target.rpartition("/")[2] in ("", "."):
# A group whose groups matched nothing, say: Hadoop's paths would make the file its folder.
raise UsageError(what + " would be written to " + located(dest, target) + ", which names no file")
location = qualify(located(dest, target))
if location in written:
raise UsageError(written[location] + " and " + what + " would both be written to " + location)
if location in sources:
raise UsageError(what + " would be written over its source " + location)
written[location] = what
def replace(fs, staged, target, aside):
"""Puts staged in target's place through renames, as Hadoop's FileSystem has no public rename that replaces an
existing file: target steps aside first, to aside, a name of its own, and comes back if staged cannot take its
place, so it is never lost; a step stopped between the renames leaves both under their own names."""
if not fs.rename(target, aside):
raise IOError("Could not move " + str(target) + " aside to replace it")
if not fs.rename(staged, target):
restored = fs.rename(aside, target)
raise IOError("Could not rename " + str(staged) + " to " + str(target)
+ ("" if restored else "; what it held is at " + str(aside)))
fs.delete(aside, False)
def group_extension(members, extensions, output_extension):
"""The extension of a group's file: --outputCodec's, or without it the one its files share, none when they
differ. The copy decompresses each file and writes the group as that extension's codec, so its bytes are one
stream its name tells the format of, whatever its files' compression."""
if output_extension is not None:
return output_extension
shared = {extensions.get(f[0], "") for f in members}
return shared.pop() if len(shared) == 1 else ""
def split_parts(members, target_size):
"""A group's files as the parts --targetSize breaks it into, each as close to the size as whole files make it."""
if target_size is None:
return [members]
parts = [[]]
size = 0
for f in members:
if parts[-1] and size + f[2] > target_size:
parts.append([])
size = 0
parts[-1].append(f)
size += f[2]
return parts
def files_word(count):
return "file" if count == 1 else "files"
def join(folder, name):
return folder + "/" + name if folder else name
def located(folder, relative):
# One string, so a colon in a file's name is not read as a scheme.
return folder.rstrip("/") + "/" + relative
def manifest_line(path, base_name, src_dir, size):
return json.dumps({"path": path, "baseName": base_name, "srcDir": src_dir, "size": size},
separators=(",", ":"))
class Copier:
"""The copy itself, through Hadoop's FileSystem API in Spark's JVM."""
def __init__(self, options, settings):
from pyspark.sql import SparkSession
self.options = options
self.spark = SparkSession.builder.appName("S3DistCp").getOrCreate()
self.jvm = self.spark._jvm
self.conf = self.spark._jsc.hadoopConfiguration()
for key, value in settings:
self.conf.set(key, value)
if options.get("s3ServerSideEncryption"):
self.conf.set("fs.s3a.encryption.algorithm", "SSE-S3")
if "storageClass" in options:
self.conf.set("fs.s3a.create.storage.class", options["storageClass"].lower())
if options.get("disableMultipartUpload"):
self.conf.set("fs.s3a.multipart.uploads.enabled", "false")
if "multipartUploadChunkSize" in options:
self.conf.set("fs.s3a.multipart.size", options["multipartUploadChunkSize"] + "M")
self.codecs = self.jvm.org.apache.hadoop.io.compress.CompressionCodecFactory(self.conf)
def path(self, location):
path = self.jvm.org.apache.hadoop.fs.Path(location)
fs = path.getFileSystem(self.conf)
return fs, fs.makeQualified(path)
def under(self, folder, relative):
return self.jvm.org.apache.hadoop.fs.Path(located(folder.toString(), relative))
def files(self, fs, root):
"""Every file under root, or root itself when it is one, as (path, relative path, size)."""
status = fs.getFileStatus(root)
if status.isFile():
return [(status.getPath().toString(), status.getPath().getName(), status.getLen())]
base = root.toUri().getPath().rstrip("/") + "/"
found = []
listing = fs.listFiles(root, True)
while listing.hasNext():
status = listing.next()
found.append((status.getPath().toString(), status.getPath().toUri().getPath()[len(base):],
status.getLen()))
return found
def prefixed(self, src_fs, src, prefixes):
"""The files under each prefix, relative to --src."""
base = src.toUri().getPath().rstrip("/") + "/"
found = {}
for prefix in prefixes:
fs, path = self.path(prefix)
start = prefix_start(prefix, path.toUri().getPath())
folder = path if start.endswith("/") or path.getParent() is None else path.getParent()
listing = fs.listFiles(folder, True)
while listing.hasNext():
status = listing.next()
file_path = status.getPath().toUri().getPath()
if file_path.startswith(start):
relative = file_path[len(base):] if file_path.startswith(base) else status.getPath().getName()
found[status.getPath().toString()] = (status.getPath().toString(), relative, status.getLen())
return list(found.values())
def read_lines(self, location, gzipped):
fs, path = self.path(location)
stream = fs.open(path)
try:
data = bytes(self.jvm.org.apache.commons.io.IOUtils.toByteArray(stream))
finally:
stream.close()
text = gzip.decompress(data).decode("utf-8") if gzipped else data.decode("utf-8")
return [line.strip() for line in text.splitlines() if line.strip()]
def write_bytes(self, fs, path, data):
out = fs.create(path, True)
try:
out.write(bytearray(data))
finally:
out.close()
def extension_of(self, path):
codec = self.codecs.getCodec(self.jvm.org.apache.hadoop.fs.Path(path))
return codec.getDefaultExtension() if codec is not None else ""
def run(self):
options = self.options
src_fs, src = self.path(options["src"])
dest_fs, dest = self.path(options["dest"])
manifest = []
previous = []
if "previousManifest" in options:
prev_fs, prev = self.path(options["previousManifest"])
if prev_fs.exists(prev):
previous = [json.loads(line) for line in self.read_lines(options["previousManifest"], True)]
elif options.get("requirePreviousManifest", True):
raise UsageError("The previous manifest " + options["previousManifest"] + " does not exist")
if options.get("copyFromManifest"):
if "previousManifest" not in options:
raise UsageError("--copyFromManifest needs --previousManifest")
files = [(entry["path"], entry["baseName"], int(entry.get("size", 0))) for entry in previous]
else:
if "srcPrefixesFile" in options:
files = self.prefixed(src_fs, src, self.read_lines(options["srcPrefixesFile"], False))
elif src_fs.exists(src):
files = self.files(src_fs, src)
else:
raise UsageError("--src " + options["src"] + " does not exist")
copied_before = {entry["baseName"] for entry in previous}
files = [f for f in files if f[1] not in copied_before]
manifest.extend(manifest_line(e["path"], e["baseName"], e.get("srcDir", ""), int(e.get("size", 0)))
for e in previous)
codec_name = options.get("outputCodec", "").lower() or None
output_codec = None
output_extension = None
if codec_name is not None:
output_extension = ""
if OUTPUT_CODECS[codec_name] is not None:
output_codec = self.codecs.getCodecByClassName(OUTPUT_CODECS[codec_name])
if output_codec is None:
raise UsageError("The " + codec_name + " codec is not available")
output_extension = output_codec.getDefaultExtension()
extensions = {f[0]: self.extension_of(f[0]) for f in files}
outputs = plan(files, options, extensions, output_extension)
check_targets(outputs, dest.toString(), options.get("outputManifest"),
lambda location: self.path(location)[1].toString())
copied_bytes = 0
for target, sources in outputs:
target_path = self.under(dest, target)
codec, recompress = output_codec, codec_name is not None
if codec_name is None and "groupBy" in options:
# A group's file is in the format its name's extension gives (see group_extension).
codec, recompress = self.codecs.getCodec(target_path), True
copied_bytes += self.write(dest_fs, target_path, sources, codec, recompress)
for f in sources:
manifest.append(manifest_line(f[0], f[1], src.toString(), f[2]))
if "outputManifest" in options:
data = gzip.compress(("\n".join(manifest) + "\n").encode("utf-8") if manifest else b"")
self.write_bytes(dest_fs, self.under(dest, options["outputManifest"]), data)
if options.get("deleteOnSuccess"):
for _, sources in outputs:
for f in sources:
fs, path = self.path(f[0])
fs.delete(path, False)
copied = sum(len(sources) for _, sources in outputs)
print("S3DistCp: copied %d %s (%d bytes) from %s to %s into %d %s"
% (copied, files_word(copied), copied_bytes, src.toString(), dest.toString(), len(outputs),
files_word(len(outputs))))
def write(self, dest_fs, target, sources, output_codec, recompress):
"""Writes sources, one after the other, to target, decompressed and compressed again when --outputCodec
is given, and returns the bytes read. With --appendToLastFile they follow what target holds, through a
copy that takes its place (see replace), as neither S3 nor the cluster's HDFS, a local folder, can append
in place; the copy has a name no other file has, and goes unless it took target's place."""
new_path = self.jvm.org.apache.hadoop.fs.Path
staged = None
if self.options.get("appendToLastFile") and dest_fs.exists(target):
staged = new_path(target.toString() + "." + uuid.uuid4().hex + "._COPYING_")
raw = dest_fs.create(staged, False)
else:
raw = dest_fs.create(target, True)
replaced = False
try:
read = self.fill(raw, dest_fs, target if staged is not None else None, sources, output_codec, recompress)
if staged is not None:
replace(dest_fs, staged, target,
new_path(target.toString() + "." + uuid.uuid4().hex + "._REPLACED_"))
replaced = True
finally:
if staged is not None and not replaced:
dest_fs.delete(staged, False)
return read
def fill(self, raw, dest_fs, existing, sources, output_codec, recompress):
"""Writes what existing holds, when there is one, then sources, to raw, and closes it; returns the bytes
read from sources."""
io_utils = self.jvm.org.apache.hadoop.io.IOUtils
out = raw
read = 0
try:
if existing is not None:
stream = dest_fs.open(existing)
try:
io_utils.copyBytes(stream, raw, self.conf, False)
finally:
stream.close()
if output_codec is not None:
out = output_codec.createOutputStream(raw)
for f in sources:
fs, path = self.path(f[0])
stream = fs.open(path)
try:
source_codec = self.codecs.getCodec(path) if recompress else None
if source_codec is not None:
stream = source_codec.createInputStream(stream)
io_utils.copyBytes(stream, out, self.conf, False)
finally:
stream.close()
read += f[2]
finally:
out.close()
return read
def main(argv):
try:
options, settings = parse(argv)
Copier(options, settings).run()
except UsageError as e:
print("S3DistCp: " + str(e), file=sys.stderr)
return 1
except Exception as e:
# A copy Hadoop failed, of a source that is not there say: what was copied stays, as S3DistCp leaves it.
java = getattr(e, "java_exception", None)
print("S3DistCp: " + (java.toString() if java is not None else str(e)), file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -280,6 +280,23 @@ class EmrServiceContainerStepsTest {
assertEquals(List.of(), runner.jobs);
}
@Test
void anS3DistCpStepRunsFlocisS3DistCpOnTheClustersStorage() {
EmrStep copy = sparkStep("copy", "CONTINUE");
copy.setArgs(new ArrayList<>(List.of("s3-dist-cp", "--src=s3://bucket/logs/", "--dest=hdfs:///output")));
EmrCluster cluster = service.runJobFlow(cluster("copying", true, copy), REGION);
fixture.runStepThread();
assertEquals("COMPLETED", service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId()).getState());
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(List.of("bash", "-c"), job.command().subList(0, 2));
assertEquals(List.of("s3-dist-cp", "--src=s3://bucket/logs/", "--dest=hdfs:///output"),
job.command().subList(3, job.command().size()));
assertEquals(List.of(), job.application());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
}
@Test
void describeStepAnswersAFailedStepsFailureDetails() {
EmrCluster cluster = service.runJobFlow(cluster("described", true, sparkStep("breaks", "CONTINUE")), REGION);
@@ -706,9 +723,9 @@ class EmrServiceContainerStepsTest {
@Test
void aClusterWhoseStepsNoContainerRanHasNoStorage() {
EmrStep copy = sparkStep("copy", "CONTINUE");
copy.setArgs(new ArrayList<>(List.of("s3-dist-cp", "--src=s3://bucket/in/", "--dest=hdfs:///in/")));
EmrCluster cluster = service.runJobFlow(cluster("unrun", true, copy), REGION);
EmrStep query = sparkStep("query", "CONTINUE");
query.setArgs(new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args", "-f", "s3://bucket/q.q")));
EmrCluster cluster = service.runJobFlow(cluster("unrun", true, query), REGION);
fixture.runStepThread();
service.terminateJobFlows(List.of(cluster.getId()));
@@ -6,12 +6,15 @@ import io.github.hectorvent.floci.services.lambda.launcher.BootstrapProcess;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -93,9 +96,37 @@ class EmrSparkStepsTest {
assertEquals(new BootstrapProcess.Result(0, "ran:--day|ran:1 2|"), ended);
}
@Test
void anS3DistCpStepWritesFlocisS3DistCpAndRunsItThroughSparkSubmit(@TempDir Path folder) throws Exception {
// The Release Guide's own S3DistCp step.
List<String> command = EmrSparkSteps.command(step("command-runner.jar", null, "s3-dist-cp",
"--s3Endpoint=s3.amazonaws.com", "--src=s3://bucket/logs/j-3GYXXXXXX9IOJ/node/",
"--dest=hdfs:///output", "--srcPattern=.*[a-zA-Z,]+"));
// A spark-submit that shows what it was given and keeps the program, in place of the image's.
Path sparkSubmit = folder.resolve("spark-submit");
Files.writeString(sparkSubmit, "#!/bin/sh\nprintf '%s|' \"$@\"\ncp \"$3\" " + folder.resolve("kept.py") + "\n");
assertTrue(sparkSubmit.toFile().setExecutable(true));
ProcessBuilder builder = new ProcessBuilder(command);
builder.environment().put("PATH", folder + ":" + System.getenv("PATH"));
builder.environment().put("TMPDIR", folder.toString());
BootstrapProcess.Result ended = BootstrapProcess.run(builder);
assertEquals(List.of("bash", "-c"), command.subList(0, 2));
assertEquals(new BootstrapProcess.Result(0, "--conf|spark.ui.enabled=false|" + folder + "/floci-s3-dist-cp.py|"
+ "--s3Endpoint=s3.amazonaws.com|--src=s3://bucket/logs/j-3GYXXXXXX9IOJ/node/|--dest=hdfs:///output|"
+ "--srcPattern=.*[a-zA-Z,]+|"), ended);
String program;
try (InputStream in = getClass().getClassLoader().getResourceAsStream(EmrSparkSteps.S3_DIST_CP_RESOURCE)) {
program = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
assertEquals(program.stripTrailing(), Files.readString(folder.resolve("kept.py")).stripTrailing());
assertFalse(program.lines().anyMatch(EmrSparkSteps.S3_DIST_CP_END::equals));
}
@Test
void toolsTheImageDoesNotHaveAreNotRun() {
for (String tool : List.of("hive-script", "pig-script", "hadoop-streaming", "hadoop-lzo", "s3-dist-cp")) {
for (String tool : List.of("hive-script", "pig-script", "hadoop-streaming", "hadoop-lzo")) {
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, tool, "--src", "s3://bucket/in/")));
}
assertNull(EmrSparkSteps.command(step("command-runner.jar", null)));
@@ -0,0 +1,376 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.launcher.BootstrapProcess;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Floci's S3DistCp program, its options and what it plans to write where, run by the host's {@code python3}: the
* planning needs no Spark, which only the copy itself runs under in a step's container.
*/
class S3DistCpProgramTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
// Loads the program, the file named first, as a module; each driver below goes on to print its answers as JSON.
private static final String LOAD_PROGRAM = """
import importlib.util, json, sys
spec = importlib.util.spec_from_file_location("s3distcp", sys.argv[1])
program = importlib.util.module_from_spec(spec)
spec.loader.exec_module(program)
""";
// Prints what each case gives.
private static final String DRIVER = LOAD_PROGRAM + """
cases = json.loads(sys.stdin.read())
answers = []
for case in cases:
try:
options, settings = program.parse(case["argv"])
if "files" not in case:
answers.append({"options": options, "settings": settings})
continue
files = [tuple(f) for f in case["files"]]
outputs = program.plan(files, options, case.get("extensions", {}), case.get("outputExtension"))
program.check_targets(outputs, options["dest"], options.get("outputManifest"), lambda l: l)
answers.append({"outputs": [[target, [f[1] for f in sources]] for target, sources in outputs]})
except program.UsageError as e:
answers.append({"error": str(e)})
print(json.dumps(answers))
""";
// Runs replace against a file system of names whose listed renames fail, and prints what each case leaves.
private static final String REPLACE_DRIVER = LOAD_PROGRAM + """
class Files:
def __init__(self, files, failing):
self.files, self.failing = dict(files), {tuple(f) for f in failing}
def rename(self, src, dst):
if (src, dst) in self.failing or src not in self.files or dst in self.files:
return False
self.files[dst] = self.files.pop(src)
return True
def delete(self, path, recursive):
return self.files.pop(path, None) is not None
answers = []
for failing in json.loads(sys.stdin.read()):
files = Files({"t": "old", "t.new": "new"}, failing)
try:
program.replace(files, "t.new", "t", "t.old")
answers.append({"files": files.files})
except IOError as e:
answers.append({"files": files.files, "error": str(e)})
print(json.dumps(answers))
""";
// Prints what a file's path starts with under each --srcPrefixesFile line, given the path Hadoop makes of it.
private static final String PREFIX_DRIVER = LOAD_PROGRAM + """
print(json.dumps([program.prefix_start(line, path) for line, path in json.loads(sys.stdin.read())]))
""";
private static final long MIB = 1024 * 1024;
// The Release Guide's log layout, by day and hour.
private static final List<List<Object>> LOGS = List.of(
file("2017-02-22/05/a.log", 3 * MIB), file("2017-02-22/05/b.log", 3 * MIB),
file("2017-02-22/05/c.log.gz", 5 * MIB), file("2017-02-22/06/d.log", MIB),
file("2017-02-22/06/notes.txt", 10));
@TempDir
static Path folder;
@BeforeAll
static void needsPython() throws Exception {
boolean python;
try {
python = BootstrapProcess.run(new ProcessBuilder("python3", "--version")).exit() == 0;
} catch (IOException e) {
python = false;
}
assumeTrue(python, "the host has no python3");
try (InputStream in = S3DistCpProgramTest.class.getClassLoader()
.getResourceAsStream(EmrSparkSteps.S3_DIST_CP_RESOURCE)) {
Files.write(folder.resolve("s3-dist-cp.py"), in.readAllBytes());
}
}
@Test
void optionsTakeEitherFormAndGenericSettingsTheirOwn() throws Exception {
JsonNode parsed = run(List.of(new Case(List.of("--src", "s3://bucket/logs", "--dest=hdfs:///output",
"--targetSize=2", "-D", "fs.s3a.connection.maximum=8", "-Dmapreduce.job.reduces=1", "--deleteOnSuccess",
"--requirePreviousManifest=false")))).get(0);
assertEquals(MAPPER.readTree("""
{"src": "s3://bucket/logs", "dest": "hdfs:///output", "targetSize": "2", "deleteOnSuccess": true,
"requirePreviousManifest": false}"""), parsed.path("options"));
assertEquals(MAPPER.readTree("[[\"fs.s3a.connection.maximum\", \"8\"], [\"mapreduce.job.reduces\", \"1\"]]"),
parsed.path("settings"));
}
@Test
void requirePreviousManifestTakesTrueOrFalseInEitherFormAndAloneIsTrue() throws Exception {
List<String> argv = List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output");
List<JsonNode> answers = run(List.of(
new Case(concat(argv, "--requirePreviousManifest", "false")),
new Case(concat(argv, "--requirePreviousManifest", "TRUE")),
new Case(concat(argv, "--requirePreviousManifest", "--deleteOnSuccess")),
new Case(concat(argv, "--requirePreviousManifest=maybe"))));
assertEquals(List.of("false", "true", "true"), answers.subList(0, 3).stream()
.map(answer -> answer.path("options").path("requirePreviousManifest").asText()).toList());
assertTrue(answers.get(2).path("options").path("deleteOnSuccess").asBoolean());
assertEquals("--requirePreviousManifest takes true or false, not maybe", answers.get(3).path("error").asText());
}
@Test
void aCopyThatWouldLoseDataFailsBeforeAnythingIsWritten() throws Exception {
List<List<Object>> logs = new ArrayList<>(LOGS);
logs.add(file("2017-02-22/05/c.log", 4));
List<JsonNode> answers = run(List.of(
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--outputCodec=gzip"), logs,
".gz"),
new Case(List.of("--src=s3://bucket/logs/", "--dest=s3a://bucket/logs/"), LOGS),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output",
"--outputManifest=2017-02-22/06/d.log"), LOGS),
new Case(List.of("--src=s3://bucket/logs/", "--dest=s3a://bucket/logs", "--srcPattern=.*/05/[ab]\\.log",
"--outputCodec=gzip"), LOGS, ".gz")));
assertEquals("2017-02-22/05/c.log and 2017-02-22/05/c.log.gz would both be written to"
+ " hdfs:///output/2017-02-22/05/c.log.gz", answers.get(0).path("error").asText());
assertEquals("2017-02-22/05/a.log would be written over its source s3a://bucket/logs/2017-02-22/05/a.log",
answers.get(1).path("error").asText());
assertEquals("2017-02-22/06/d.log and the manifest would both be written to"
+ " hdfs:///output/2017-02-22/06/d.log", answers.get(2).path("error").asText());
// The same folder is fine when every output has a name of its own.
assertEquals(List.of("2017-02-22/05/a.log.gz", "2017-02-22/05/b.log.gz"), targets(answers.get(3)));
}
@Test
void anOutputThatWouldLeaveTheDestinationFailsTheCopy() throws Exception {
// A manifest's baseName is the output's path under --dest, and Hadoop's paths resolve a "..".
List<JsonNode> answers = run(List.of(
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--copyFromManifest",
"--previousManifest=s3://bucket/manifest.gz"),
List.of(file("2017-02-22/../../victim", 3))),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--outputManifest=../manifest.gz"),
LOGS)));
assertEquals(List.of("2017-02-22/../../victim leads out of --dest hdfs:///output",
"../manifest.gz leads out of --dest hdfs:///output"),
answers.stream().map(answer -> answer.path("error").asText()).toList());
}
@Test
void anOutputWithNoFileNameFailsTheCopy() throws Exception {
// Hadoop's paths would write it as its folder.
List<String> argv = List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output");
List<JsonNode> answers = run(List.of(
new Case(concat(argv, "--groupBy=.*/(z*)[ab]\\.log"), LOGS),
new Case(concat(argv, "--outputManifest="), LOGS)));
assertEquals(List.of("2017-02-22/05/a.log, 2017-02-22/05/b.log would be written to"
+ " hdfs:///output/2017-02-22/05/, which names no file",
"the manifest would be written to hdfs:///output/, which names no file"),
answers.stream().map(answer -> answer.path("error").asText()).toList());
}
@Test
void optionsS3DistCpRefusesFailItBeforeAnythingIsCopied() throws Exception {
List<JsonNode> answers = run(List.of(
new Case(List.of("--src=s3://bucket/logs/")),
new Case(List.of("--src=s3://amzn_s3_demo/logs/", "--dest=hdfs:///output")),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--groupBy=.*\\.log")),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--outputCodec=zip")),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--targetSize=ten")),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--deleteOnSuccess=yes")),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--srcPatern=.*"))));
assertEquals(List.of("--dest is required",
"S3DistCp does not support Amazon S3 bucket names that contain the underscore character:"
+ " s3://amzn_s3_demo/logs/",
"The --groupBy regular expression .*\\.log has no parenthetical group to name the concatenated"
+ " files by",
"--outputCodec takes gzip, gz, lzo, lzop, snappy or none, not zip",
"--targetSize takes a whole number, not ten",
"--deleteOnSuccess takes no value",
"Unknown option --srcPatern"), answers.stream().map(answer -> answer.path("error").asText()).toList());
}
@Test
void aCopyKeepsEachFilesFolderUnderTheDestinationAndASourcePatternMatchesTheWholePath() throws Exception {
List<JsonNode> answers = run(List.of(
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output"), LOGS),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--srcPattern=.*\\.log"), LOGS),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--srcPattern=\\d+"), LOGS)));
assertEquals(outputs("""
[["2017-02-22/05/a.log", ["2017-02-22/05/a.log"]], ["2017-02-22/05/b.log", ["2017-02-22/05/b.log"]],
["2017-02-22/05/c.log.gz", ["2017-02-22/05/c.log.gz"]],
["2017-02-22/06/d.log", ["2017-02-22/06/d.log"]],
["2017-02-22/06/notes.txt", ["2017-02-22/06/notes.txt"]]]"""), answers.get(0).path("outputs"));
assertEquals(List.of("2017-02-22/05/a.log", "2017-02-22/05/b.log", "2017-02-22/06/d.log"),
targets(answers.get(1)));
assertEquals(List.of(), targets(answers.get(2)));
}
@Test
void anOutputCodecRenamesEachFileForItsExtensionAndNoneTakesTheSourcesOff() throws Exception {
List<String> argv = List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", "--srcPattern=.*/05/.*");
List<JsonNode> answers = run(List.of(
new Case(argv, LOGS, ".gz"),
new Case(argv, LOGS, "")));
assertEquals(List.of("2017-02-22/05/a.log.gz", "2017-02-22/05/b.log.gz", "2017-02-22/05/c.log.gz"),
targets(answers.get(0)));
assertEquals(List.of("2017-02-22/05/a.log", "2017-02-22/05/b.log", "2017-02-22/05/c.log"),
targets(answers.get(1)));
}
@Test
void groupByConcatenatesTheFilesItsGroupsNameAndTargetSizeBreaksAGroupIntoNumberedParts() throws Exception {
String groupBy = "--groupBy=.*/(\\d\\d)/.*\\.log.*";
List<JsonNode> answers = run(List.of(
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", groupBy), LOGS),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", groupBy, "--targetSize=6"), LOGS),
new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output", groupBy, "--targetSize=6",
"--outputCodec=gzip"), LOGS, ".gz")));
assertEquals(outputs("""
[["2017-02-22/05/05", ["2017-02-22/05/a.log", "2017-02-22/05/b.log", "2017-02-22/05/c.log.gz"]],
["2017-02-22/06/06", ["2017-02-22/06/d.log"]]]"""), answers.get(0).path("outputs"));
// "broken into parts as: myfile0.gz, myfile1.gz", and a group within the size stays whole.
assertEquals(outputs("""
[["2017-02-22/05/050", ["2017-02-22/05/a.log", "2017-02-22/05/b.log"]],
["2017-02-22/05/051", ["2017-02-22/05/c.log.gz"]], ["2017-02-22/06/06", ["2017-02-22/06/d.log"]]]"""),
answers.get(1).path("outputs"));
assertEquals(List.of("2017-02-22/05/050.gz", "2017-02-22/05/051.gz", "2017-02-22/06/06.gz"),
targets(answers.get(2)));
}
@Test
void anAppendedCopyTakesTheFilesPlaceOnlyOnceItCanAndTheOldFileComesBackOtherwise() throws Exception {
List<JsonNode> answers = runDriver(REPLACE_DRIVER, List.of(
List.of(),
List.of(List.of("t.new", "t")),
List.of(List.of("t", "t.old")),
List.of(List.of("t.new", "t"), List.of("t.old", "t"))));
assertEquals(MAPPER.readTree("{\"files\": {\"t\": \"new\"}}"), answers.get(0));
assertEquals(MAPPER.readTree("""
{"files": {"t": "old", "t.new": "new"}, "error": "Could not rename t.new to t"}"""), answers.get(1));
assertEquals(MAPPER.readTree("""
{"files": {"t": "old", "t.new": "new"}, "error": "Could not move t aside to replace it"}"""),
answers.get(2));
// Should even the way back fail, the old content keeps the name it stepped aside to.
assertEquals(MAPPER.readTree("""
{"files": {"t.new": "new", "t.old": "old"},
"error": "Could not rename t.new to t; what it held is at t.old"}"""), answers.get(3));
}
@Test
void withoutAnOutputCodecAGroupKeepsTheCompressionItsFilesShareAndAMixedOneHasNone() throws Exception {
List<String> argv = List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output");
List<JsonNode> answers = run(List.of(
new Case(concat(argv, "--groupBy=.*/(\\d\\d)/.*\\.log.*"), LOGS),
new Case(concat(argv, "--groupBy=.*/(\\d\\d)/.*\\.gz"), LOGS),
new Case(concat(argv, "--groupBy=.*/(\\d\\d)/.*(\\.gz)"), LOGS)));
// 05 holds a.log, b.log and c.log.gz, written uncompressed; 06 holds d.log alone.
assertEquals(List.of("2017-02-22/05/05", "2017-02-22/06/06"), targets(answers.get(0)));
assertEquals(List.of("2017-02-22/05/05.gz"), targets(answers.get(1)));
// A group's name ending in the extension does not get it twice.
assertEquals(List.of("2017-02-22/05/05.gz"), targets(answers.get(2)));
}
@Test
void aSourcePrefixEndingInASlashNamesThatFolderAloneAndAnyOtherIsAPrefixAsS3ListsOne() throws Exception {
// Hadoop's Path drops the line's trailing slash.
List<JsonNode> answers = runDriver(PREFIX_DRIVER, List.of(
List.of("s3://bucket/logs/day/", "/logs/day"),
List.of("s3://bucket/logs/day", "/logs/day")));
assertEquals("/logs/day/", answers.get(0).asText());
assertFalse("/logs/day-old/a.log".startsWith(answers.get(0).asText()));
assertEquals("/logs/day", answers.get(1).asText());
assertTrue("/logs/day-old/a.log".startsWith(answers.get(1).asText()));
}
@Test
void numberFilesPutsASequentialNumberBeforeEachFileFromTheStartingIndex() throws Exception {
List<JsonNode> answers = run(List.of(new Case(List.of("--src=s3://bucket/logs/", "--dest=hdfs:///output",
"--srcPattern=.*\\.log", "--numberFiles", "--startingIndex=1"), LOGS)));
assertEquals(List.of("2017-02-22/05/1a.log", "2017-02-22/05/2b.log", "2017-02-22/06/3d.log"),
targets(answers.get(0)));
}
private static List<Object> file(String relative, long size) {
return List.of("s3a://bucket/logs/" + relative, relative, size);
}
private static List<String> concat(List<String> argv, String... more) {
List<String> all = new ArrayList<>(argv);
all.addAll(List.of(more));
return all;
}
private record Case(List<String> argv, List<List<Object>> files, String outputExtension) {
Case(List<String> argv) {
this(argv, null, null);
}
Case(List<String> argv, List<List<Object>> files) {
this(argv, files, null);
}
}
private static List<JsonNode> run(List<Case> cases) throws Exception {
List<Object> json = cases.stream().map(c -> {
Map<String, Object> node = new LinkedHashMap<>();
node.put("argv", c.argv());
if (c.files() != null) {
node.put("files", c.files());
node.put("extensions", Map.of("s3a://bucket/logs/2017-02-22/05/c.log.gz", ".gz"));
node.put("outputExtension", c.outputExtension());
}
return (Object) node;
}).toList();
return runDriver(DRIVER, json);
}
private static List<JsonNode> runDriver(String program, Object cases) throws Exception {
Path driver = folder.resolve("driver.py");
Files.writeString(driver, program);
Path input = folder.resolve("cases.json");
Files.writeString(input, MAPPER.writeValueAsString(cases));
BootstrapProcess.Result ended = BootstrapProcess.run(new ProcessBuilder("python3", "-I",
driver.toString(), folder.resolve("s3-dist-cp.py").toString()).redirectInput(input.toFile()));
assertEquals(0, ended.exit(), ended.output());
List<JsonNode> answers = new ArrayList<>();
MAPPER.readTree(ended.output()).forEach(answers::add);
return answers;
}
private static JsonNode outputs(String json) throws Exception {
return MAPPER.readTree(json);
}
private static List<String> targets(JsonNode answer) {
List<String> targets = new ArrayList<>();
answer.path("outputs").forEach(output -> targets.add(output.get(0).asText()));
return targets;
}
}