當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。