mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(glue): run Spark job scripts in a container (#8568)
This commit is contained in:
1 parent
379ac190c3
commit
a06be2d292
13 files changed
+2182
-9
No files matched your search
@@ -0,0 +1,584 @@
|
||||
package io.floci.aws.services.glue;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.S3Uri;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.SessionCreds;
|
||||
import io.floci.aws.services.lambda.launcher.ImageCacheService.LaunchImage;
|
||||
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
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;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class DockerGlueScriptRunnerTest {
|
||||
|
||||
private static final String ENDPOINT = "http://floci:4566";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/glue";
|
||||
private static final String SCRIPT = "s3://glue-demo/scripts/job.py";
|
||||
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
private final LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
|
||||
private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
private final S3Service s3 = mock(S3Service.class);
|
||||
private final ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
private final LambdaExecutionRoleCredentials roleCredentials = mock(LambdaExecutionRoleCredentials.class);
|
||||
private final GlueScriptRunner.Progress progress = mock(GlueScriptRunner.Progress.class);
|
||||
private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
private final MutableClock clock = new MutableClock();
|
||||
|
||||
@Test
|
||||
void putsTheScriptAndItsArgumentsAfterFlocisSparkSettings() {
|
||||
List<String> command = DockerGlueScriptRunner.commandLine("/home/hadoop/workspace/job.py",
|
||||
ENDPOINT, "us-east-1", "000000000000", List.of("--bucket", "glue-demo", "--JOB_NAME", "etl"));
|
||||
|
||||
int script = command.indexOf("/home/hadoop/workspace/job.py");
|
||||
assertEquals(List.of("--bucket", "glue-demo", "--JOB_NAME", "etl"), command.subList(script + 1, command.size()));
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3a.endpoint=http://floci:4566"));
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3a.endpoint.region=us-east-1"));
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3a.path.style.access=true"));
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3a.connection.ssl.enabled=false"));
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3a.committer.magic.track.commits.in.memory.enabled=true"));
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem"));
|
||||
assertTrue(command.contains("spark.hadoop.aws.glue.endpoint=http://floci:4566"));
|
||||
assertTrue(command.contains("spark.hadoop.hive.metastore.glue.catalogid=000000000000"));
|
||||
assertTrue(command.contains("spark.hadoop.aws.region=us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enablesSslForAnHttpsEndpoint() {
|
||||
List<String> command = DockerGlueScriptRunner.commandLine("/job.py", "https://floci:4566",
|
||||
"us-east-1", "000000000000", List.of());
|
||||
|
||||
assertTrue(command.contains("spark.hadoop.fs.s3a.connection.ssl.enabled=true"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsAPythonScriptsNameAndNamesAnyOtherScript() {
|
||||
assertEquals("job.py", DockerGlueScriptRunner.scriptName(S3Uri.parse("s3://b/scripts/job.py")));
|
||||
assertEquals("script.py", DockerGlueScriptRunner.scriptName(S3Uri.parse("s3://b/scripts/job")));
|
||||
assertEquals("script.py", DockerGlueScriptRunner.scriptName(S3Uri.parse("s3://b/job.sh")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void turnsArgumentsIntoNameValuePairsInOrder() {
|
||||
Map<String, String> arguments = new LinkedHashMap<>();
|
||||
arguments.put("--a", "1");
|
||||
arguments.put("--flag", null);
|
||||
|
||||
assertEquals(List.of("--a", "1", "--flag", ""), GlueScriptRunner.argumentList(arguments));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExitOfZeroEndsTheRunAndTheContainerIsRemoved() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(docker.copyArchiveToContainerCmd("script")).thenReturn(copy);
|
||||
Map<String, String> copied = copiedIn(copy);
|
||||
inS3("glue-demo", "scripts/job.py", "print('hi')");
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertEquals(0, outcome.exitCode());
|
||||
assertFalse(outcome.stopped());
|
||||
assertFalse(outcome.timedOut());
|
||||
// Extracted at the container's root, where the Glue image keeps its workspace.
|
||||
assertEquals(Map.of("home/hadoop/workspace/job.py", "print('hi')"), copied);
|
||||
verify(spec).withEntrypoint(List.of("spark-submit"));
|
||||
verify(spec).withCmd(argThat((List<String> cmd) -> cmd.contains("/home/hadoop/workspace/job.py")
|
||||
&& cmd.getLast().equals("jr_1") && cmd.contains("--JOB_NAME")));
|
||||
verify(lifecycle).startCreated(eq("script"), any());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonZeroExitIsTheScriptsExitCode() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 3L));
|
||||
inS3("glue-demo", "scripts/job.py", "raise SystemExit(3)");
|
||||
|
||||
assertEquals(3, runner.run(request(Duration.ZERO), progress).exitCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theJobRolesCredentialsReachTheScriptAndAreGivenBackWhenItEnds() {
|
||||
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
when(roleCredentials.forRole(ROLE, "000000000000", "jr_1")).thenReturn(Optional.of(session));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
|
||||
runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
verify(awsEnv).sdkBaselineEnv("us-east-1", Optional.empty(), Optional.of(session), "000000000000");
|
||||
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScriptThatCannotBeReadFailsTheRunBeforeAnyContainerExists() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
when(s3.headObject("glue-demo", "scripts/job.py"))
|
||||
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertTrue(outcome.failure().contains("Could not read the script " + SCRIPT));
|
||||
verify(lifecycle, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunCancelledBeforeItStartsNeverCreatesAContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
when(progress.cancelled()).thenReturn(true);
|
||||
|
||||
assertTrue(runner.run(request(Duration.ZERO), progress).stopped());
|
||||
verify(lifecycle, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStopWhileTheImageIsPulledNeverStartsTheScript() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
when(lifecycle.create(any())).thenAnswer(pulling -> {
|
||||
runner.stop("jr_1");
|
||||
return "script";
|
||||
});
|
||||
|
||||
assertTrue(runner.run(request(Duration.ZERO), progress).stopped());
|
||||
verify(lifecycle, never()).startCreated(anyString(), any());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStopWhileTheScriptRunsEndsTheRunAndRemovesTheContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", true, null));
|
||||
inS3("glue-demo", "scripts/job.py", "while True: pass");
|
||||
when(docker.inspectContainerCmd("script").exec().getState().getRunning()).thenAnswer(look -> {
|
||||
runner.stop("jr_1");
|
||||
return true;
|
||||
});
|
||||
|
||||
assertTrue(runner.run(request(Duration.ZERO), progress).stopped());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScriptPastItsTimeoutEndsTheRunAndRemovesTheContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", true, null));
|
||||
inS3("glue-demo", "scripts/job.py", "while True: pass");
|
||||
when(docker.inspectContainerCmd("script").exec().getState().getRunning()).thenAnswer(look -> {
|
||||
clock.advance(Duration.ofMinutes(31));
|
||||
return true;
|
||||
});
|
||||
|
||||
assertTrue(runner.run(request(Duration.ofMinutes(30)), progress).timedOut());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunWithoutATimeoutIsNeverTimedOut() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", true, null));
|
||||
inS3("glue-demo", "scripts/job.py", "while True: pass");
|
||||
AtomicInteger looks = new AtomicInteger();
|
||||
when(docker.inspectContainerCmd("script").exec().getState().getRunning()).thenAnswer(look -> {
|
||||
clock.advance(Duration.ofDays(30));
|
||||
// Ends on the second look, as the container exits.
|
||||
return looks.incrementAndGet() < 2;
|
||||
});
|
||||
when(docker.inspectContainerCmd("script").exec().getState().getExitCodeLong()).thenReturn(0L);
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertFalse(outcome.timedOut());
|
||||
assertNull(outcome.failure());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTimeoutCountsFromTheRunsStartSoAnImagePullIsPartOfIt() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", true, null));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
when(lifecycle.create(any())).thenAnswer(pulling -> {
|
||||
clock.advance(Duration.ofMinutes(31));
|
||||
return "script";
|
||||
});
|
||||
|
||||
assertTrue(runner.run(request(Duration.ofMinutes(30)), progress).timedOut());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSingleRefusedLookAtTheContainerDoesNotEndTheRun() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
AtomicInteger looks = new AtomicInteger();
|
||||
when(docker.inspectContainerCmd("script")).thenAnswer(look -> {
|
||||
if (looks.incrementAndGet() == 1) {
|
||||
throw new IllegalStateException("daemon busy");
|
||||
}
|
||||
return mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS);
|
||||
});
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertNull(outcome.failure());
|
||||
assertTrue(looks.get() >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerLooksThatKeepFailingFailTheRunAndRemoveTheContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", true, null));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
when(docker.inspectContainerCmd("script")).thenThrow(new IllegalStateException("daemon gone"));
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertEquals("daemon gone", outcome.failure());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerThatCannotBeCreatedFailsTheRunAndStillReleasesItsCredentials() {
|
||||
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
when(roleCredentials.forRole(ROLE, "000000000000", "jr_1")).thenReturn(Optional.of(session));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
when(lifecycle.create(any())).thenThrow(new IllegalStateException("no space left on device"));
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertEquals("no space left on device", outcome.failure());
|
||||
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutCountsFromRecordedStartedOnEvenBeforeWorkerBegins() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
Instant startedOn = clock.instant();
|
||||
clock.advance(Duration.ofMinutes(31));
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(startedOn, Duration.ofMinutes(30)), progress);
|
||||
|
||||
assertTrue(outcome.timedOut());
|
||||
verify(lifecycle, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutDuringPreparationDoesNotStartTheContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
when(lifecycle.create(any())).thenAnswer(pulling -> {
|
||||
clock.advance(Duration.ofMinutes(31));
|
||||
return "script";
|
||||
});
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ofMinutes(30)), progress);
|
||||
|
||||
assertTrue(outcome.timedOut());
|
||||
verify(lifecycle, never()).startCreated(anyString(), any());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutAtInspectionReturnsTimedOutEvenIfContainerAlsoStopped() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", true, 0L));
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
InspectContainerResponse response = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
when(response.getState().getRunning()).thenReturn(false);
|
||||
when(response.getState().getExitCodeLong()).thenReturn(0L);
|
||||
when(docker.inspectContainerCmd("script").exec()).thenAnswer(look -> {
|
||||
clock.advance(Duration.ofMinutes(31));
|
||||
return response;
|
||||
});
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ofMinutes(30)), progress);
|
||||
|
||||
assertTrue(outcome.timedOut());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesRoleNameViaIamServiceForScriptCredentials() {
|
||||
IamService iamService = mock(IamService.class);
|
||||
ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class);
|
||||
String resolvedArn = "arn:aws:iam::000000000000:role/service-role/glue-role";
|
||||
IamRole role = new IamRole("role-id", "glue-role", "/service-role/", resolvedArn, "{}");
|
||||
when(iamService.findRole("000000000000", "glue-role")).thenReturn(Optional.of(role));
|
||||
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
|
||||
when(roleCredentials.forRole(resolvedArn, "000000000000", "jr_1")).thenReturn(Optional.of(session));
|
||||
DockerGlueScriptRunner runner = runner("script", iamService, authorizer);
|
||||
container("script", false, 0L);
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request("glue-role", clock.instant(), Duration.ZERO), progress);
|
||||
|
||||
assertEquals(0, outcome.exitCode());
|
||||
verify(awsEnv).sdkBaselineEnv("us-east-1", Optional.empty(), Optional.of(session), "000000000000");
|
||||
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsCrossAccountRoleArnBeforeCreatingContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(
|
||||
request("arn:aws:iam::999999999999:role/admin", clock.instant(), Duration.ZERO), progress);
|
||||
|
||||
assertTrue(outcome.failure().contains("Cross-account"));
|
||||
verify(lifecycle, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcementRejectsRoleThatDoesNotTrustGlue() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
IamService iamService = mock(IamService.class);
|
||||
ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class);
|
||||
IamRole role = new IamRole("role-id", "glue", "/", ROLE, "{}");
|
||||
when(iamService.findRole("000000000000", "glue")).thenReturn(Optional.of(role));
|
||||
when(authorizer.refusal(ROLE, "000000000000", "glue.amazonaws.com",
|
||||
"arn:aws:glue:us-east-1:000000000000:job/etl", List.of()))
|
||||
.thenReturn(Optional.of("The role " + ROLE + " does not trust glue.amazonaws.com."));
|
||||
DockerGlueScriptRunner runner = runner("script", iamService, authorizer);
|
||||
container("script", false, 0L);
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(ROLE, clock.instant(), Duration.ZERO), progress);
|
||||
|
||||
assertTrue(outcome.failure().contains("does not trust"));
|
||||
verify(lifecycle, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcementAllowsRoleThatTrustsGlue() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
IamService iamService = mock(IamService.class);
|
||||
ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class);
|
||||
IamRole role = new IamRole("role-id", "glue", "/", ROLE, "{\"Statement\":[]}");
|
||||
when(iamService.findRole("000000000000", "glue")).thenReturn(Optional.of(role));
|
||||
when(authorizer.refusal(ROLE, "000000000000", "glue.amazonaws.com",
|
||||
"arn:aws:glue:us-east-1:000000000000:job/etl", List.of())).thenReturn(Optional.empty());
|
||||
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
|
||||
when(roleCredentials.forRole(ROLE, "000000000000", "jr_1")).thenReturn(Optional.of(session));
|
||||
DockerGlueScriptRunner runner = runner("script", iamService, authorizer);
|
||||
container("script", false, 0L);
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(ROLE, clock.instant(), Duration.ZERO), progress);
|
||||
|
||||
assertEquals(0, outcome.exitCode());
|
||||
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void customRegionKeepsDeploymentPartitionForRoleName() {
|
||||
RegionResolver chinaDeployment = new RegionResolver("cn-north-1", "000000000000", "aws-cn");
|
||||
DockerGlueScriptRunner runner = runner("script", mock(IamService.class), mock(ServiceRoleAuthorizer.class),
|
||||
chinaDeployment);
|
||||
container("script", false, 0L);
|
||||
inS3("glue-demo", "scripts/job.py", "pass");
|
||||
|
||||
runner.run(request("glue", "xx-custom-1", clock.instant(), Duration.ZERO), progress);
|
||||
|
||||
verify(roleCredentials).forRole("arn:aws-cn:iam::000000000000:role/glue", "000000000000", "jr_1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcementRejectsRoleArnOutsideCustomRegionPartition() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
RegionResolver chinaDeployment = new RegionResolver("cn-north-1", "000000000000", "aws-cn");
|
||||
DockerGlueScriptRunner runner = runner("script", mock(IamService.class), mock(ServiceRoleAuthorizer.class),
|
||||
chinaDeployment);
|
||||
container("script", false, 0L);
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(ROLE, "xx-custom-1", clock.instant(), Duration.ZERO),
|
||||
progress);
|
||||
|
||||
assertTrue(outcome.failure().contains("another partition"));
|
||||
verify(lifecycle, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopDuringScriptUploadAbortsStreamAndRemovesContainer() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(docker.copyArchiveToContainerCmd("script")).thenReturn(copy);
|
||||
when(copy.withTarInputStream(any())).thenAnswer(streaming -> {
|
||||
InputStream stream = streaming.getArgument(0);
|
||||
try {
|
||||
stream.transferTo(OutputStream.nullOutputStream());
|
||||
} catch (IOException ignored) {
|
||||
// The stopped writer closes the pipe once it sees the stop.
|
||||
}
|
||||
return copy;
|
||||
});
|
||||
byte[] content = "print('x')\n".getBytes(StandardCharsets.UTF_8);
|
||||
S3Object object = new S3Object("glue-demo", "scripts/job.py", content, "application/octet-stream");
|
||||
InputStream stoppingStream = new InputStream() {
|
||||
@Override
|
||||
public int read() {
|
||||
runner.stop("jr_1");
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) {
|
||||
runner.stop("jr_1");
|
||||
b[off] = 'x';
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
when(s3.openObject("glue-demo", "scripts/job.py", null))
|
||||
.thenReturn(new S3Service.ObjectRead(object, stoppingStream));
|
||||
|
||||
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
|
||||
|
||||
assertTrue(outcome.stopped());
|
||||
verify(lifecycle, never()).startCreated(anyString(), any());
|
||||
verify(lifecycle).stopAndRemove("script", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeLeftoverContainersContinuesWhenOneContainerRemovalFails() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
String owner = ContainerStorageHelper.ownerIdentity(config);
|
||||
Map<String, String> labels = Map.of(
|
||||
ContainerStorageHelper.SERVICE_LABEL, DockerGlueScriptRunner.SERVICE,
|
||||
ContainerStorageHelper.OWNER_LABEL, owner);
|
||||
Container first = mock(Container.class);
|
||||
when(first.getId()).thenReturn("c1");
|
||||
when(first.getLabels()).thenReturn(labels);
|
||||
Container second = mock(Container.class);
|
||||
when(second.getId()).thenReturn("c2");
|
||||
when(second.getLabels()).thenReturn(labels);
|
||||
when(docker.listContainersCmd().withShowAll(true).withLabelFilter(anyMap()).exec())
|
||||
.thenReturn(List.of(first, second));
|
||||
doThrow(new IllegalStateException("daemon busy")).when(lifecycle).removeIfExistsStrict("c1", true);
|
||||
|
||||
runner.removeLeftoverContainers();
|
||||
|
||||
verify(lifecycle).removeIfExistsStrict("c1", true);
|
||||
verify(lifecycle).removeIfExistsStrict("c2", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAvailableReflectsDockerDaemonReachability() {
|
||||
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
|
||||
assertTrue(runner.isAvailable());
|
||||
|
||||
when(docker.pingCmd().exec()).thenThrow(new IllegalStateException("daemon unreachable"));
|
||||
assertFalse(runner.isAvailable());
|
||||
}
|
||||
|
||||
private GlueScriptRunner.Run request(Duration timeout) {
|
||||
return request(clock.instant(), timeout);
|
||||
}
|
||||
|
||||
private GlueScriptRunner.Run request(Instant startedOn, Duration timeout) {
|
||||
return request(ROLE, startedOn, timeout);
|
||||
}
|
||||
|
||||
private GlueScriptRunner.Run request(String role, Instant startedOn, Duration timeout) {
|
||||
return request(role, "us-east-1", startedOn, timeout);
|
||||
}
|
||||
|
||||
private GlueScriptRunner.Run request(String role, String region, Instant startedOn, Duration timeout) {
|
||||
return new GlueScriptRunner.Run("jr_1", "etl", "000000000000", region, role, SCRIPT,
|
||||
List.of("--JOB_NAME", "etl", "--JOB_RUN_ID", "jr_1"), "glue-image:5", null, startedOn, timeout);
|
||||
}
|
||||
|
||||
// A runner whose script container is "id", running or not, with an exit code once it is not.
|
||||
private DockerGlueScriptRunner runner(String id) {
|
||||
return runner(id, null, null);
|
||||
}
|
||||
|
||||
private DockerGlueScriptRunner runner(String id, IamService iamService, ServiceRoleAuthorizer authorizer) {
|
||||
return runner(id, iamService, authorizer, new RegionResolver("us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
private DockerGlueScriptRunner runner(String id, IamService iamService, ServiceRoleAuthorizer authorizer,
|
||||
RegionResolver regionResolver) {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
when(builder.resolveImage(anyString())).thenAnswer(image -> image.getArgument(0));
|
||||
when(builder.resolveDockerNetwork(any())).thenReturn(Optional.empty());
|
||||
when(lifecycle.getDockerClient()).thenReturn(docker);
|
||||
when(lifecycle.create(any())).thenReturn(id);
|
||||
when(lifecycle.resolveImageForLaunch(anyString(), eq(ImagePullBehavior.DEFAULT), isNull()))
|
||||
.thenAnswer(pull -> new LaunchImage(pull.getArgument(0), null));
|
||||
when(awsEnv.flociEndpoint()).thenReturn(ENDPOINT);
|
||||
return new DockerGlueScriptRunner(builder, lifecycle, logStreamer, awsEnv, roleCredentials, iamService, authorizer,
|
||||
regionResolver, s3, config, clock, Duration.ZERO);
|
||||
}
|
||||
|
||||
private String container(String id, boolean running, Long exitCode) {
|
||||
when(docker.inspectContainerCmd(id).exec().getState().getRunning()).thenReturn(running);
|
||||
when(docker.inspectContainerCmd(id).exec().getState().getExitCodeLong()).thenReturn(exitCode);
|
||||
return id;
|
||||
}
|
||||
|
||||
// What each tar copied into the container holds, by entry, read as the daemon reads it.
|
||||
private static Map<String, String> copiedIn(CopyArchiveToContainerCmd copy) {
|
||||
Map<String, String> copied = new LinkedHashMap<>();
|
||||
when(copy.withTarInputStream(any())).thenAnswer(streaming -> {
|
||||
InputStream stream = streaming.getArgument(0);
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(stream);
|
||||
for (TarArchiveEntry entry = tar.getNextEntry(); entry != null; entry = tar.getNextEntry()) {
|
||||
copied.put(entry.getName(), new String(tar.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
stream.transferTo(OutputStream.nullOutputStream());
|
||||
return copy;
|
||||
});
|
||||
return copied;
|
||||
}
|
||||
|
||||
// An object in Floci's S3, which each read opens afresh.
|
||||
private void inS3(String bucket, String key, String content) {
|
||||
S3Object object = new S3Object(bucket, key, content.getBytes(StandardCharsets.UTF_8),
|
||||
"application/octet-stream");
|
||||
when(s3.openObject(bucket, key, null))
|
||||
.thenAnswer(read -> new S3Service.ObjectRead(object, new ByteArrayInputStream(object.getData())));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package io.floci.aws.services.glue;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -12,6 +14,7 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class GlueJobRunIntegrationTest {
|
||||
@@ -19,6 +22,9 @@ class GlueJobRunIntegrationTest {
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/my-role";
|
||||
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
@@ -59,4 +65,10 @@ class GlueJobRunIntegrationTest {
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("EntityNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scriptsAreNotRunUnlessTheRunnerModeIsDocker() {
|
||||
assertEquals("immediate", config.services().glue().runnerMode());
|
||||
assertEquals("public.ecr.aws/glue/aws-glue-libs:5", config.services().glue().image());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package io.floci.aws.services.glue;
|
||||
|
||||
import io.floci.aws.testing.GlueRequests;
|
||||
import io.floci.aws.testing.IndependentServiceSettingsProfile;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Job runs in the {@code docker} runner mode, over the wire, with the container replaced by a runner that
|
||||
* reports how it ended: what a run keeps of its account and Region on the thread that runs its script.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IndependentServiceSettingsProfile.class)
|
||||
class GlueScriptRunIntegrationTest {
|
||||
|
||||
private record CreatedJob(String region, String name) {
|
||||
}
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::" + ACCOUNT_ID + ":role/my-role";
|
||||
private static final String SCRIPT = "s3://glue-demo/scripts/job.py";
|
||||
|
||||
@InjectMock
|
||||
DockerGlueScriptRunner runner;
|
||||
|
||||
private final List<Boolean> cancelledSeen = new CopyOnWriteArrayList<>();
|
||||
private final List<CreatedJob> createdJobs = new CopyOnWriteArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void runnerEndsWithExitZero() {
|
||||
cancelledSeen.clear();
|
||||
when(runner.isAvailable()).thenReturn(true);
|
||||
when(runner.run(any(), any())).thenAnswer(invocation -> {
|
||||
GlueScriptRunner.Progress progress = invocation.getArgument(1);
|
||||
cancelledSeen.add(progress.cancelled());
|
||||
return GlueScriptRunner.Outcome.exitedWith(0);
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteCreatedJobs() {
|
||||
for (CreatedJob job : createdJobs) {
|
||||
call(job.region(), "DeleteJob", "{ \"JobName\": \"" + job.name() + "\" }").statusCode(200);
|
||||
}
|
||||
createdJobs.clear();
|
||||
}
|
||||
|
||||
private static ValidatableResponse call(String region, String action, String body) {
|
||||
return GlueRequests.call(action, ACCOUNT_ID, region, body);
|
||||
}
|
||||
|
||||
private static String state(String region, String jobName, String runId) {
|
||||
return call(region, "GetJobRun", "{ \"JobName\": \"" + jobName + "\", \"RunId\": \"" + runId + "\" }")
|
||||
.statusCode(200).extract().path("JobRun.JobRunState");
|
||||
}
|
||||
|
||||
private static String awaitEnd(String region, String jobName, String runId) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(1).toNanos();
|
||||
String state = state(region, jobName, runId);
|
||||
while ("RUNNING".equals(state) && System.nanoTime() < deadline) {
|
||||
Thread.sleep(10);
|
||||
state = state(region, jobName, runId);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private String startRun(String region, String command) {
|
||||
String jobName = "script-job-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
call(region, "CreateJob", """
|
||||
{ "Name": "%s", "Role": "%s",
|
||||
"Command": { "Name": "%s", "ScriptLocation": "%s" } }
|
||||
""".formatted(jobName, ROLE, command, SCRIPT)).statusCode(200);
|
||||
createdJobs.add(new CreatedJob(region, jobName));
|
||||
return jobName;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSparkJobsScriptRunsAndItsExitSettlesTheRunInTheDefaultRegion() throws InterruptedException {
|
||||
String jobName = startRun("us-east-1", "glueetl");
|
||||
String runId = call("us-east-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
|
||||
.statusCode(200).extract().path("JobRunId");
|
||||
|
||||
assertThat(awaitEnd("us-east-1", jobName, runId), equalTo("SUCCEEDED"));
|
||||
assertThat(cancelledSeen, equalTo(List.of(false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunInAnotherRegionIsNotTakenForCancelledOnTheThreadThatRunsItsScript() throws InterruptedException {
|
||||
String jobName = startRun("eu-west-1", "glueetl");
|
||||
String runId = call("eu-west-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
|
||||
.statusCode(200).extract().path("JobRunId");
|
||||
|
||||
assertThat(awaitEnd("eu-west-1", jobName, runId), equalTo("SUCCEEDED"));
|
||||
assertThat(cancelledSeen, equalTo(List.of(false)));
|
||||
call("eu-west-1", "GetJobRuns", "{ \"JobName\": \"" + jobName + "\" }")
|
||||
.statusCode(200)
|
||||
.body("JobRuns.Id", hasItem(runId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPythonShellJobKeepsTheSimulationAndNeverReachesTheRunner() {
|
||||
String jobName = startRun("us-east-1", "pythonshell");
|
||||
|
||||
String runId = call("us-east-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
|
||||
.statusCode(200).extract().path("JobRunId");
|
||||
|
||||
assertThat(state("us-east-1", jobName, runId), equalTo("SUCCEEDED"));
|
||||
assertThat(cancelledSeen, equalTo(List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToSimulationWhenDockerIsUnavailable() {
|
||||
when(runner.isAvailable()).thenReturn(false);
|
||||
String jobName = startRun("us-east-1", "glueetl");
|
||||
|
||||
String runId = call("us-east-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
|
||||
.statusCode(200).extract().path("JobRunId");
|
||||
|
||||
assertThat(state("us-east-1", jobName, runId), equalTo("SUCCEEDED"));
|
||||
assertThat(cancelledSeen, equalTo(List.of()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
package io.floci.aws.services.glue;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.glue.model.Job;
|
||||
import io.floci.aws.services.glue.model.JobCommand;
|
||||
import io.floci.aws.services.glue.model.JobRun;
|
||||
import io.floci.aws.services.glue.model.JobRunBookkeeping;
|
||||
import io.floci.aws.services.glue.schemaregistry.GlueSchemaRegistryService;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Glue job runs in the docker runner mode: a script's end, a timeout and a stop settle the run. */
|
||||
class GlueScriptRunTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/glue";
|
||||
private static final String SCRIPT = "s3://glue-demo/scripts/job.py";
|
||||
|
||||
private GlueService glueService;
|
||||
private RegionResolver regionResolver;
|
||||
private MutableClock clock;
|
||||
private InMemoryStorage<String, JobRun> runStore;
|
||||
private InMemoryStorage<String, JobRunBookkeeping> bookkeeping;
|
||||
private FakeRunner runner;
|
||||
private final List<Runnable> queued = new ArrayList<>();
|
||||
private GlueJobRunService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
|
||||
StorageFactory storageFactory = new InMemoryStorageFactory(ACCOUNT_ID);
|
||||
glueService = new GlueService(storageFactory, new GlueSchemaRegistryService(storageFactory, regionResolver),
|
||||
regionResolver, new ResourceGroupsTaggingService(storageFactory),
|
||||
new KmsService(storageFactory, regionResolver));
|
||||
clock = new MutableClock();
|
||||
runStore = new InMemoryStorage<>();
|
||||
bookkeeping = new InMemoryStorage<>();
|
||||
runner = new FakeRunner();
|
||||
service = newService();
|
||||
}
|
||||
|
||||
private GlueJobRunService newService() {
|
||||
Executor held = queued::add;
|
||||
return new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock, regionResolver, runner, held,
|
||||
"glue-image:5", "glue-net");
|
||||
}
|
||||
|
||||
private void createJob(String name, String command, String script, Map<String, String> defaults, Integer timeout) {
|
||||
Job job = new Job();
|
||||
job.setName(name);
|
||||
job.setRole(ROLE);
|
||||
JobCommand jobCommand = new JobCommand();
|
||||
jobCommand.setName(command);
|
||||
jobCommand.setScriptLocation(script);
|
||||
job.setCommand(jobCommand);
|
||||
job.setGlueVersion("5.0");
|
||||
job.setWorkerType("G.1X");
|
||||
job.setNumberOfWorkers(2);
|
||||
job.setDefaultArguments(defaults);
|
||||
job.setTimeout(timeout);
|
||||
glueService.createJob(job, null, REGION);
|
||||
}
|
||||
|
||||
private void runQueued() {
|
||||
List<Runnable> tasks = new ArrayList<>(queued);
|
||||
queued.clear();
|
||||
tasks.forEach(Runnable::run);
|
||||
}
|
||||
|
||||
private String state(String job, String runId) {
|
||||
return service.getJobRun(job, runId).getJobRunState();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runsTheScriptWithTheJobsRoleAndTheMergedArguments() {
|
||||
createJob("etl", "glueetl", SCRIPT, Map.of("--bucket", "glue-demo", "--mode", "default"), 30);
|
||||
JobRun overrides = new JobRun();
|
||||
overrides.setArguments(Map.of("--mode", "run"));
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, overrides);
|
||||
runQueued();
|
||||
|
||||
GlueScriptRunner.Run request = runner.requests.getFirst();
|
||||
assertEquals(run.getId(), request.runId());
|
||||
assertEquals(ROLE, request.role());
|
||||
assertEquals(SCRIPT, request.scriptLocation());
|
||||
assertEquals("glue-image:5", request.image());
|
||||
assertEquals("glue-net", request.dockerNetwork());
|
||||
assertEquals(Duration.ofMinutes(30), request.timeout());
|
||||
assertEquals(ACCOUNT_ID, request.accountId());
|
||||
assertEquals(REGION, request.region());
|
||||
Map<String, String> arguments = pairs(request.arguments());
|
||||
assertEquals("glue-demo", arguments.get("--bucket"));
|
||||
assertEquals("run", arguments.get("--mode"));
|
||||
assertEquals("etl", arguments.get("--JOB_NAME"));
|
||||
assertEquals(run.getId(), arguments.get("--JOB_RUN_ID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staysRunningUntilTheScriptEnds() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
clock.advance(Duration.ofHours(1));
|
||||
|
||||
assertEquals("RUNNING", state("etl", run.getId()));
|
||||
runQueued();
|
||||
assertEquals("SUCCEEDED", state("etl", run.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsTheRunWithTheScriptsExitCode() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
runner.outcome = GlueScriptRunner.Outcome.exitedWith(3);
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
runQueued();
|
||||
|
||||
JobRun ended = service.getJobRun("etl", run.getId());
|
||||
assertEquals("FAILED", ended.getJobRunState());
|
||||
assertTrue(ended.getErrorMessage().contains("code 3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsTheRunWhenTheScriptCouldNotStart() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
runner.outcome = GlueScriptRunner.Outcome.couldNotStart("Could not read the script");
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
runQueued();
|
||||
|
||||
JobRun ended = service.getJobRun("etl", run.getId());
|
||||
assertEquals("FAILED", ended.getJobRunState());
|
||||
assertEquals("Could not read the script", ended.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timesTheRunOutWhenTheRunnerSaysItRanOutOfTime() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, 5);
|
||||
runner.outcome = GlueScriptRunner.Outcome.outOfTime();
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
runQueued();
|
||||
|
||||
JobRun ended = service.getJobRun("etl", run.getId());
|
||||
assertEquals("TIMEOUT", ended.getJobRunState());
|
||||
assertTrue(ended.getErrorMessage().contains("5 minutes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopsTheRunAndTheScriptsContainer() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
|
||||
GlueJobRunService.StopResult result = service.batchStopJobRun("etl", List.of(run.getId()));
|
||||
|
||||
assertEquals(1, result.stopped().size());
|
||||
assertEquals("STOPPED", state("etl", run.getId()));
|
||||
assertEquals(List.of(run.getId()), runner.stopped);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScriptThatEndsAfterAStopLeavesTheRunStopped() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
service.batchStopJobRun("etl", List.of(run.getId()));
|
||||
|
||||
runQueued();
|
||||
|
||||
assertEquals("STOPPED", state("etl", run.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotStartTheScriptOfARunThatWasStoppedFirst() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
service.batchStopJobRun("etl", List.of(run.getId()));
|
||||
|
||||
runner.cancelledSeen = null;
|
||||
runQueued();
|
||||
|
||||
assertEquals(Boolean.TRUE, runner.cancelledSeen);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsARunAnEarlierProcessLeftRunning() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
|
||||
GlueJobRunService restarted = new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock,
|
||||
regionResolver, runner, queued::add, "glue-image:5", null);
|
||||
JobRun read = restarted.getJobRun("etl", run.getId());
|
||||
|
||||
assertEquals("FAILED", read.getJobRunState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesOtherJobsToTheSimulation() {
|
||||
createJob("shell", "pythonshell", SCRIPT, null, null);
|
||||
createJob("local", "glueetl", "/tmp/job.py", null, null);
|
||||
|
||||
JobRun shell = service.startJobRun("shell", null, new JobRun());
|
||||
JobRun local = service.startJobRun("local", null, new JobRun());
|
||||
|
||||
assertEquals("SUCCEEDED", shell.getJobRunState());
|
||||
assertEquals("SUCCEEDED", local.getJobRunState());
|
||||
assertTrue(queued.isEmpty());
|
||||
assertNull(runner.cancelledSeen);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunOverridesTheJobsTimeoutForTheScript() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, 30);
|
||||
JobRun overrides = new JobRun();
|
||||
overrides.setTimeout(7);
|
||||
|
||||
service.startJobRun("etl", null, overrides);
|
||||
runQueued();
|
||||
|
||||
assertEquals(Duration.ofMinutes(7), runner.requests.getFirst().timeout());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJobWithoutATimeoutRunsItsScriptUnderTheDefaultCreateJobGives() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
|
||||
service.startJobRun("etl", null, new JobRun());
|
||||
runQueued();
|
||||
|
||||
assertEquals(Duration.ofMinutes(glueService.getJob("etl").getTimeout()), runner.requests.getFirst().timeout());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunnerThatThrowsFailsTheRunWithItsMessage() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
runner.failure = new IllegalStateException("docker is down");
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
runQueued();
|
||||
|
||||
JobRun ended = service.getJobRun("etl", run.getId());
|
||||
assertEquals("FAILED", ended.getJobRunState());
|
||||
assertEquals("docker is down", ended.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunTheExecutorRefusesFailsAtOnce() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
Executor refusing = task -> {
|
||||
throw new RejectedExecutionException("shut down");
|
||||
};
|
||||
GlueJobRunService stopping = new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock,
|
||||
regionResolver, runner, refusing, "glue-image:5", null);
|
||||
|
||||
JobRun run = stopping.startJobRun("etl", null, new JobRun());
|
||||
|
||||
assertEquals("FAILED", run.getJobRunState());
|
||||
assertEquals("Floci is shutting down", run.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunningScriptCountsAgainstMaxConcurrentRuns() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
service.startJobRun("etl", null, new JobRun());
|
||||
|
||||
assertFalse(service.hasCapacity("etl"));
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.startJobRun("etl", null, new JobRun()));
|
||||
assertEquals("ConcurrentRunsExceededException", refused.getErrorCode());
|
||||
|
||||
runQueued();
|
||||
assertTrue(service.hasCapacity("etl"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunsEndComesAfterTheLastPositionATriggerHasSeen() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
assertTrue(service.completionsAfter("etl", null).isEmpty());
|
||||
|
||||
runQueued();
|
||||
|
||||
List<GlueRunCompletion> completions = service.completionsAfter("etl", null);
|
||||
assertEquals(1, completions.size());
|
||||
assertEquals("SUCCEEDED", completions.getFirst().state());
|
||||
assertTrue(service.completionsAfter("etl", completions.getFirst().position()).isEmpty());
|
||||
assertEquals("SUCCEEDED", state("etl", run.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheJobStopsItsScriptAndALateEndChangesNothing() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
|
||||
service.deleteRuns("etl");
|
||||
runQueued();
|
||||
|
||||
assertEquals(List.of(run.getId()), runner.stopped);
|
||||
assertEquals(Boolean.TRUE, runner.cancelledSeen);
|
||||
assertTrue(runStore.get(run.getId()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoppedRunIsNotStoppedTwiceAndKeepsItsFirstEnd() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
service.batchStopJobRun("etl", List.of(run.getId()));
|
||||
|
||||
GlueJobRunService.StopResult again = service.batchStopJobRun("etl", List.of(run.getId()));
|
||||
|
||||
assertEquals(1, again.errors().size());
|
||||
assertEquals(List.of(run.getId()), runner.stopped);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScalaJobKeepsTheSimulationBecauseItsScriptIsNotPython() {
|
||||
createJob("scala", "glueetl", SCRIPT, Map.of("--job-language", "scala"), null);
|
||||
|
||||
JobRun run = service.startJobRun("scala", null, new JobRun());
|
||||
|
||||
assertEquals("SUCCEEDED", run.getJobRunState());
|
||||
assertTrue(queued.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunsOwnJobLanguageCanMakeItScalaToo() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun overrides = new JobRun();
|
||||
overrides.setArguments(Map.of("--job-language", "Scala"));
|
||||
|
||||
service.startJobRun("etl", null, overrides);
|
||||
|
||||
assertTrue(queued.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunStoppedByAResetOrShutdownRatherThanTheCallerFails() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
runner.outcome = GlueScriptRunner.Outcome.halted();
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
runQueued();
|
||||
|
||||
JobRun ended = service.getJobRun("etl", run.getId());
|
||||
assertEquals("FAILED", ended.getJobRunState());
|
||||
assertEquals("Floci stopped the job run before its script ended", ended.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamingJobKeepsTheSimulationEvenWithGlueEtlAndS3Script() {
|
||||
Job job = new Job();
|
||||
job.setName("stream");
|
||||
job.setRole(ROLE);
|
||||
JobCommand command = new JobCommand();
|
||||
command.setName("glueetl");
|
||||
command.setScriptLocation(SCRIPT);
|
||||
job.setCommand(command);
|
||||
job.setJobMode("STREAMING");
|
||||
glueService.createJob(job, null, REGION);
|
||||
|
||||
JobRun run = service.startJobRun("stream", null, new JobRun());
|
||||
|
||||
assertEquals("SUCCEEDED", run.getJobRunState());
|
||||
assertTrue(queued.isEmpty());
|
||||
assertTrue(runner.requests.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResetIgnoresAnInFlightScriptRunOutcome() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
runner.onRun = () -> {
|
||||
service.beforeReset();
|
||||
runStore.clear();
|
||||
bookkeeping.clear();
|
||||
};
|
||||
|
||||
runQueued();
|
||||
|
||||
assertTrue(runStore.get(run.getId()).isEmpty());
|
||||
assertTrue(bookkeeping.get(run.getId()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunnerErrorStillEndsTheRunFailedAndFreesCapacity() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
runner.error = new AssertionError("unexpected linkage error");
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
assertThrows(AssertionError.class, this::runQueued);
|
||||
|
||||
JobRun ended = service.getJobRun("etl", run.getId());
|
||||
assertEquals("FAILED", ended.getJobRunState());
|
||||
assertEquals("unexpected linkage error", ended.getErrorMessage());
|
||||
assertTrue(service.hasCapacity("etl"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedRunsWaitInWaitingUntilAConcurrencySlotFrees() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun queuing = new JobRun();
|
||||
queuing.setJobRunQueuingEnabled(true);
|
||||
|
||||
JobRun first = service.startJobRun("etl", null, queuing);
|
||||
JobRun second = service.startJobRun("etl", null, queuing);
|
||||
JobRun third = service.startJobRun("etl", null, queuing);
|
||||
|
||||
assertEquals("RUNNING", first.getJobRunState());
|
||||
assertEquals("WAITING", state("etl", second.getId()));
|
||||
assertEquals("WAITING", state("etl", third.getId()));
|
||||
assertEquals(1, queued.size());
|
||||
|
||||
// Finishing the first run launches only the second, keeping the third in WAITING.
|
||||
runQueued();
|
||||
assertEquals("SUCCEEDED", state("etl", first.getId()));
|
||||
assertEquals("RUNNING", state("etl", second.getId()));
|
||||
assertEquals("WAITING", state("etl", third.getId()));
|
||||
assertEquals(1, queued.size());
|
||||
|
||||
// Stopping the second run frees the slot and launches the third.
|
||||
service.batchStopJobRun("etl", List.of(second.getId()));
|
||||
assertEquals("STOPPED", state("etl", second.getId()));
|
||||
assertEquals("RUNNING", state("etl", third.getId()));
|
||||
assertEquals(2, queued.size());
|
||||
|
||||
runQueued();
|
||||
assertEquals("STOPPED", state("etl", second.getId()));
|
||||
assertEquals("SUCCEEDED", state("etl", third.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWaitingRunLeftByAnEarlierProcessFailsWhenReadAfterRestart() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
JobRun queuing = new JobRun();
|
||||
queuing.setJobRunQueuingEnabled(true);
|
||||
service.startJobRun("etl", null, queuing);
|
||||
JobRun waitingRun = service.startJobRun("etl", null, queuing);
|
||||
assertEquals("WAITING", waitingRun.getJobRunState());
|
||||
|
||||
GlueJobRunService restarted = new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock,
|
||||
regionResolver, runner, queued::add, "glue-image:5", null);
|
||||
JobRun read = restarted.getJobRun("etl", waitingRun.getId());
|
||||
|
||||
assertEquals("FAILED", read.getJobRunState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToSimulationWhenRunnerIsUnavailable() {
|
||||
createJob("etl", "glueetl", SCRIPT, null, null);
|
||||
runner.available = false;
|
||||
|
||||
JobRun run = service.startJobRun("etl", null, new JobRun());
|
||||
|
||||
assertEquals("SUCCEEDED", run.getJobRunState());
|
||||
assertTrue(queued.isEmpty());
|
||||
assertTrue(runner.requests.isEmpty());
|
||||
}
|
||||
|
||||
private static Map<String, String> pairs(List<String> arguments) {
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
for (int i = 0; i + 1 < arguments.size(); i += 2) {
|
||||
map.put(arguments.get(i), arguments.get(i + 1));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static final class FakeRunner implements GlueScriptRunner {
|
||||
final List<Run> requests = new ArrayList<>();
|
||||
final List<String> stopped = new ArrayList<>();
|
||||
GlueScriptRunner.Outcome outcome = Outcome.exitedWith(0);
|
||||
boolean available = true;
|
||||
Boolean cancelledSeen;
|
||||
RuntimeException failure;
|
||||
Error error;
|
||||
Runnable onRun;
|
||||
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return available;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Outcome run(Run run, Progress progress) {
|
||||
requests.add(run);
|
||||
if (onRun != null) {
|
||||
onRun.run();
|
||||
}
|
||||
if (error != null) {
|
||||
throw error;
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
cancelledSeen = progress.cancelled();
|
||||
return cancelledSeen ? Outcome.halted() : outcome;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(String runId) {
|
||||
stopped.add(runId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeLeftoverContainers() {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.floci.aws.services.glue;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.glue.model.JobRunBookkeeping;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class JobRunBookkeepingTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void aScriptRunSurvivesStorage() throws Exception {
|
||||
JobRunBookkeeping bookkeeping = new JobRunBookkeeping();
|
||||
bookkeeping.setScriptRun(true);
|
||||
|
||||
JobRunBookkeeping read = mapper.readValue(mapper.writeValueAsString(bookkeeping), JobRunBookkeeping.class);
|
||||
|
||||
assertTrue(read.isScriptRun());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bookkeepingStoredBeforeScriptRunsExistReadsAsNoScriptRun() throws Exception {
|
||||
String stored = "{\"completionOrder\":4,\"originRunId\":\"jr_1\",\"workflowRunId\":null}";
|
||||
|
||||
JobRunBookkeeping read = mapper.readValue(stored, JobRunBookkeeping.class);
|
||||
|
||||
assertFalse(read.isScriptRun());
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,9 @@ import java.util.Map;
|
||||
* forwards to its targets, and {@code floci.services.elbv2.backend-keep-alive=false} opens a
|
||||
* fresh connection to the target for every request it forwards.
|
||||
* {@code ElbV2BackendNoKeepAliveIntegrationTest} relies on both.</li>
|
||||
* <li>{@code floci.services.glue.runner-mode=docker} runs a Spark job's script through the Docker
|
||||
* runner rather than simulating the run. {@code GlueScriptRunIntegrationTest} relies on it, with
|
||||
* the container replaced by a mock runner.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Each override is inert for the other classes. Each one is read by a single service: the
|
||||
@@ -84,7 +87,7 @@ import java.util.Map;
|
||||
* Neptune cluster creation, Route53 VPC association and authorization, CloudFront origin fetches,
|
||||
* Cognito app client validation, the Scheduler dispatcher, the RDS Data API and Aurora auto-pause,
|
||||
* Firehose delivery, the Lambda runtime image resolver, the IoT MQTT broker, EC2, SageMaker
|
||||
* training jobs, Bedrock Runtime, ElastiCache, Service Quotas and the ELBv2 data plane, which
|
||||
* training jobs, Bedrock Runtime, ElastiCache, Service Quotas, Glue job runs and the ELBv2 data plane, which
|
||||
* only acts once a class creates a listener or registers a target. Each class is the only one here
|
||||
* that calls its service, so no override reaches another class. Strict claiming is read for every
|
||||
* request, but only changes the answer to an RPC-signaled request no protocol claims, which only
|
||||
@@ -134,7 +137,8 @@ public class IndependentServiceSettingsProfile implements QuarkusTestProfile {
|
||||
Map.entry("floci.protocols.strict-claiming", "true"),
|
||||
Map.entry("floci.services.servicequotas.standard-on-demand-vcpus", "7"),
|
||||
Map.entry("floci.services.elbv2.mock", "false"),
|
||||
Map.entry("floci.services.elbv2.backend-keep-alive", "false")));
|
||||
Map.entry("floci.services.elbv2.backend-keep-alive", "false"),
|
||||
Map.entry("floci.services.glue.runner-mode", "docker")));
|
||||
overrides.putAll(new YamlConfigSource("runtime-images", """
|
||||
floci:
|
||||
services:
|
||||
|
||||
Reference in new issue
Block a user