com.spotify.docker.client.messages.ContainerExit Java Examples

The following examples show how to use com.spotify.docker.client.messages.ContainerExit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerExit waitContainer(final String containerId)
    throws DockerException, InterruptedException {
  try {
    final WebTarget resource = noTimeoutResource()
        .path("containers").path(containerId).path("wait");
    // Wait forever
    return request(POST, ContainerExit.class, resource,
                   resource.request(APPLICATION_JSON_TYPE));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 404:
        throw new ContainerNotFoundException(containerId, e);
      default:
        throw e;
    }
  }
}
 
Example #2
Source File: JobExpirationTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
  startDefaultMaster();

  final HeliosClient client = defaultClient();

  startDefaultAgent(testHost());
  awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS);

  final JobId jobId = createJob(testJobName, testJobVersion, BUSYBOX, IDLE_COMMAND,
      DateTime.now().plusSeconds(10).toDate());

  deployJob(jobId, testHost());

  // Make sure the job runs
  final TaskStatus taskStatus = awaitJobState(
      client,
      testHost(),
      jobId,
      RUNNING,
      WAIT_TIMEOUT_SECONDS,
      SECONDS);

  // Then make sure it expires
  Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable<JobId>() {
    @Override
    public JobId call() throws Exception {
      if (client.jobs().get().containsKey(jobId)) {
        return null; // job still exists, return null to continue polling
      } else {
        return jobId; // job no longer exists, return non-null to exit polling
      }
    }
  });

  // Wait for the agent to kill the container
  final ContainerExit exit = docker.waitContainer(taskStatus.getContainerId());
  assertThat(exit.statusCode(), is(0L));
}
 
Example #3
Source File: ReapingTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
  startDefaultMaster();

  final String id = "test-" + toHexString(new SecureRandom().nextInt());
  final String namespace = "helios-" + id;
  final String intruder1 = intruder(namespace);
  final String intruder2 = intruder(namespace);

  // Start a container in the agent namespace
  startContainer(intruder1);

  // Start agent
  final HeliosClient client = defaultClient();
  startDefaultAgent(testHost(), "--id=" + id);
  awaitHostRegistered(client, testHost(), LONG_WAIT_SECONDS, SECONDS);
  awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS);

  // With LXC, killing a container results in exit code 0.
  // In docker 1.5 killing a container results in exit code 137, in previous versions it's -1.
  final String executionDriver = docker.info().executionDriver();
  final List<Long> expectedExitCodes =
      (executionDriver != null && executionDriver.startsWith("lxc-"))
      ? Collections.singletonList(0L) : asList(-1L, 137L);

  // Wait for the agent to kill the container
  final ContainerExit exit1 = docker.waitContainer(intruder1);
  assertThat(exit1.statusCode(), isIn(expectedExitCodes));

  // Start another container in the agent namespace
  startContainer(intruder2);

  // Wait for the agent to kill the second container as well
  final ContainerExit exit2 = docker.waitContainer(intruder2);
  assertThat(exit2.statusCode(), isIn(expectedExitCodes));
}
 
Example #4
Source File: PollingDockerClient.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerExit waitContainer(final String containerId)
    throws DockerException, InterruptedException {
  // XXX (dano): We're doing this poll loop instead of docker.waitContainer() because we saw the
  //             agent hang forever on waitContainer after the socket got into a weird half-open
  //             state where the kernel (netstat/lsof) would only show one end of the connection
  //             and restarting docker would not close the socket. ¯\_(ツ)_/¯
  while (true) {
    final ContainerInfo info = inspectContainer(containerId);
    if (!info.state().running()) {
      return ContainerExit.create(info.state().exitCode());
    }
    Thread.sleep(WAIT_INSPECT_INTERVAL_MILLIS);
  }
}
 
Example #5
Source File: SupervisorTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void verifySupervisorRestartsExitedContainer() throws Exception {
  final String containerId1 = "deadbeef1";
  final String containerId2 = "deadbeef2";

  final ContainerCreation createResponse1 = ContainerCreation.builder().id(containerId1).build();
  final ContainerCreation createResponse2 = ContainerCreation.builder().id(containerId2).build();

  when(docker.createContainer(any(ContainerConfig.class), any(String.class)))
      .thenReturn(createResponse1);

  final ImageInfo imageInfo = mock(ImageInfo.class);
  when(docker.inspectImage(IMAGE)).thenReturn(imageInfo);

  when(docker.inspectContainer(eq(containerId1))).thenReturn(runningResponse);

  final SettableFuture<ContainerExit> waitFuture1 = SettableFuture.create();
  final SettableFuture<ContainerExit> waitFuture2 = SettableFuture.create();
  when(docker.waitContainer(containerId1)).thenAnswer(futureAnswer(waitFuture1));
  when(docker.waitContainer(containerId2)).thenAnswer(futureAnswer(waitFuture2));

  // Start the job
  sut.setGoal(START);
  verify(docker, timeout(30000)).createContainer(any(ContainerConfig.class), any(String.class));
  verify(docker, timeout(30000)).startContainer(eq(containerId1));
  verify(docker, timeout(30000)).waitContainer(containerId1);

  // Indicate that the container exited
  when(docker.inspectContainer(eq(containerId1))).thenReturn(stoppedResponse);
  when(docker.createContainer(any(ContainerConfig.class), any(String.class)))
      .thenReturn(createResponse2);
  when(docker.inspectContainer(eq(containerId2))).thenReturn(runningResponse);
  waitFuture1.set(ContainerExit.create(1L));

  // Verify that the container was restarted
  verify(docker, timeout(30000)).createContainer(any(ContainerConfig.class), any(String.class));
  verify(docker, timeout(30000)).startContainer(eq(containerId2));
  verify(docker, timeout(30000)).waitContainer(containerId2);
}
 
Example #6
Source File: HeliosSoloDeploymentTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  this.dockerClient = mock(DockerClient.class);
  this.heliosClient = mock(HeliosClient.class);

  // the anonymous classes to override a method are to workaround the docker-client "messages"
  // having no mutators, fun
  final Info info = mock(Info.class);
  when(info.operatingSystem()).thenReturn("foo");
  when(this.dockerClient.info()).thenReturn(info);

  // mock the call to dockerClient.createContainer so we can test the arguments passed to it
  this.containerConfig = ArgumentCaptor.forClass(ContainerConfig.class);

  final ContainerCreation creation = mock(ContainerCreation.class);
  when(creation.id()).thenReturn(CONTAINER_ID);

  when(this.dockerClient.createContainer(
      this.containerConfig.capture(), anyString())).thenReturn(creation);

  // we have to mock out several other calls to get the HeliosSoloDeployment ctor
  // to return non-exceptionally. the anonymous classes to override a method are to workaround
  // the docker-client "messages" having no mutators, fun
  when(this.dockerClient.info()).thenReturn(info);

  final PortBinding binding = PortBinding.of("192.168.1.1", 5801);
  final ImmutableMap<String, List<PortBinding>> ports =
      ImmutableMap.<String, List<PortBinding>>of("5801/tcp", ImmutableList.of(binding));
  final ContainerInfo containerInfo = mock(ContainerInfo.class);
  final NetworkSettings networkSettings = mock(NetworkSettings.class);
  when(networkSettings.gateway()).thenReturn("a-gate-way");
  when(networkSettings.ports()).thenReturn(ports);
  when(containerInfo.networkSettings()).thenReturn(networkSettings);
  when(this.dockerClient.inspectContainer(CONTAINER_ID)).thenReturn(containerInfo);

  when(this.dockerClient.waitContainer(CONTAINER_ID)).thenReturn(ContainerExit.create(0L));
}
 
Example #7
Source File: RunnablePipelineContainer.java    From repairnator with MIT License 4 votes vote down vote up
public ContainerExit getExitStatus() {
    return exitStatus;
}
 
Example #8
Source File: SupervisorTest.java    From helios with Apache License 2.0 4 votes vote down vote up
@Test
public void verifySupervisorStartsAndStopsDockerContainer() throws Exception {
  final String containerId = "deadbeef";

  when(docker.createContainer(any(ContainerConfig.class), any(String.class)))
      .thenReturn(ContainerCreation.builder().id(containerId).build());

  final ImageInfo imageInfo = mock(ImageInfo.class);
  when(docker.inspectImage(IMAGE)).thenReturn(imageInfo);

  // Have waitContainer wait forever.
  final SettableFuture<ContainerExit> waitFuture = SettableFuture.create();
  when(docker.waitContainer(containerId)).thenAnswer(futureAnswer(waitFuture));

  // Start the job
  sut.setGoal(START);

  // Verify that the container is created
  verify(docker, timeout(30000)).createContainer(containerConfigCaptor.capture(),
      containerNameCaptor.capture());
  verify(model, timeout(30000)).setTaskStatus(eq(JOB.getId()),
      eq(TaskStatus.newBuilder()
          .setJob(JOB)
          .setGoal(START)
          .setState(CREATING)
          .setContainerId(null)
          .setEnv(ENV)
          .build())
  );
  final ContainerConfig containerConfig = containerConfigCaptor.getValue();
  assertEquals(IMAGE, containerConfig.image());
  assertEquals(EXPECTED_CONTAINER_ENV, ImmutableSet.copyOf(containerConfig.env()));
  final String containerName = containerNameCaptor.getValue();

  assertEquals(JOB.getId().toShortString(), shortJobIdFromContainerName(containerName));

  // Verify that the container is started
  verify(docker, timeout(30000)).startContainer(eq(containerId));
  verify(model, timeout(30000)).setTaskStatus(eq(JOB.getId()),
      eq(TaskStatus.newBuilder()
          .setJob(JOB)
          .setGoal(START)
          .setState(STARTING)
          .setContainerId(containerId)
          .setEnv(ENV)
          .build())
  );
  when(docker.inspectContainer(eq(containerId))).thenReturn(runningResponse);

  verify(docker, timeout(30000)).waitContainer(containerId);
  verify(model, timeout(30000)).setTaskStatus(eq(JOB.getId()),
      eq(TaskStatus.newBuilder()
          .setJob(JOB)
          .setGoal(START)
          .setState(RUNNING)
          .setContainerId(containerId)
          .setEnv(ENV)
          .build())
  );

  // Stop the job
  sut.setGoal(STOP);
  verify(docker, timeout(30000)).stopContainer(
      eq(containerId), eq(Supervisor.DEFAULT_SECONDS_TO_WAIT_BEFORE_KILL));

  // Change docker container state to stopped now that it was killed
  when(docker.inspectContainer(eq(containerId))).thenReturn(stoppedResponse);

  // Verify that the pulling state is signalled
  verify(model, timeout(30000)).setTaskStatus(eq(JOB.getId()),
      eq(TaskStatus.newBuilder()
          .setJob(JOB)
          .setGoal(START)
          .setState(PULLING_IMAGE)
          .setContainerId(null)
          .setEnv(ENV)
          .build())
  );

  // Verify that the STOPPING and STOPPED states are signalled
  verify(model, timeout(30000)).setTaskStatus(eq(JOB.getId()),
      eq(TaskStatus.newBuilder()
          .setJob(JOB)
          .setGoal(STOP)
          .setState(STOPPING)
          .setContainerId(containerId)
          .setEnv(ENV)
          .build())
  );

  verify(model, timeout(30000)).setTaskStatus(eq(JOB.getId()),
      eq(TaskStatus.newBuilder()
          .setJob(JOB)
          .setGoal(STOP)
          .setState(STOPPED)
          .setContainerId(containerId)
          .setEnv(ENV)
          .build())
  );
}
 
Example #9
Source File: SupervisorTest.java    From helios with Apache License 2.0 4 votes vote down vote up
@Test
public void verifySupervisorStopsDockerContainerWithConfiguredKillTime() throws Exception {
  final String containerId = "deadbeef";

  final Job longKillTimeJob = Job.newBuilder()
      .setName(NAME)
      .setCommand(COMMAND)
      .setImage(IMAGE)
      .setVersion(VERSION)
      .setSecondsToWaitBeforeKill(30)
      .build();

  mockTaskStatus(longKillTimeJob.getId());

  final Supervisor longKillTimeSupervisor = createSupervisor(longKillTimeJob);

  when(docker.createContainer(any(ContainerConfig.class), any(String.class)))
      .thenReturn(ContainerCreation.builder().id(containerId).build());

  final ImageInfo imageInfo = mock(ImageInfo.class);
  when(docker.inspectImage(IMAGE)).thenReturn(imageInfo);

  // Have waitContainer wait forever.
  final SettableFuture<ContainerExit> waitFuture = SettableFuture.create();
  when(docker.waitContainer(containerId)).thenAnswer(futureAnswer(waitFuture));

  // Start the job (so that a runner exists)
  longKillTimeSupervisor.setGoal(START);
  when(docker.inspectContainer(eq(containerId))).thenReturn(runningResponse);

  // This is already verified above, but it works as a hack to wait for the model/docker state
  // to converge in such a way that a setGoal(STOP) will work. :|
  verify(docker, timeout(30000)).waitContainer(containerId);

  // Stop the job
  longKillTimeSupervisor.setGoal(STOP);
  verify(docker, timeout(30000)).stopContainer(
      eq(containerId), eq(longKillTimeJob.getSecondsToWaitBeforeKill()));

  // Change docker container state to stopped now that it was killed
  when(docker.inspectContainer(eq(containerId))).thenReturn(stoppedResponse);
}
 
Example #10
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Wait for a docker container to exit.
 *
 * @param containerId The id of the container to wait for.
 * @return Exit response with status code.
 * @throws ContainerNotFoundException
 *                              if container is not found (404)
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
ContainerExit waitContainer(String containerId) throws DockerException, InterruptedException;