Search in sources :

Example 1 with ContainerState

use of com.spotify.docker.client.messages.ContainerState in project kie-wb-common by kiegroup.

the class DockerRuntimeManager method refresh.

@Override
public void refresh(RuntimeId runtimeId) throws RuntimeOperationException {
    DockerRuntime runtime = (DockerRuntime) runtimeRegistry.getRuntimeById(runtimeId.getId());
    try {
        ContainerInfo containerInfo = docker.getDockerClient(runtime.getProviderId()).inspectContainer(runtime.getId());
        ContainerState state = containerInfo.state();
        String stateString = STOPPED;
        if (state.running() && !state.paused()) {
            stateString = RUNNING;
        } else if (state.paused()) {
            stateString = "Paused";
        } else if (state.restarting()) {
            stateString = "Restarting";
        } else if (state.oomKilled()) {
            stateString = "Killed";
        }
        DockerRuntime newRuntime = new DockerRuntime(runtime.getId(), runtime.getName(), runtime.getConfig(), runtime.getProviderId(), runtime.getEndpoint(), runtime.getInfo(), new DockerRuntimeState(stateString, state.startedAt().toString()));
        runtimeRegistry.registerRuntime(newRuntime);
    } catch (DockerException | InterruptedException ex) {
        LOG.error("Error Refreshing container: " + runtimeId.getId(), ex);
        throw new RuntimeOperationException("Error Refreshing container: " + runtimeId.getId(), ex);
    }
}
Also used : DockerRuntime(org.guvnor.ala.docker.model.DockerRuntime) DockerException(com.spotify.docker.client.DockerException) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) DockerRuntimeState(org.guvnor.ala.docker.model.DockerRuntimeState) RuntimeOperationException(org.guvnor.ala.exceptions.RuntimeOperationException) ContainerState(com.spotify.docker.client.messages.ContainerState)

Example 2 with ContainerState

use of com.spotify.docker.client.messages.ContainerState in project helios by spotify.

the class TaskRunner method run0.

private long run0() throws InterruptedException, DockerException {
    // Delay
    Thread.sleep(delayMillis);
    // Check if the container is already running
    final ContainerInfo info = getContainerInfo(existingContainerId);
    final String containerId;
    if (info != null && info.state().running()) {
        containerId = existingContainerId;
        this.containerId = Optional.of(existingContainerId);
    } else {
        // Create and start container if necessary
        containerId = createAndStartContainer();
        this.containerId = Optional.of(containerId);
        if (healthChecker.isPresent()) {
            listener.healthChecking();
            final RetryScheduler retryScheduler = BoundedRandomExponentialBackoff.newBuilder().setMinIntervalMillis(SECONDS.toMillis(1)).setMaxIntervalMillis(SECONDS.toMillis(30)).build().newScheduler();
            while (!healthChecker.get().check(containerId)) {
                final ContainerState state = getContainerState(containerId);
                if (state == null) {
                    final String err = "container " + containerId + " was not found during health " + "checking, or has no State object";
                    log.warn(err);
                    throw new RuntimeException(err);
                }
                if (!state.running()) {
                    final String err = "container " + containerId + " exited during health checking. " + "Exit code: " + state.exitCode() + ", Config: " + config;
                    log.warn(err);
                    listener.exited(state.exitCode());
                    throw new RuntimeException(err);
                }
                final long retryMillis = retryScheduler.nextMillis();
                log.warn("container failed healthcheck, will retry in {}ms: {}: {}", retryMillis, config, containerId);
                Thread.sleep(retryMillis);
            }
            log.info("healthchecking complete of containerId={} taskConfig={}", containerId, config);
        } else {
            log.info("no healthchecks configured for containerId={} taskConfig={}", containerId, config);
        }
    }
    listener.running();
    // Register and wait for container to exit
    serviceRegistrationHandle = Optional.fromNullable(registrar.register(config.registration()));
    final ContainerExit exit;
    try {
        exit = docker.waitContainer(containerId);
    } finally {
        unregister();
        this.containerId = Optional.absent();
    }
    log.info("container exited: {}: {}: {}", config, containerId, exit.statusCode());
    listener.exited(exit.statusCode());
    return exit.statusCode();
}
Also used : HeliosRuntimeException(com.spotify.helios.common.HeliosRuntimeException) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) ContainerExit(com.spotify.docker.client.messages.ContainerExit) ContainerState(com.spotify.docker.client.messages.ContainerState)

Example 3 with ContainerState

use of com.spotify.docker.client.messages.ContainerState in project helios by spotify.

the class GracePeriodTest method setup.

@Before
public void setup() throws Exception {
    final ContainerState runningState = Mockito.mock(ContainerState.class);
    when(runningState.running()).thenReturn(true);
    when(runningResponse.state()).thenReturn(runningState);
    when(runningResponse.networkSettings()).thenReturn(mock(NetworkSettings.class));
    final ContainerState stoppedState = Mockito.mock(ContainerState.class);
    when(stoppedState.running()).thenReturn(false);
    when(stoppedResponse.state()).thenReturn(stoppedState);
    when(retryPolicy.delay(any(ThrottleState.class))).thenReturn(10L);
    when(registrar.register(any(ServiceRegistration.class))).thenReturn(new NopServiceRegistrationHandle());
    final TaskConfig config = TaskConfig.builder().namespace(NAMESPACE).host("AGENT_NAME").job(JOB).envVars(ENV).defaultRegistrationDomain("domain").build();
    final TaskStatus.Builder taskStatus = TaskStatus.newBuilder().setJob(JOB).setEnv(ENV).setPorts(PORTS);
    final StatusUpdater statusUpdater = new DefaultStatusUpdater(model, taskStatus);
    final TaskMonitor monitor = new TaskMonitor(JOB.getId(), FlapController.create(), statusUpdater);
    final TaskRunnerFactory runnerFactory = TaskRunnerFactory.builder().registrar(registrar).config(config).dockerClient(docker).listener(monitor).build();
    sut = Supervisor.newBuilder().setJob(JOB).setStatusUpdater(statusUpdater).setDockerClient(docker).setRestartPolicy(retryPolicy).setRunnerFactory(runnerFactory).setMetrics(new NoopSupervisorMetrics()).setMonitor(monitor).setSleeper(sleeper).build();
    final ConcurrentMap<JobId, TaskStatus> statusMap = Maps.newConcurrentMap();
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(final InvocationOnMock invocationOnMock) {
            final Object[] arguments = invocationOnMock.getArguments();
            final JobId jobId = (JobId) arguments[0];
            final TaskStatus status = (TaskStatus) arguments[1];
            statusMap.put(jobId, status);
            return null;
        }
    }).when(model).setTaskStatus(eq(JOB.getId()), taskStatusCaptor.capture());
    when(model.getTaskStatus(eq(JOB.getId()))).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
            final JobId jobId = (JobId) invocationOnMock.getArguments()[0];
            return statusMap.get(jobId);
        }
    });
}
Also used : ThrottleState(com.spotify.helios.common.descriptors.ThrottleState) TaskStatus(com.spotify.helios.common.descriptors.TaskStatus) ContainerState(com.spotify.docker.client.messages.ContainerState) NetworkSettings(com.spotify.docker.client.messages.NetworkSettings) InvocationOnMock(org.mockito.invocation.InvocationOnMock) NoopSupervisorMetrics(com.spotify.helios.servicescommon.statistics.NoopSupervisorMetrics) JobId(com.spotify.helios.common.descriptors.JobId) ServiceRegistration(com.spotify.helios.serviceregistration.ServiceRegistration) NopServiceRegistrationHandle(com.spotify.helios.serviceregistration.NopServiceRegistrationHandle) Before(org.junit.Before)

Example 4 with ContainerState

use of com.spotify.docker.client.messages.ContainerState in project helios by spotify.

the class TaskRunnerTest method testContainerNotRunningVariation.

@Test
public void testContainerNotRunningVariation() throws Throwable {
    final TaskRunner.NopListener mockListener = mock(TaskRunner.NopListener.class);
    final ImageInfo mockImageInfo = mock(ImageInfo.class);
    final ContainerCreation mockCreation = mock(ContainerCreation.class);
    final HealthChecker mockHealthChecker = mock(HealthChecker.class);
    final ContainerState stoppedState = mock(ContainerState.class);
    when(stoppedState.running()).thenReturn(false);
    when(stoppedState.error()).thenReturn("container is a potato");
    final ContainerInfo stopped = mock(ContainerInfo.class);
    when(stopped.state()).thenReturn(stoppedState);
    when(mockCreation.id()).thenReturn("potato");
    when(mockDocker.inspectContainer(anyString())).thenReturn(stopped);
    when(mockDocker.inspectImage(IMAGE)).thenReturn(mockImageInfo);
    when(mockDocker.createContainer(any(ContainerConfig.class), anyString())).thenReturn(mockCreation);
    when(mockHealthChecker.check(anyString())).thenReturn(false);
    final TaskRunner tr = TaskRunner.builder().delayMillis(0).config(TaskConfig.builder().namespace("test").host(HOST).job(JOB).containerDecorators(ImmutableList.of(containerDecorator)).build()).docker(mockDocker).listener(mockListener).healthChecker(mockHealthChecker).build();
    tr.run();
    try {
        tr.resultFuture().get();
        fail("this should throw");
    } catch (Exception t) {
        assertTrue(t instanceof ExecutionException);
        assertEquals(RuntimeException.class, t.getCause().getClass());
        verify(mockListener).failed(t.getCause(), "container is a potato");
    }
}
Also used : ContainerConfig(com.spotify.docker.client.messages.ContainerConfig) ContainerCreation(com.spotify.docker.client.messages.ContainerCreation) HeliosRuntimeException(com.spotify.helios.common.HeliosRuntimeException) ContainerInfo(com.spotify.docker.client.messages.ContainerInfo) ImageInfo(com.spotify.docker.client.messages.ImageInfo) ExecutionException(java.util.concurrent.ExecutionException) ContainerState(com.spotify.docker.client.messages.ContainerState) HeliosRuntimeException(com.spotify.helios.common.HeliosRuntimeException) DockerException(com.spotify.docker.client.exceptions.DockerException) ImageNotFoundException(com.spotify.docker.client.exceptions.ImageNotFoundException) DockerTimeoutException(com.spotify.docker.client.exceptions.DockerTimeoutException) ExecutionException(java.util.concurrent.ExecutionException) ImagePullFailedException(com.spotify.docker.client.exceptions.ImagePullFailedException) Test(org.junit.Test)

Example 5 with ContainerState

use of com.spotify.docker.client.messages.ContainerState in project helios by spotify.

the class SupervisorTest method setup.

@Before
public void setup() throws Exception {
    final ContainerState runningState = mock(ContainerState.class);
    when(runningState.running()).thenReturn(true);
    when(runningResponse.state()).thenReturn(runningState);
    when(runningResponse.networkSettings()).thenReturn(mock(NetworkSettings.class));
    final ContainerState stoppedState = mock(ContainerState.class);
    when(stoppedState.running()).thenReturn(false);
    when(stoppedResponse.state()).thenReturn(stoppedState);
    when(retryPolicy.delay(any(ThrottleState.class))).thenReturn(10L);
    sut = createSupervisor(JOB);
    mockTaskStatus(JOB.getId());
}
Also used : NetworkSettings(com.spotify.docker.client.messages.NetworkSettings) ThrottleState(com.spotify.helios.common.descriptors.ThrottleState) ContainerState(com.spotify.docker.client.messages.ContainerState) Before(org.junit.Before)

Aggregations

ContainerState (com.spotify.docker.client.messages.ContainerState)5 ContainerInfo (com.spotify.docker.client.messages.ContainerInfo)3 NetworkSettings (com.spotify.docker.client.messages.NetworkSettings)2 HeliosRuntimeException (com.spotify.helios.common.HeliosRuntimeException)2 ThrottleState (com.spotify.helios.common.descriptors.ThrottleState)2 Before (org.junit.Before)2 DockerException (com.spotify.docker.client.DockerException)1 DockerException (com.spotify.docker.client.exceptions.DockerException)1 DockerTimeoutException (com.spotify.docker.client.exceptions.DockerTimeoutException)1 ImageNotFoundException (com.spotify.docker.client.exceptions.ImageNotFoundException)1 ImagePullFailedException (com.spotify.docker.client.exceptions.ImagePullFailedException)1 ContainerConfig (com.spotify.docker.client.messages.ContainerConfig)1 ContainerCreation (com.spotify.docker.client.messages.ContainerCreation)1 ContainerExit (com.spotify.docker.client.messages.ContainerExit)1 ImageInfo (com.spotify.docker.client.messages.ImageInfo)1 JobId (com.spotify.helios.common.descriptors.JobId)1 TaskStatus (com.spotify.helios.common.descriptors.TaskStatus)1 NopServiceRegistrationHandle (com.spotify.helios.serviceregistration.NopServiceRegistrationHandle)1 ServiceRegistration (com.spotify.helios.serviceregistration.ServiceRegistration)1 NoopSupervisorMetrics (com.spotify.helios.servicescommon.statistics.NoopSupervisorMetrics)1