File tree Expand file tree Collapse file tree
JShellAPI/src/main/java/org/togetherjava/jshellapi/service Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1313import java .nio .charset .StandardCharsets ;
1414import java .time .Duration ;
1515import java .util .Arrays ;
16+ import java .util .Map ;
1617import java .util .Set ;
18+ import java .util .UUID ;
1719import java .util .concurrent .TimeUnit ;
1820
1921@ Service
2022public class DockerService implements AutoCloseable {
2123
24+ private static final String WORKER_LABEL = "jshell-api-worker" ;
25+ private static final UUID WORKER_UNIQUE_ID = UUID .randomUUID ();
26+
2227 private final DockerClient client ;
2328
2429 public DockerService () {
@@ -30,6 +35,19 @@ public DockerService() {
3035 .connectionTimeout (Duration .ofSeconds (60 ))
3136 .build ();
3237 this .client = DockerClientImpl .getInstance (clientConfig , httpClient );
38+
39+ cleanupLeftovers ();
40+ }
41+
42+ private void cleanupLeftovers () {
43+ for (Container container : client .listContainersCmd ().withLabelFilter (Set .of (WORKER_LABEL )).exec ()) {
44+ String containerHumanName = container .getId () + " " + Arrays .toString (container .getNames ());
45+ System .out .println ("Found worker container " + containerHumanName );
46+ if (!container .getLabels ().get (WORKER_LABEL ).equals (WORKER_UNIQUE_ID .toString ())) {
47+ System .out .println ("Killing container " + containerHumanName );
48+ client .killContainerCmd (container .getId ()).exec ();
49+ }
50+ }
3351 }
3452
3553 public String spawnContainer (
@@ -68,6 +86,7 @@ public String spawnContainer(
6886 .withAttachStderr (true )
6987 .withAttachStdout (true )
7088 .withEnv ("evalTimeoutSeconds=" + evalTimeout .toSeconds (), "sysOutCharLimit=" + sysoutLimit )
89+ .withLabels (Map .of (WORKER_LABEL , WORKER_UNIQUE_ID .toString ()))
7190 .withName (name )
7291 .exec ()
7392 .getId ();
You can’t perform that action at this time.
0 commit comments