当前位置: 首页>>代码示例>>Java>>正文


Java DockerClient类代码示例

本文整理汇总了Java中com.github.dockerjava.api.DockerClient的典型用法代码示例。如果您正苦于以下问题:Java DockerClient类的具体用法?Java DockerClient怎么用?Java DockerClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DockerClient类属于com.github.dockerjava.api包,在下文中一共展示了DockerClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: checkDiskSpace

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private void checkDiskSpace(DockerClient dockerClient, String id) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        dockerClient
                .execStartCmd(dockerClient.execCreateCmd(id).withAttachStdout(true).withCmd("df", "-P").exec().getId())
                .exec(new ExecStartResultCallback(outputStream, null))
                .awaitCompletion();
    } catch (Exception e) {
        log.debug("Can't exec disk checking command", e);
    }

    DiskSpaceUsage df = parseAvailableDiskSpace(outputStream.toString());

    VisibleAssertions.assertTrue(
            "Docker environment should have more than 2GB free disk space",
            df.availableMB.map(it -> it >= 2048).orElse(true)
    );
}
 
开发者ID:testcontainers,项目名称:testcontainers-java,代码行数:20,代码来源:DockerClientFactory.java

示例2: readFileFromContainer

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
@Nullable
private byte[] readFileFromContainer(@NonNull final DockerClient _dockerClient,
                                     @NonNull final CreateContainerResponse _container,
                                     @NonNull final String _outputFile) {
    final InputStream fileStream =_dockerClient
            .copyArchiveFromContainerCmd(_container.getId(), _outputFile)
            .exec();
    final TarArchiveInputStream tarIn = new TarArchiveInputStream(fileStream);

    try {
        if (tarIn.getNextEntry() == null) {
            log.error("No entry in tar archive");
            return null;
        }

        return IOUtils.toByteArray(tarIn);
    } catch (IOException _e) {
        log.error("Could not read file from container", _e);
        return null;
    }
}
 
开发者ID:jonfryd,项目名称:tifoon,代码行数:22,代码来源:DockerExecutorPlugin.java

示例3: call

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
public Void call() throws Exception {
    final ConsoleLogger console = new ConsoleLogger(listener);
    DockerClient client = DockerCommand.getClient(descriptor, cfgData.dockerUrlRes, cfgData.dockerVersionRes, cfgData.dockerCertPathRes, authConfig);

    PullImageCmd pullImageCmd = client.pullImageCmd(fromImageRes);
    PullImageResultCallback callback = new PullImageResultCallback() {
        @Override
        public void onNext(PullResponseItem item) {
            console.logInfo(item.toString());
            super.onNext(item);
        }

        @Override
        public void onError(Throwable throwable) {
            console.logError("Failed to exec start:" + throwable.getMessage());
            super.onError(throwable);
        }
    };
    pullImageCmd.exec(callback).awaitSuccess();
    
    return null;
}
 
开发者ID:jenkinsci,项目名称:docker-build-step-plugin,代码行数:23,代码来源:PullImageRemoteCallable.java

示例4: destroyInstance

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private ServiceInstance destroyInstance(ServiceInstance i, DockerClient client) {
	if(i.getContainerId() != null) {
		RemoveContainerCmd cmd = client.removeContainerCmd(i.getContainerId()).withForce(true);
		try {
			cmd.exec();
			return i.withStatus(Status.TERMINATED);
		} catch (NotFoundException e) {
			logger.warning("No container with id " + i.getContainerId() + " found");
			return i.withStatus(Status.TERMINATION_FAILED)
					.withStatusDetails(e.getMessage());
		}
	} else {
		return i.withStatus(Status.TERMINATION_FAILED)
				.withStatusDetails("No container id found.");
	}
	
}
 
开发者ID:qzagarese,项目名称:dockerunit,代码行数:18,代码来源:DefaultServiceBuilder.java

示例5: getDockerClient

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private DockerClient getDockerClient() {
    /*
    TLS connection: ...

    DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost("tcp://192.168.99.100:2376")
            .withDockerTlsVerify(true)
            .withDockerCertPath("/Users/jon/.docker/machine/machines/default")
            .build();
    */

    final String localDockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375" : "unix:///var/run/docker.sock";

    final DefaultDockerClientConfig config = DefaultDockerClientConfig
            .createDefaultConfigBuilder()
            .withDockerHost(localDockerHost)
            .build();

    return DockerClientBuilder
            .getInstance(config)
            .build();
}
 
开发者ID:jonfryd,项目名称:tifoon,代码行数:23,代码来源:DockerExecutorPlugin.java

示例6: runCommand

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private boolean runCommand(@NonNull final DockerClient _dockerClient,
                           @NonNull final CreateContainerResponse _container,
                           @NonNull final String[] _commandWithArguments) {
    final ExecCreateCmdResponse mExecCreateCmdResponse = _dockerClient
            .execCreateCmd(_container.getId())
            .withAttachStdout(true)
            .withCmd(_commandWithArguments)
            .exec();

    try {
        return _dockerClient
                .execStartCmd(mExecCreateCmdResponse.getId())
                .exec(new ExecStartResultCallback() {
                    @Override
                    public void onNext(Frame frame) {
                        super.onNext(frame);
                    }
                })
                .awaitCompletion(30, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        // ignore
    }

    return false;
}
 
开发者ID:jonfryd,项目名称:tifoon,代码行数:26,代码来源:DockerExecutorPlugin.java

示例7: stopAndRemoveContainer

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private void stopAndRemoveContainer(@NonNull final DockerClient _dockerClient,
                                    @NonNull final CreateContainerResponse _container) {
    _dockerClient
            .stopContainerCmd(_container.getId())
            .withTimeout(0)
            .exec();

    try {
        _dockerClient
                .waitContainerCmd(_container.getId())
                .exec(new WaitContainerResultCallback())
                .awaitCompletion();
    } catch (InterruptedException e) {
        // ignore
    }

    _dockerClient
            .removeContainerCmd(_container.getId())
            .exec();
}
 
开发者ID:jonfryd,项目名称:tifoon,代码行数:21,代码来源:DockerExecutorPlugin.java

示例8: buildDockerClientWithShutdown

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private DockerClient buildDockerClientWithShutdown () {

		logger.warn( "\n\n\n *********** Dockerclient: {} poolsize: {}  *** \n\n\n", 
			dockerConfiguration.getDockerHost(), dockerPoolSize );

		// need to support connection leaks in docker java image load code
		// means shutdown needs to occur - which can then cause intermittent
		// race conditions.
		//
		if ( lastFactory != null ) {
			try {
				lastFactory.close();
			} catch (IOException e) {
				logger.error( "Failed closing factory", e );
			}
		}
		// Netty: use 2*core count threads
		// lastFactory = buildNettyDockerCommandFactory() ;
		lastFactory = buildDockerJerseyCommandFactory();
		return DockerClientBuilder
			.getInstance( dockerConfiguration )
			.withDockerCmdExecFactory( lastFactory )
			.build();
	}
 
开发者ID:csap-platform,项目名称:csap-core,代码行数:25,代码来源:Docker_Java.java

示例9: getDefaultConnection

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
/**
 * TODO delete and make method with serverId param after thinking about it
 *
 * @return default connection to system docker
 */
public DockerClient getDefaultConnection() {
    return connections.computeIfAbsent(DEFAULT_CONNECTION, id -> {
        DockerClientConfig config = null;

        if (SystemUtils.IS_OS_MAC_OSX) {
            config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost("unix:///var/run/docker.sock")
                    .build();
        }
        if (SystemUtils.IS_OS_LINUX) {
            config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost("unix:///var/run/docker.sock")
                    .build();
        }
        if (SystemUtils.IS_OS_WINDOWS) {
            config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost("tcp://localhost:2376")
                    .withDockerTlsVerify(true)
                    .withDockerTlsVerify("1")
                    .build();
        }

        return DockerClientBuilder.getInstance(config).build();
    });
}
 
开发者ID:petrleocompel,项目名称:docker-dash,代码行数:31,代码来源:DockerConnectionService.java

示例10: create

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
@Override
protected DockerHost create() {
  for (Connect.Def connectionDef : config.getConnection().getConnectionDefinitions()) {
    if (connectionDef.resolve().isEmpty()) {
      LOG.info("Connection definition empty: [{}]", connectionDef.toString());
      continue;
    }

    LOG.info("Attempting to use connection: [{}]", connectionDef.toString());
    Optional<DockerClient> client = clientFactory.tryCreate(connectionDef, config);
    if (client.isPresent()) {
      LOG.info("Successful connection: [{}]", connectionDef.toString());
      return DockerHost.create(connectionDef.ipAddress(), connectionDef, config);
    } else {
      LOG.info("Failed connection: [{}]", connectionDef.toString());
    }
  }

  throw new IllegalStateException("Could not connect to docker using the provided connections: " + config.getConnection().toString());
}
 
开发者ID:Qorr,项目名称:Hvalspik,代码行数:21,代码来源:DockerHostProvider.java

示例11: pullImageAsyncIfNeededSuccessfully

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void pullImageAsyncIfNeededSuccessfully() {
    final DockerImage image = new DockerImage("test:1.2.3");

    InspectImageResponse inspectImageResponse = mock(InspectImageResponse.class);
    when(inspectImageResponse.getId()).thenReturn(image.asString());

    InspectImageCmd imageInspectCmd = mock(InspectImageCmd.class);
    when(imageInspectCmd.exec())
            .thenThrow(new NotFoundException("Image not found"))
            .thenReturn(inspectImageResponse);

    // Array to make it final
    ArgumentCaptor<ResultCallback> resultCallback = ArgumentCaptor.forClass(ResultCallback.class);
    PullImageCmd pullImageCmd = mock(PullImageCmd.class);
    when(pullImageCmd.exec(resultCallback.capture())).thenReturn(null);

    final DockerClient dockerClient = mock(DockerClient.class);
    when(dockerClient.inspectImageCmd(image.asString())).thenReturn(imageInspectCmd);
    when(dockerClient.pullImageCmd(eq(image.asString()))).thenReturn(pullImageCmd);

    final DockerImpl docker = new DockerImpl(dockerClient);
    docker.setMetrics(new MetricReceiverWrapper(MetricReceiver.nullImplementation));
    assertTrue("Should return true, we just scheduled the pull", docker.pullImageAsyncIfNeeded(image));
    assertTrue("Should return true, the pull i still ongoing", docker.pullImageAsyncIfNeeded(image));

    assertTrue(docker.imageIsDownloaded(image));
    resultCallback.getValue().onComplete();
    assertFalse(docker.pullImageAsyncIfNeeded(image));
}
 
开发者ID:vespa-engine,项目名称:vespa,代码行数:32,代码来源:DockerImplTest.java

示例12: pullImageAsyncIfNeededWithError

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void pullImageAsyncIfNeededWithError() {
    final DockerImage image = new DockerImage("test:1.2.3");

    InspectImageCmd imageInspectCmd = mock(InspectImageCmd.class);
    when(imageInspectCmd.exec()).thenThrow(new NotFoundException("Image not found"));

    // Array to make it final
    ArgumentCaptor<ResultCallback> resultCallback = ArgumentCaptor.forClass(ResultCallback.class);
    PullImageCmd pullImageCmd = mock(PullImageCmd.class);
    when(pullImageCmd.exec(resultCallback.capture())).thenReturn(null);

    final DockerClient dockerClient = mock(DockerClient.class);
    when(dockerClient.inspectImageCmd(image.asString())).thenReturn(imageInspectCmd);
    when(dockerClient.pullImageCmd(eq(image.asString()))).thenReturn(pullImageCmd);

    final DockerImpl docker = new DockerImpl(dockerClient);
    docker.setMetrics(new MetricReceiverWrapper(MetricReceiver.nullImplementation));
    assertTrue("Should return true, we just scheduled the pull", docker.pullImageAsyncIfNeeded(image));
    assertTrue("Should return true, the pull i still ongoing", docker.pullImageAsyncIfNeeded(image));

    try {
        resultCallback.getValue().onComplete();
    } catch (Exception ignored) { }

    assertFalse(docker.imageIsDownloaded(image));
    assertTrue("Should return true, new pull scheduled", docker.pullImageAsyncIfNeeded(image));
}
 
开发者ID:vespa-engine,项目名称:vespa,代码行数:30,代码来源:DockerImplTest.java

示例13: followOutput

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
/**
 * {@inheritDoc}
 */
public void followOutput(DockerClient dockerClient, String containerId,
                         Consumer<OutputFrame> consumer, OutputFrame.OutputType... types) {

    final LogContainerCmd cmd = dockerClient.logContainerCmd(containerId)
            .withFollowStream(true)
            .withSince(0);

    final FrameConsumerResultCallback callback = new FrameConsumerResultCallback();
    for (OutputFrame.OutputType type : types) {
        callback.addConsumer(type, consumer);
        if (type == STDOUT) cmd.withStdOut(true);
        if (type == STDERR) cmd.withStdErr(true);
    }

    cmd.exec(callback);
}
 
开发者ID:testcontainers,项目名称:testcontainers-java,代码行数:20,代码来源:LogUtils.java

示例14: waitUntilStartupSuccessful

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
public boolean waitUntilStartupSuccessful(DockerClient dockerClient, String containerId) {
    final Boolean[] startedOK = {null};
    Unreliables.retryUntilTrue(CONTAINER_RUNNING_TIMEOUT_SEC, TimeUnit.SECONDS, () -> {
        //noinspection CodeBlock2Expr
        return DOCKER_CLIENT_RATE_LIMITER.getWhenReady(() -> {
            StartupStatus state = checkStartupState(dockerClient, containerId);
            switch (state) {
                case SUCCESSFUL:    startedOK[0] = true;
                                    return true;
                case FAILED:        startedOK[0] = false;
                                    return true;
                default:            return false;
            }
        });
    });
    return startedOK[0];
}
 
开发者ID:testcontainers,项目名称:testcontainers-java,代码行数:18,代码来源:StartupCheckStrategy.java

示例15: runInsideDocker

import com.github.dockerjava.api.DockerClient; //导入依赖的package包/类
private <T> T runInsideDocker(DockerClient client, Consumer<CreateContainerCmd> createContainerCmdConsumer, BiFunction<DockerClient, String, T> block) {
    checkAndPullImage(client, TINY_IMAGE);
    CreateContainerCmd createContainerCmd = client.createContainerCmd(TINY_IMAGE);
    createContainerCmdConsumer.accept(createContainerCmd);
    String id = createContainerCmd.exec().getId();

    try {
        client.startContainerCmd(id).exec();
        return block.apply(client, id);
    } finally {
        try {
            client.removeContainerCmd(id).withRemoveVolumes(true).withForce(true).exec();
        } catch (NotFoundException | InternalServerErrorException ignored) {
            log.debug("", ignored);
        }
    }
}
 
开发者ID:testcontainers,项目名称:testcontainers-java,代码行数:18,代码来源:DockerClientFactory.java


注:本文中的com.github.dockerjava.api.DockerClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。