TerminationLogging implements TerminationHook { @Override public void accept(Integer exitCode) { final Map<String, String> env = System.getenv(); final String terminationLog = env.get("STYX_TERMINATION_LOG"); if (terminationLog == null) { return; } final String content = String.format("{\"component_id\": \"%s\"," + "\"workflow_id\": \"%s\"," + "\"parameter\": \"%s\"," + "\"execution_id\": \"%s\"," + "\"event\": \"exited\"," + "\"exit_code\": %d}", env.getOrDefault("STYX_COMPONENT_ID", "UNKNOWN_COMPONENT_ID"), env.getOrDefault("STYX_WORKFLOW_ID", "UNKNOWN_WORKFLOW_ID"), env.getOrDefault("STYX_PARAMETER", "UNKNOWN_PARAMETER"), env.getOrDefault("STYX_EXECUTION_ID", "UNKNOWN_EXECUTION_ID"), exitCode); final Path path = Paths.get(terminationLog); try { Files.write(path, content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { LOG.error("Could not write termination log to {}.", path, e); throw new RuntimeException(e); } }  @Override void accept(Integer exitCode);  }
@Test public void shouldNotWriteFileIfNoTerminationLog() throws IOException { final Path tempFile = Files.createTempFile("termination-log-", ""); tempFile.toFile().deleteOnExit(); terminationHook.accept(20); final String content = new String(Files.readAllBytes(tempFile)); assertThat(content, is("")); }
@Test public void shouldWriteToTerminationLog() throws IOException { final Path tempFile = Files.createTempFile("termination-log-", ""); tempFile.toFile().deleteOnExit(); environmentVariables.set(STYX_TERMINATION_LOG, tempFile.toString()); final String expected = "{\"component_id\": \"foo\"," + "\"workflow_id\": \"bar\"," + "\"parameter\": \"2018-01-01\"," + "\"execution_id\": \"foobar\"," + "\"event\": \"exited\"," + "\"exit_code\": 20}"; terminationHook.accept(20); final String content = new String(Files.readAllBytes(tempFile)); assertThat(content, is(expected)); }
@Test public void shouldWriteToTerminationLogWithDefaultValues() throws IOException { final Path tempFile = Files.createTempFile("termination-log-", ""); tempFile.toFile().deleteOnExit(); environmentVariables.set(STYX_TERMINATION_LOG, tempFile.toString()); environmentVariables .clear(STYX_COMPONENT_ID, STYX_WORKFLOW_ID, STYX_PARAMETER, STYX_EXECUTION_ID); final String expected = "{\"component_id\": \"UNKNOWN_COMPONENT_ID\"," + "\"workflow_id\": \"UNKNOWN_WORKFLOW_ID\"," + "\"parameter\": \"UNKNOWN_PARAMETER\"," + "\"execution_id\": \"UNKNOWN_EXECUTION_ID\"," + "\"event\": \"exited\"," + "\"exit_code\": 20}"; terminationHook.accept(20); final String content = new String(Files.readAllBytes(tempFile)); assertThat(content, is(expected)); }
@Test(expected = RuntimeException.class) public void shouldFailToWriteTerminationLog() { environmentVariables.set(STYX_TERMINATION_LOG, "."); terminationHook.accept(20); }