com.github.dockerjava.api.command.InspectContainerResponse.ContainerState Java Examples

The following examples show how to use com.github.dockerjava.api.command.InspectContainerResponse.ContainerState. 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: GenericContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldReportOOMAfterWait() {
    try (
        GenericContainer container = new GenericContainer<>()
            .withStartupCheckStrategy(new NoopStartupCheckStrategy())
            .waitingFor(new WaitForExitedState(ContainerState::getOOMKilled))
            .withCreateContainerCmdModifier(it -> {
                it.getHostConfig()
                    .withMemory(20 * FileUtils.ONE_MB)
                    .withMemorySwappiness(0L)
                    .withMemorySwap(0L)
                    .withMemoryReservation(0L)
                    .withKernelMemory(16 * FileUtils.ONE_MB);
            })
            .withCommand("sh", "-c", "A='0123456789'; for i in $(seq 0 32); do A=$A$A; done; sleep 10m")
    ) {
        assertThatThrownBy(container::start)
            .hasStackTraceContaining("Container crashed with out-of-memory");
    }
}
 
Example #2
Source File: GenericContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Override
@SneakyThrows
protected void waitUntilReady() {
    Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, () -> {
        ContainerState state = waitStrategyTarget.getCurrentContainerInfo().getState();

        log.debug("Current state: {}", state);
        if (!"exited".equalsIgnoreCase(state.getStatus())) {
            Thread.sleep(100);
            return false;
        }
        return predicate.test(state);
    });

    throw new IllegalStateException("Nope!");
}
 
Example #3
Source File: DockerHandler.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
throws TargetException {

	boolean result = false;
	try {
		DockerClient dockerClient = DockerUtils.createDockerClient( parameters.getTargetProperties());
		ContainerState state = DockerUtils.getContainerState( machineId, dockerClient );
		result = state != null && extractBoolean( state.getRunning());

	} catch( Exception e ) {
		// nothing, we consider it is not running
		Utils.logException( this.logger, e );
	}

	return result;
}
 
Example #4
Source File: DockerHandler.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void terminateMachine( TargetHandlerParameters parameters, String machineId )
throws TargetException {

	this.logger.fine( "Terminating machine " + machineId );
	try {
		cancelMachineConfigurator( machineId );
		DockerClient dockerClient = DockerUtils.createDockerClient( parameters.getTargetProperties());
		Container container = DockerUtils.findContainerByIdOrByName( machineId, dockerClient );

		// The case "container == null" is possible.
		// Indeed, it may have been killed manually. This method will then
		// just mark the Roboconf instance as "not deployed" without throwing an exception.
		if( container != null ) {

			// Stop the container
			ContainerState state = DockerUtils.getContainerState( machineId, dockerClient );
			if( state != null
					&& ( extractBoolean( state.getRunning()) || extractBoolean( state.getPaused())))
				dockerClient.killContainerCmd( container.getId()).exec();

			dockerClient.removeContainerCmd( container.getId()).withForce( true ).exec();

			// Delete the volume we used to share user data
			// (container names are prefixed by their parent, here "/").
			// See https://github.com/moby/moby/issues/6705
			String containerName = container.getNames()[ 0 ].substring( 1 );
			File userDataDir = this.containerIdToVolume.remove( containerName );
			Utils.deleteFilesRecursivelyAndQuietly( userDataDir );
		}

	} catch( Exception e ) {
		throw new TargetException( e );
	}
}
 
Example #5
Source File: DockerUtils.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the state of a container.
 * @param containerId the container ID
 * @param dockerClient the Docker client
 * @return a container state, or null if the container was not found
 */
public static ContainerState getContainerState( String containerId, DockerClient dockerClient ) {

	ContainerState result = null;
	try {
		InspectContainerResponse resp = dockerClient.inspectContainerCmd( containerId ).exec();
		if( resp != null )
			result = resp.getState();

	} catch( Exception e ) {
		// nothing
	}

	return result;
}
 
Example #6
Source File: DockerHandlerWithContainerTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
/**
 * Creates, checks and terminates a Docker container.
 * @param targetProperties the target properties
 * @throws Exception
 */
private void testCreateAndTerminateVM( Map<String,String> targetProperties ) throws Exception {

	DockerHandler target = new DockerHandler();
	target.userDataVolume = this.folder.newFolder();

	Instance scopedInstance = new Instance( "test-596598515" );
	String path = InstanceHelpers.computeInstancePath( scopedInstance );

	Map<String,String> msgCfg = new LinkedHashMap<>();
	msgCfg.put("net.roboconf.messaging.type", "telepathy");
	msgCfg.put("mindControl", "false");
	msgCfg.put("psychosisProtection", "active");

	TargetHandlerParameters parameters = new TargetHandlerParameters()
			.targetProperties( targetProperties )
			.messagingProperties( msgCfg )
			.applicationName( "roboconf" )
			.domain( "my-domain" )
			.scopedInstancePath( path )
			.scopedInstance( scopedInstance );

	String containerId = null;
	try {
		target.start();
		containerId = target.createMachine( parameters );
		Assert.assertNotNull( containerId );
		Assert.assertNull( scopedInstance.data.get( Instance.MACHINE_ID ));

		// DockerMachineConfigurator is implemented in such a way that it runs only
		// once when the image already exists. However, we must wait for the thread pool
		// executor to pick up the configurator.
		target.configureMachine( parameters, containerId );

		// Be careful, the Docker target changes the machine ID
		containerId = DockerTestUtils.waitForMachineId(
				containerId,
				scopedInstance.data,
				DockerTestUtils.DOCKER_CONFIGURE_TIMEOUT);

		Assert.assertNotNull( containerId );

		// Check the machine is running
		Assert.assertTrue( target.isMachineRunning( parameters, containerId ));

		// Verify user data were passed correctly (read like an agent)
		File[] children = target.userDataVolume.listFiles();
		Assert.assertNotNull( children );
		Assert.assertEquals( 1, children.length );

		File userDataDirectory = children[ 0 ];
		File userDataFile = new File( userDataDirectory, DockerMachineConfigurator.USER_DATA_FILE );
		Assert.assertTrue( userDataFile.exists());

		AgentProperties agentProps = new UserDataHelper().findParametersFromUrl( userDataFile.toURI().toString(), this.logger );
		Assert.assertNotNull( agentProps );
		Assert.assertEquals( parameters.getApplicationName(), agentProps.getApplicationName());
		Assert.assertEquals( parameters.getDomain(), agentProps.getDomain());
		Assert.assertEquals( parameters.getScopedInstancePath(), agentProps.getScopedInstancePath());
		Assert.assertEquals( parameters.getMessagingProperties(), agentProps.getMessagingConfiguration());
		Assert.assertNull( agentProps.validate());

		// Just for verification, try to terminate an invalid container
		target.terminateMachine( parameters, "invalid identifier" );
		Assert.assertTrue( target.isMachineRunning( parameters, containerId ));

		// Terminate the container
		target.terminateMachine( parameters, containerId );
		Assert.assertFalse( target.isMachineRunning( parameters, containerId ));

		// Verify user data were deleted
		Assert.assertFalse( userDataFile.exists());
		Assert.assertFalse( userDataDirectory.exists());
		Assert.assertTrue( userDataDirectory.getParentFile().exists());

	} finally {
		if( containerId != null ) {
			ContainerState state = DockerUtils.getContainerState( containerId, this.docker );
			if( state != null && extractBoolean( state.getRunning()))
				this.docker.removeContainerCmd( containerId ).withForce( true ).exec();
		}

		target.stop();
	}
}