Java Code Examples for com.spotify.docker.client.DockerClient

The following are top voted examples for showing how to use com.spotify.docker.client.DockerClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pay-adminusers   File: PostgresContainer.java   Source Code and License 7 votes vote down vote up
public  PostgresContainer(DockerClient docker, String host) throws InterruptedException, IOException, ClassNotFoundException, DockerException {
    Class.forName("org.postgresql.Driver");

    this.docker = docker;
    this.host = host;

    failsafeDockerPull(docker, GOVUK_POSTGRES_IMAGE);
    docker.listImages(DockerClient.ListImagesParam.create("name", GOVUK_POSTGRES_IMAGE));

    final HostConfig hostConfig = HostConfig.builder().logConfig(LogConfig.create("json-file")).publishAllPorts(true).build();
    ContainerConfig containerConfig = ContainerConfig.builder()
            .image(GOVUK_POSTGRES_IMAGE)
            .hostConfig(hostConfig)
            .env("POSTGRES_USER=" + DB_USERNAME, "POSTGRES_PASSWORD=" + DB_PASSWORD)
            .build();
    containerId = docker.createContainer(containerConfig).id();
    docker.startContainer(containerId);
    port = hostPortNumber(docker.inspectContainer(containerId));
    registerShutdownHook();
    waitForPostgresToStart();
}
 
Example 2
Project: SuitAgent   File: DockerUtil.java   Source Code and License 6 votes vote down vote up
private static List<String> getAllHostContainerId(){
    String cacheKey = "allHostContainerIds";
    int cacheTime = 28;//28秒缓存周期,保证一次采集job只需要访问一次docker即可

    List<String> ids = (List<String>) getCache(cacheKey);
    if (ids != null){
        return ids;
    }else {
        ids = new ArrayList<>();
    }
    synchronized (LockForGetAllHostContainerId){
        try {
            List<Container> containerList = getContainers(DockerClient.ListContainersParam.allContainers());
            for (Container container : containerList) {
                ids.add(container.id());
            }
        } catch (Exception e) {
            log.error("",e);
        }
    }
    setCache(cacheKey,ids,cacheTime);
    return ids;
}
 
Example 3
Project: comdor   File: RtDockerHost.java   Source Code and License 6 votes vote down vote up
@Override
public void followLogs(final String containerId, final Logger logger) {
    logger.info("********** Container logs **********");
    try {
        final LogStream logs = this.client.logs(
            containerId,
            DockerClient.LogsParam.stdout(),
            DockerClient.LogsParam.stderr(),
            DockerClient.LogsParam.follow()
        );
        logger.info(logs.readFully());
    } catch (final DockerException | InterruptedException ex) {
        throw new IllegalStateException(
            "Exception when starting container with id " + containerId, ex
        );
    }
    logger.info("************************************");
}
 
Example 4
Project: docker-image-builder   File: CacheImageProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public ProcessorResult proceess(Image image, RuntimeConfiguration configuration) {
    if(configuration.getUsecache() && configuration.getCacheImage() != null){
        DockerRemoteHandler dockerRemoteHandler = new DockerRemoteHandler();
        Registry registry = configuration.getCacheImage().getRegistry();
        final DockerClient parentDockerClient = dockerRemoteHandler.buildDockerClient(registry, configuration.getDockerHost());
        Result result = dockerRemoteHandler.pull(parentDockerClient, configuration.getCacheImage());
        if(result.getStatus()){
            return new ProcessorResult(image,configuration).success();

        }else{
            logger.info("pull cache image failed, continue without cache image");
            return new ProcessorResult(image,configuration).success();
        }
    }else{
        return new ProcessorResult(image,configuration).success();
    }
}
 
Example 5
Project: just-ask   File: DockerHelper.java   Source Code and License 6 votes vote down vote up
private static void predownloadImagesIfRequired() throws DockerException, InterruptedException {

        DockerClient client = getClient();
        LOG.warning("Commencing download of images.");
        Collection<MappingInfo> images = getInstance().getMapping().values();

        ProgressHandler handler = new LoggingBuildHandler();
        for (MappingInfo image : images) {
            List<Image> foundImages = client.listImages(DockerClient.ListImagesParam.byName(image.getTarget()));
            if (! foundImages.isEmpty()) {
                LOG.warning(String.format("Skipping download for Image [%s] because it's already available.",
                    image.getTarget()));
                continue;
            }
            client.pull(image.getTarget(), handler);
        }
    }
 
Example 6
Project: docker-elastic-agents   File: DockerContainerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldStartContainerWithHostEntry() throws Exception {
    Map<String, String> properties = new HashMap<>();
    properties.put("Image", "alpine:latest");
    properties.put("Hosts", "127.0.0.2\tbaz \n192.168.5.1\tfoo\tbar\n127.0.0.1  gocd.local ");
    properties.put("Command", "cat\n/etc/hosts");

    DockerContainer container = DockerContainer.create(new CreateAgentRequest("key", properties, "prod"), createSettings(), docker);

    containers.add(container.name());
    ContainerInfo containerInfo = docker.inspectContainer(container.name());

    final ImmutableList<String> extraHosts = containerInfo.hostConfig().extraHosts();
    assertThat(extraHosts, containsInAnyOrder(
            "baz:127.0.0.2", "foo\tbar:192.168.5.1", "gocd.local:127.0.0.1"
    ));

    String logs = docker.logs(container.name(), DockerClient.LogsParam.stdout()).readFully();
    assertThat(logs, containsString("127.0.0.2\tbaz"));
    assertThat(logs, containsString("192.168.5.1\tfoo"));
    assertThat(logs, containsString("127.0.0.1\tgocd.local"));
}
 
Example 7
Project: platform   File: ContainerManagerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void removeParentAndChildren(String parentId) {
    // stop parent
    removeContainer(parentId);

    // find children
    try {
        List<Container> containers = dockerClient.listContainers(DockerClient.ListContainersParam.allContainers());
        for (Container c : containers) {
            if (c != null && c.labels().get(LABEL_PARENT) != null
                    && c.labels().get(LABEL_PARENT).equals(parentId)) {
                removeParentAndChildren(c.id());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error while removing containers: " + e.toString());
    }
}
 
Example 8
Project: pay-adminusers   File: PostgresContainer.java   Source Code and License 6 votes vote down vote up
public void stop() {
    if (stopped) {
        return;
    }
    try {
        stopped = true;
        System.out.println("Killing postgres container with ID: " + containerId);
        LogStream logs = docker.logs(containerId, DockerClient.LogsParam.stdout(), DockerClient.LogsParam.stderr());
        System.out.println("Killed container logs:\n");
        logs.attach(System.out, System.err);
        docker.stopContainer(containerId, 5);
        docker.removeContainer(containerId);
    } catch (DockerException | InterruptedException | IOException e) {
        System.err.println("Could not shutdown " + containerId);
        e.printStackTrace();
    }
}
 
Example 9
Project: docker-swarm-elastic-agents   File: DockerSecretValidator.java   Source Code and License 6 votes vote down vote up
@Override
public ValidationResult validate(Map<String, String> elasticProfile) {
    final ValidationResult validationResult = new ValidationResult();

    try {
        final DockerSecrets dockerSecrets = DockerSecrets.fromString(elasticProfile.get("Secrets"));

        if (!dockerSecrets.isEmpty()) {
            DockerClient dockerClient = dockerClientFactory.docker(pluginRequest.getPluginSettings());
            if (!dockerApiVersionAtLeast(dockerClient, "1.26")) {
                throw new RuntimeException("Docker secret requires api version 1.26 or higher.");
            }
            dockerSecrets.toSecretBind(dockerClient.listSecrets());
        }
    } catch (Exception e) {
        validationResult.addError("Secrets", e.getMessage());
    }

    return validationResult;
}
 
Example 10
Project: docker-swarm-elastic-agents   File: DockerMountsValidator.java   Source Code and License 6 votes vote down vote up
@Override
public ValidationResult validate(Map<String, String> elasticProfile) {
    final ValidationResult validationResult = new ValidationResult();

    try {
        final DockerMounts dockerMounts = DockerMounts.fromString(elasticProfile.get("Mounts"));

        if (!dockerMounts.isEmpty()) {
            DockerClient dockerClient = dockerClientFactory.docker(pluginRequest.getPluginSettings());

            if (!dockerApiVersionAtLeast(dockerClient, "1.26")) {
                throw new RuntimeException("Docker volume mount requires api version 1.26 or higher.");
            }

            dockerMounts.toMount(dockerClient.listVolumes().volumes());
        }
    } catch (Exception e) {
        validationResult.addError("Mounts", e.getMessage());
    }

    return validationResult;
}
 
Example 11
Project: docker-swarm-elastic-agents   File: SwarmClusterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldCreateSwarmClusterObject() throws Exception {
    final DockerClient dockerClient = mock(DockerClient.class);
    final Node node = mockNode("node-id", "manager", true);
    final List<Node> nodeList = Arrays.asList(node);
    final List<Task> taskList = Arrays.asList(mockTask(node.id()));

    when(dockerClient.listNodes()).thenReturn(nodeList);
    when(dockerClient.listTasks()).thenReturn(taskList);

    final SwarmCluster swarmCluster = new SwarmCluster(dockerClient);

    verify(dockerClient, times(1)).listNodes();
    verify(dockerClient, times(1)).listTasks();

    assertThat(swarmCluster.getNodes(), hasSize(1));
    assertThat(swarmCluster.getNodes().get(0).getTasks(), hasSize(1));
}
 
Example 12
Project: junit-docker-postgres   File: EmbeddedPostgresDocker.java   Source Code and License 6 votes vote down vote up
private ContainerCreation createContainer(DockerClient docker, int postgresPort, int exposedPort) throws Exception {
    Map<String, List<PortBinding>> portBindings = new HashMap<>();
    portBindings.put(String.valueOf(postgresPort + "/tcp"), Arrays.asList(PortBinding.of("0.0.0.0", exposedPort)));

    HostConfig hostConfig = HostConfig.builder()
            .portBindings(portBindings)
            .build();

    ContainerConfig containerConfig = ContainerConfig.builder()
            .hostConfig(hostConfig)
            .exposedPorts(postgresPort + "/tcp")
            .image(imageConfig.getContainerImage())
            .networkDisabled(false)
            .build();

    return docker.createContainer(containerConfig);
}
 
Example 13
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<Instance> pull(Trace trace, Instance image) {
      return Observable.create((Subscriber<? super Instance> subscriber) -> {
	Trace.Event pulling = trace.start("RxDocker: pull(image)", image);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.pull(image.toString(), message -> logPullProgress(trace, message));
	} catch(Exception ex) {
		trace.event(Level.ERROR, "RxDocker: pulling failed", ex);
		pulling.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	pulling.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(image);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 14
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> startContainer(Trace trace, String containerId) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event starting = trace.start("RxDocker: starting container (containerId): ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.startContainer(containerId);
	} catch(Exception ex) {
		trace.event(Level.ERROR, "RxDocker: starting failed", ex);
		starting.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	starting.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 15
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> killContainer(Trace trace, String containerId) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event killing = trace.start("RxDocker: killing container: ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.killContainer(containerId);
	} catch(Exception ex) {
		trace.event("RxDocker: killing failed", ex);
		killing.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	killing.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 16
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> stopContainer(Trace trace, String containerId, int secondsBeforeFail) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event stopping = trace.start("RxDocker: stopping container: ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.stopContainer(containerId, secondsBeforeFail);
	} catch(Exception ex) {
		trace.event("RxDocker: stopping failed", ex);
		stopping.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	stopping.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 17
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> removeContainer(Trace trace, String containerId) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event removing = trace.start("RxDocker: removing container: ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.removeContainer(containerId, true);
	} catch(Exception ex) {
		trace.event("RxDocker: removing failed", ex);
		removing.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	removing.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 18
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
public Observable<ContainerInfo> inspectContainer(Trace trace, String containerId) {
	return Observable.create((Subscriber<? super ContainerInfo> subscriber) -> {
		Event inspecting = trace.start("RxDocker: inspecting container (containerId): ", containerId);
		final DockerClient client;
		final ContainerInfo info;
		try {
			client = obtainDockerClient();
			info = new SpotifyInspectWrapper(client.inspectContainer(containerId));
		} catch(Exception ex) {
			trace.event("RxDocker: inspecting failed", ex);
			inspecting.end();
			
			if (subscriber.isUnsubscribed()) return;
			subscriber.onError(ex);
			return;
		}
		inspecting.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onNext(info);
		subscriber.onCompleted();
	}).subscribeOn(scheduler);
}
 
Example 19
Project: pay-publicauth   File: PostgresContainer.java   Source Code and License 6 votes vote down vote up
public PostgresContainer(DockerClient docker, String host) throws InterruptedException, IOException, ClassNotFoundException, DockerException {
    Class.forName("org.postgresql.Driver");

    this.docker = docker;
    this.host = host;

    failsafeDockerPull(docker, GOVUK_POSTGRES_IMAGE);
    docker.listImages(DockerClient.ListImagesParam.create("name", GOVUK_POSTGRES_IMAGE));

    final HostConfig hostConfig = HostConfig.builder().logConfig(LogConfig.create("json-file")).publishAllPorts(true).build();
    ContainerConfig containerConfig = ContainerConfig.builder()
            .image(GOVUK_POSTGRES_IMAGE)
            .hostConfig(hostConfig)
            .env("POSTGRES_USER=" + DB_USERNAME, "POSTGRES_PASSWORD=" + DB_PASSWORD)
            .build();
    containerId = docker.createContainer(containerConfig).id();
    docker.startContainer(containerId);
    port = hostPortNumber(docker.inspectContainer(containerId));
    registerShutdownHook();
    waitForPostgresToStart();
}
 
Example 20
Project: pay-publicauth   File: PostgresContainer.java   Source Code and License 6 votes vote down vote up
public void stop() {
    if (stopped) {
        return;
    }
    try {
        stopped = true;
        System.err.println("Killing postgres container with ID: " + containerId);
        LogStream logs = docker.logs(containerId, DockerClient.LogsParam.stdout(), DockerClient.LogsParam.stderr());
        System.err.println("Killed container logs:\n");
        logs.attach(System.err, System.err);
        docker.stopContainer(containerId, 5);
        docker.removeContainer(containerId);
    } catch (DockerException | InterruptedException | IOException e) {
        System.err.println("Could not shutdown " + containerId);
        e.printStackTrace();
    }
}
 
Example 21
Project: junit-docker-rule   File: DockerRule.java   Source Code and License 6 votes vote down vote up
/**
 * Stop and remove container.<br/>
 * This is {@link ExternalResource#before()} made available as public - it may be helpful in scenarios
 * when you want to use {@link DockerRule} and operate it manually.
 */
@Override
public final void after() {
    log.debug("after {}", containerShortId);
    try {
        dockerLogs.close();
        ContainerState state = dockerClient.inspectContainer(container.id()).state();
        log.debug("{} state {}", containerShortId, state);
        if (state.running()) {
            if (builder.stopOptions().contains(StopOption.KILL)) {
                dockerClient.killContainer(container.id());
                log.info("{} killed", containerShortId);
            } else {
                dockerClient.stopContainer(container.id(), STOP_TIMEOUT);
                log.info("{} stopped", containerShortId);
            }
        }
        if (builder.stopOptions().contains(StopOption.REMOVE)) {
            dockerClient.removeContainer(container.id(), DockerClient.RemoveContainerParam.removeVolumes());
            log.info("{} deleted", containerShortId);
            container = null;
        }
    } catch (DockerException | InterruptedException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 22
Project: junit-docker-rule   File: DockerRuleStopOptionsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldKeepContainer() throws Throwable {

    DockerRule testee = DockerRule.builder()//
            .imageName("alpine:3.4")//
            .cmd("sh", "-c", "sleep 1")//
            .stopOptions(StopOption.KEEP)
            .build();

    final DockerClient dockerClient = testee.getDockerClient();
    testee.before();
    final String containerId = testee.getContainerId();

    try {
        testee.after();
        assertContainerExists(dockerClient, containerId);
    } finally {
        cleanup(dockerClient, containerId);
    }
}
 
Example 23
Project: junit-docker-rule   File: DockerRuleStopOptionsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldStopContainer() throws Throwable {
    DockerRule testee = DockerRule.builder()//
            .imageName("alpine:3.4")//
            .cmd("sh", "-c", "trapinfo() { echo STOPPED; exit; }; trap \"trapinfo\" SIGTERM; for i in 01 02 03 04 05 06 07 08 09 10; do (echo $i; sleep 1); done")//
            .stopOptions(StopOption.KEEP, StopOption.STOP)
            .build();

    final DockerClient dockerClient = testee.getDockerClient();
    testee.before();
    final String containerId = testee.getContainerId();

    try {
        testee.after();
        assertTrue(StringUtils.trimToEmpty(testee.getLog()).contains("STOPPED"));
    } finally {
        cleanup(dockerClient, containerId);
    }
}
 
Example 24
Project: junit-docker-rule   File: DockerRuleStopOptionsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldKillContainer() throws Throwable {
    DockerRule testee = DockerRule.builder()//
            .imageName("alpine:3.4")//
            .cmd("sh", "-c", "trapinfo() { echo STOPPED; exit; }; trap \"trapinfo\" SIGTERM; for i in 01 02 03 04 05 06 07 08 09 10; do (echo $i; sleep 1); done")//
            .stopOptions(StopOption.KEEP, StopOption.KILL)
            .build();

    final DockerClient dockerClient = testee.getDockerClient();
    testee.before();
    final String containerId = testee.getContainerId();

    try {
        testee.after();
        assertFalse(StringUtils.trimToEmpty(testee.getLog()).contains("STOPPED"));
    } finally {
        cleanup(dockerClient, containerId);
    }

}
 
Example 25
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
public List<DockerContainerElement> getServiceOfferings(IProgressMonitor monitor) throws CoreException {
	return new BehaviourRequest<List<DockerContainerElement>>("Getting available service options") { //$NON-NLS-1$
		@Override
		protected List<DockerContainerElement> doRun(DockerClient client, SubMonitor progress) throws CoreException {
			// return client.getServiceOfferings();
			try {
				List<Container> containers = client.listContainers();
				return DomainHelper.convert(containers);					
			}
			catch (DockerException | InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}
	}.run(monitor);
}
 
Example 26
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
public StreamingLogToken addApplicationLogListener(final String appName, final ApplicationLogListener listener) {
	if (appName != null && listener != null) {
		try {
			return new BehaviourRequest<StreamingLogToken>("Adding application log listener") //$NON-NLS-1$
			{
				@Override
				protected StreamingLogToken doRun(DockerClient client, SubMonitor progress) throws CoreException {
					// return client.streamLogs(appName, listener);
					return null;
				}

			}.run(new NullProgressMonitor());
		}
		catch (CoreException e) {
			DockerFoundryPlugin.logError(NLS.bind(Messages.ERROR_APPLICATION_LOG_LISTENER, appName, e.getMessage()),
					e);
		}
	}

	return null;
}
 
Example 27
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
public List<ApplicationLog> getRecentApplicationLogs(final String appName, IProgressMonitor monitor)
		throws CoreException {
	List<ApplicationLog> logs = null;
	if (appName != null) {
		logs = new BehaviourRequest<List<ApplicationLog>>("Getting existing application logs for: " + appName) //$NON-NLS-1$
		{

			@Override
			protected List<ApplicationLog> doRun(DockerClient client, SubMonitor progress) throws CoreException {
				// return client.getRecentLogs(appName);
				return null;
			}

		}.run(monitor);
	}
	if (logs == null) {
		logs = Collections.emptyList();
	}
	return logs;
}
 
Example 28
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
/**
	 * Retrieves the orgs and spaces for the current server instance.
	 * @param monitor
	 * @return
	 * @throws CoreException if it failed to retrieve the orgs and spaces.
	 */
//	public CloudOrgsAndSpaces getCloudSpaces(IProgressMonitor monitor) throws CoreException {
//		return new BehaviourRequest<CloudOrgsAndSpaces>("Getting orgs and spaces") { //$NON-NLS-1$
//
//			@Override
//			protected CloudOrgsAndSpaces doRun(DockerClient client, SubMonitor progress) throws CoreException {
//				// return internalGetCloudSpaces(client);
//				return null;
//			}
//
//		}.run(monitor);
//	}

	public List<CloudRoute> getRoutes(final String domainName, IProgressMonitor monitor) throws CoreException {

		List<CloudRoute> routes = new BehaviourRequest<List<CloudRoute>>(NLS.bind(Messages.ROUTES, domainName)) {
			@Override
			protected List<CloudRoute> doRun(DockerClient client, SubMonitor progress) throws CoreException {
				// return client.getRoutes(domainName);
				return null;
			}
		}.run(monitor);

		return routes;
	}
 
Example 29
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
public void deleteRoute(final List<CloudRoute> routes, IProgressMonitor monitor) throws CoreException {

		if (routes == null || routes.isEmpty()) {
			return;
		}
		new BehaviourRequest<Void>("Deleting routes") { //$NON-NLS-1$
			@Override
			protected Void doRun(DockerClient client, SubMonitor progress) throws CoreException {
				for (CloudRoute route : routes) {
					// client.deleteRoute(route.getHost(),
					// route.getDomain().getName());
				}
				return null;

			}
		}.run(monitor);
	}
 
Example 30
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
protected BaseClientRequest<Void> getUpdateEnvVarRequest(final String appName,
		final List<EnvironmentVariable> variables) {
	final String label = NLS.bind(Messages.DockerFoundryServerBehaviour_UPDATE_ENV_VARS, appName);
	return new BehaviourRequest<Void>(label) {

		@Override
		protected Void doRun(DockerClient client, SubMonitor progress) throws CoreException {
			// Update environment variables.
			Map<String, String> varsMap = new HashMap<String, String>();

			if (variables != null) {
				for (EnvironmentVariable var : variables) {
					varsMap.put(var.getVariable(), var.getValue());
				}
			}

			// client.updateApplicationEnv(appName, varsMap);

			return null;
		}

	};
}
 
Example 31
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
BaseClientRequest<List<CloudService>> getDeleteServicesRequest(final List<String> services) {
	return new BehaviourRequest<List<CloudService>>(Messages.DockerFoundryServerBehaviour_DELETE_SERVICES) {
		@Override
		protected List<CloudService> doRun(DockerClient client, SubMonitor progress) throws CoreException {

			SubMonitor serviceProgress = SubMonitor.convert(progress, services.size());

			for (String service : services) {
				serviceProgress.subTask(NLS.bind(Messages.DockerFoundryServerBehaviour_DELETING_SERVICE, service));
				// client.deleteService(service);
				serviceProgress.worked(1);
			}
			// return client.getServices();
			return null;
		}
	};
}
 
Example 32
Project: dockerfoundry   File: DockerFoundryServerBehaviour.java   Source Code and License 6 votes vote down vote up
BaseClientRequest<List<CloudService>> getCreateServicesRequest(final CloudService[] services) {
	return new BehaviourRequest<List<CloudService>>(Messages.DockerFoundryServerBehaviour_CREATE_SERVICES) {
		@Override
		protected List<CloudService> doRun(DockerClient client, SubMonitor progress) throws CoreException {

			SubMonitor serviceProgress = SubMonitor.convert(progress, services.length);

			for (CloudService service : services) {
				serviceProgress.subTask(NLS.bind(Messages.DockerFoundryServerBehaviour_CREATING_SERVICE,
						service.getName()));
				// client.createService(service);
				serviceProgress.worked(1);
			}
			// return client.getServices();
			return null;
		}
	};
}
 
Example 33
Project: dockerfoundry   File: DockerConnectionElement.java   Source Code and License 6 votes vote down vote up
public DockerClient getDockerClient() throws DockerCertificateException {
	DockerClient client = null;
	if (this.isUseDefault()) {
		client = DefaultDockerClient.builder()
				.uri(DefaultDockerClient.DEFAULT_UNIX_ENDPOINT).build();
	} else {
		if (this.isUseUnixSocket()) {
			client = DefaultDockerClient.builder().uri(getSocketPath())
					.build();
		} else if (isUseHTTPS()) {
			if (isEnableAuth()) {
				client = DefaultDockerClient
						.builder()
						.dockerCertificates(
								new DockerCertificates(Paths
										.get(getAuthPath())))
						.uri(getHost()).build();
			} else {
				client = DefaultDockerClient.builder().uri(getHost())
						.build();
			}
		}
	}
	return client;
}
 
Example 34
Project: docker-ephemeral-cloud   File: DockerCloud.java   Source Code and License 6 votes vote down vote up
private int countRunningContainers(String imageName) throws DockerException, InterruptedException, DockerCertificateException {
	// The could be a performance hog in huge Docker environments. Replacing with
	// docker labels/metadata is the plan.
	DockerClient dockerClient = null;
	
	try {
		dockerClient = buildDockerClient();
		List<ListContainersParam> params = new ArrayList<ListContainersParam>(2);
		params.add(ListContainersParam.withLabel(DockerLabelsBuilder.CLOUD_NAME, DockerLabelsBuilder.sanitize(getName())));
		if (imageName != null) {
			params.add(ListContainersParam.withLabel(DockerLabelsBuilder.IMAGE_NAME, DockerLabelsBuilder.sanitize(imageName)));
		}
		return dockerClient.listContainers(params.toArray(new ListContainersParam[params.size()])).size();
	} finally {
		if (dockerClient != null) {
			dockerClient.close();
		}
	}
}
 
Example 35
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<Instance> pull(Trace trace, Instance image) {
      return Observable.create((Subscriber<? super Instance> subscriber) -> {
	Trace.Event pulling = trace.start("RxDocker: pull(image)", image);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.pull(image.toString(), message -> logPullProgress(trace, message));
	} catch(Exception ex) {
		trace.event(Level.ERROR, "RxDocker: pulling failed", ex);
		pulling.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	pulling.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(image);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 36
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> startContainer(Trace trace, String containerId) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event starting = trace.start("RxDocker: starting container (containerId): ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.startContainer(containerId);
	} catch(Exception ex) {
		trace.event(Level.ERROR, "RxDocker: starting failed", ex);
		starting.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	starting.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 37
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> killContainer(Trace trace, String containerId) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event killing = trace.start("RxDocker: killing container: ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.killContainer(containerId);
	} catch(Exception ex) {
		trace.event("RxDocker: killing failed", ex);
		killing.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	killing.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 38
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> stopContainer(Trace trace, String containerId, int secondsBeforeFail) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event stopping = trace.start("RxDocker: stopping container: ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.stopContainer(containerId, secondsBeforeFail);
	} catch(Exception ex) {
		trace.event("RxDocker: stopping failed", ex);
		stopping.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	stopping.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 39
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
  public Observable<String> removeContainer(Trace trace, String containerId) {
      return Observable.create((Subscriber<? super String> subscriber) -> {
	Event removing = trace.start("RxDocker: removing container: ", containerId);
	final DockerClient client;
	try {
		client = obtainDockerClient();
		client.removeContainer(containerId, true);
	} catch(Exception ex) {
		trace.event("RxDocker: removing failed", ex);
		removing.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onError(ex);
		return;
	}
	removing.end();
	
	if (subscriber.isUnsubscribed()) return;
	subscriber.onNext(containerId);
	subscriber.onCompleted();
}).subscribeOn(scheduler);
  }
 
Example 40
Project: mobi   File: SpotifyRxDocker.java   Source Code and License 6 votes vote down vote up
@Override
public Observable<ContainerInfo> inspectContainer(Trace trace, String containerId) {
	return Observable.create((Subscriber<? super ContainerInfo> subscriber) -> {
		Event inspecting = trace.start("RxDocker: inspecting container (containerId): ", containerId);
		final DockerClient client;
		final ContainerInfo info;
		try {
			client = obtainDockerClient();
			info = new SpotifyInspectWrapper(client.inspectContainer(containerId));
		} catch(Exception ex) {
			trace.event("RxDocker: inspecting failed", ex);
			inspecting.end();
			
			if (subscriber.isUnsubscribed()) return;
			subscriber.onError(ex);
			return;
		}
		inspecting.end();
		
		if (subscriber.isUnsubscribed()) return;
		subscriber.onNext(info);
		subscriber.onCompleted();
	}).subscribeOn(scheduler);
}