com.spotify.docker.client.messages.swarm.Service Java Examples

The following examples show how to use com.spotify.docker.client.messages.swarm.Service. 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: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public Service inspectService(final String serviceId)
    throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  try {
    final WebTarget resource = resource().path("services").path(serviceId);
    return request(GET, Service.class, resource, resource.request(APPLICATION_JSON_TYPE));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 404:
        throw new ServiceNotFoundException(serviceId);
      default:
        throw e;
    }
  }
}
 
Example #2
Source File: DockerBasedService.java    From pravega with Apache License 2.0 6 votes vote down vote up
public void start(final boolean wait, final ServiceSpec serviceSpec) {
    try {
        String serviceId = getServiceID();
        if (serviceId != null) {
             Service service = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId));
             Exceptions.handleInterrupted(() -> dockerClient.updateService(serviceId, service.version().index(), serviceSpec));
        } else {
            ServiceCreateResponse serviceCreateResponse = Exceptions.handleInterruptedCall(() -> dockerClient.createService(serviceSpec));
            assertNotNull("Service id is null", serviceCreateResponse.id());
        }
        if (wait) {
            Exceptions.handleInterrupted(() -> waitUntilServiceRunning().get(5, TimeUnit.MINUTES));
        }
    } catch (Exception e) {
        throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Unable to create service", e);
    }
}
 
Example #3
Source File: DockerBasedService.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> scaleService(final int instanceCount) {
    try {
        Preconditions.checkArgument(instanceCount >= 0, "negative value: %s", instanceCount);

        Service.Criteria criteria = Service.Criteria.builder().serviceName(this.serviceName).build();
        TaskSpec taskSpec = Exceptions.handleInterruptedCall(() -> dockerClient.listServices(criteria).get(0).spec().taskTemplate());
        String serviceId = getServiceID();
        EndpointSpec endpointSpec = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId).spec().endpointSpec());
        Service service = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId));
        Exceptions.handleInterrupted(() -> dockerClient.updateService(serviceId, service.version().index(), ServiceSpec.builder().endpointSpec(endpointSpec).mode(ServiceMode.withReplicas(instanceCount)).taskTemplate(taskSpec).name(serviceName).networks(service.spec().networks()).build()));
        return Exceptions.handleInterruptedCall(() -> waitUntilServiceRunning());
    } catch (DockerException e) {
        throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Test failure: Unable to scale service to given instances=" + instanceCount, e);
    }
}
 
Example #4
Source File: DockerBasedService.java    From pravega with Apache License 2.0 6 votes vote down vote up
private String getServiceID() {
    Service.Criteria criteria = Service.Criteria.builder().serviceName(this.serviceName).build();
    String serviceId = null;
    try {
        List<Service> serviceList = Exceptions.handleInterruptedCall(
                () -> dockerClient.listServices(criteria));
        log.info("Service list size {}", serviceList.size());
        if (!serviceList.isEmpty()) {
            serviceId = serviceList.get(0).id();
        }

    } catch (DockerException e) {
        throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Unable to get service id", e);
    }
    return serviceId;
}
 
Example #5
Source File: SwarmCluster.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
private void fetchTasks(DockerClient dockerClient) throws DockerException, InterruptedException {
    final Map<String, DockerNode> dockerNodeMap = nodes.stream().distinct().collect(toMap(DockerNode::getId, node -> node));
    final List<Task> tasks = dockerClient.listTasks();
    LOG.info("Running tasks " + tasks.size());
    final Map<String, Service> serviceIdToService = serviceIdToServiceMap(dockerClient);

    for (Task task : tasks) {
        final Service service = serviceIdToService.get(task.serviceId());
        if (service == null || !createdByPlugin(service)) {
            continue;
        }

        final DockerTask dockerTask = new DockerTask(task, service);
        final DockerNode dockerNode = dockerNodeMap.get(dockerTask.getNodeId());
        if (dockerNode != null) {
            dockerNode.add(dockerTask);
        }
    }
}
 
Example #6
Source File: AgentStatusReportExecutor.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
public GoPluginApiResponse execute() {
    String elasticAgentId = request.getElasticAgentId();
    JobIdentifier jobIdentifier = request.getJobIdentifier();
    LOG.info(String.format("[status-report] Generating status report for agent: %s with job: %s", elasticAgentId, jobIdentifier));

    try {
        final DockerClient dockerClient = dockerClientFactory.docker(request.getClusterProfileProperties());
        Service dockerService = findService(elasticAgentId, jobIdentifier, dockerClient);

        DockerServiceElasticAgent elasticAgent = DockerServiceElasticAgent.fromService(dockerService, dockerClient);
        final String statusReportView = builder.build(builder.getTemplate("agent-status-report.template.ftlh"), elasticAgent);

        JsonObject responseJSON = new JsonObject();
        responseJSON.addProperty("view", statusReportView);

        return DefaultGoPluginApiResponse.success(responseJSON.toString());
    } catch (Exception e) {
        return StatusReportGenerationErrorHandler.handle(builder, e);
    }
}
 
Example #7
Source File: DockerServices.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
private DockerServices unregisteredAfterTimeout(ClusterProfileProperties clusterProfileProperties, Agents knownAgents) throws Exception {
    Period period = clusterProfileProperties.getAutoRegisterPeriod();
    DockerServices unregisteredContainers = new DockerServices();

    for (String serviceName : services.keySet()) {
        if (knownAgents.containsServiceWithId(serviceName)) {
            continue;
        }

        Service serviceInfo;
        try {
            serviceInfo = docker(clusterProfileProperties).inspectService(serviceName);
        } catch (ServiceNotFoundException e) {
            LOG.warn("The container " + serviceName + " could not be found.");
            continue;
        }
        DateTime dateTimeCreated = new DateTime(serviceInfo.createdAt());

        if (clock.now().isAfter(dateTimeCreated.plus(period))) {
            unregisteredContainers.register(DockerService.fromService(serviceInfo));
        }
    }
    return unregisteredContainers;
}
 
Example #8
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateServiceWithPlacementPreference()
    throws IOException, DockerException, InterruptedException {
  final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);

  final ImmutableList<Preference> prefs = ImmutableList.of(
      Preference.create(
          Spread.create(
              "test"
          )
      )
  );

  final TaskSpec taskSpec = TaskSpec.builder()
      .placement(Placement.create(null, prefs))
      .containerSpec(ContainerSpec.builder()
          .image("this_image_is_found_in_the_registry")
          .build())
      .build();

  final ServiceSpec spec = ServiceSpec.builder()
      .name("test")
      .taskTemplate(taskSpec)
      .build();


  enqueueServerApiVersion("1.30");
  enqueueServerApiResponse(201, "fixtures/1.30/createServiceResponse.json");

  final ServiceCreateResponse response = dockerClient.createService(spec);
  assertThat(response.id(), equalTo("ak7w3gjqoa3kuz8xcpnyy0pvl"));

  enqueueServerApiVersion("1.30");
  enqueueServerApiResponse(200, "fixtures/1.30/inspectCreateResponseWithPlacementPrefs.json");

  final Service service = dockerClient.inspectService("ak7w3gjqoa3kuz8xcpnyy0pvl");
  assertThat(service.spec().taskTemplate().placement(), equalTo(taskSpec.placement()));
}
 
Example #9
Source File: ServiceController.java    From paas with Apache License 2.0 5 votes vote down vote up
/**
 * 查询服务详细信息
 * @author hf
 * @since 2018/7/13 15:39
 */
@GetMapping("/inspect/{id}")
@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_SYSTEM')")
public ResultVO inspectById(@RequestAttribute String uid, @PathVariable String id) {
    ResultVO resultVO = userServiceService.checkPermission(uid,id);
    if(ResultEnum.OK.getCode() != resultVO.getCode()) {
        return resultVO;
    }
    Service service = userServiceService.inspectById(id);

    return service != null ? ResultVOUtils.success(service) : ResultVOUtils.error(ResultEnum.SERVICE_INSPECT_ERROR) ;
}
 
Example #10
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public List<Service> listServices(final Service.Criteria criteria)
    throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  final Map<String, List<String>> filters = new HashMap<>();

  if (criteria.serviceId() != null) {
    filters.put("id", Collections.singletonList(criteria.serviceId()));
  }
  if (criteria.serviceName() != null) {
    filters.put("name", Collections.singletonList(criteria.serviceName()));
  }

  final List<String> labels = new ArrayList<>();
  for (Entry<String, String> input: criteria.labels().entrySet()) {
    if ("".equals(input.getValue())) {
      labels.add(input.getKey());
    } else {
      labels.add(String.format("%s=%s", input.getKey(), input.getValue()));
    }
  }

  if (!labels.isEmpty()) {
    filters.put("label", labels);
  }

  WebTarget resource = resource().path("services");
  resource = resource.queryParam("filters", urlEncodeFilters(filters));
  return request(GET, SERVICE_LIST, resource, resource.request(APPLICATION_JSON_TYPE));
}
 
Example #11
Source File: DockerBasedService.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    try {
        Service.Criteria criteria = Service.Criteria.builder().serviceName(this.serviceName).build();
        List<Service> serviceList = Exceptions.handleInterruptedCall(() -> dockerClient.listServices(criteria));
        for (int i = 0; i < serviceList.size(); i++) {
            String serviceId = serviceList.get(i).id();
            Exceptions.handleInterrupted(() -> dockerClient.removeService(serviceId));
        }
    } catch (DockerException e) {
        throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Unable to remove service.", e);
    }
}
 
Example #12
Source File: AgentStatusReportExecutor.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private Service findServiceUsingElasticAgentId(String elasticAgentId, DockerClient client) throws Exception {
    for (Service service : client.listServices()) {
        if (service.spec().name().equals(elasticAgentId) || service.id().equals(elasticAgentId)) {
            return service;
        }
    }
    throw StatusReportGenerationException.noRunningService(elasticAgentId);
}
 
Example #13
Source File: AgentStatusReportExecutor.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private Service findServiceUsingJobIdentifier(JobIdentifier jobIdentifier, DockerClient client) {
    try {
        return client.listServices(Service.Criteria.builder().addLabel(Constants.JOB_IDENTIFIER_LABEL_KEY, jobIdentifier.toJson()).build()).get(0);
    } catch (Exception e) {
        throw StatusReportGenerationException.noRunningService(jobIdentifier);
    }
}
 
Example #14
Source File: AgentStatusReportExecutor.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private Service findService(String elasticAgentId, JobIdentifier jobIdentifier, DockerClient dockerClient) throws Exception {
    Service dockerService;
    if (StringUtils.isNotBlank(elasticAgentId)) {
        dockerService = findServiceUsingElasticAgentId(elasticAgentId, dockerClient);
    } else {
        dockerService = findServiceUsingJobIdentifier(jobIdentifier, dockerClient);
    }
    return dockerService;
}
 
Example #15
Source File: DockerTask.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
public DockerTask(Task task, Service service) {
    id = task.id();
    image = task.spec().containerSpec().image();
    nodeId = task.nodeId();
    serviceId = task.serviceId();
    created = task.createdAt();
    state = capitalize(task.status().state());
    jobIdentifier = JobIdentifier.fromJson(service.spec().labels().get(Constants.JOB_IDENTIFIER_LABEL_KEY));
}
 
Example #16
Source File: DockerServiceElasticAgent.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
public static DockerServiceElasticAgent fromService(Service service, DockerClient client) throws DockerException, InterruptedException {
    DockerServiceElasticAgent agent = new DockerServiceElasticAgent();

    agent.id = service.id();
    agent.name = service.spec().name();
    agent.createdAt = service.createdAt();
    agent.jobIdentifier = JobIdentifier.fromJson(service.spec().labels().get(JOB_IDENTIFIER_LABEL_KEY));

    LogStream logStream = client.serviceLogs(service.id(), DockerClient.LogsParam.stdout(), DockerClient.LogsParam.stderr());
    agent.logs = logStream.readFully();
    logStream.close();

    TaskSpec taskSpec = service.spec().taskTemplate();

    agent.image = taskSpec.containerSpec().image();
    agent.hostname = taskSpec.containerSpec().hostname();
    agent.limits = resourceToString(taskSpec.resources().limits());
    agent.reservations = resourceToString(taskSpec.resources().reservations());
    agent.command = listToString(taskSpec.containerSpec().command());
    agent.args = listToString(taskSpec.containerSpec().args());
    agent.placementConstraints = listToString(taskSpec.placement().constraints());
    agent.environments = toMap(taskSpec);
    agent.hosts = listToString(taskSpec.containerSpec().hosts());

    final List<Task> tasks = client.listTasks(Task.Criteria.builder().serviceName(service.id()).build());
    if (!tasks.isEmpty()) {
        for (Task task : tasks) {
            agent.tasksStatus.add(new TaskStatus(task));
        }
    }

    return agent;
}
 
Example #17
Source File: SwarmCluster.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private Map<String, Service> serviceIdToServiceMap(DockerClient dockerClient) throws DockerException, InterruptedException {
    final List<Service> services = dockerClient.listServices();
    if (services == null || services.isEmpty()) {
        return Collections.emptyMap();
    }

    final HashMap<String, Service> serviceIdToService = new HashMap<>();
    for (Service service : services) {
        serviceIdToService.put(service.id(), service);
    }
    return serviceIdToService;
}
 
Example #18
Source File: SwarmCluster.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private boolean createdByPlugin(Service service) {
    final String createdBy = service.spec().labels().get(Constants.CREATED_BY_LABEL_KEY);
    if (StringUtils.isBlank(createdBy)) {
        return false;
    }

    return createdBy.equals(Constants.PLUGIN_ID);
}
 
Example #19
Source File: DockerServices.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private void refreshAgentInstances(ClusterProfileProperties pluginSettings) throws Exception {
    DockerClient dockerClient = docker(pluginSettings);
    List<Service> clusterSpecificServices = dockerClient.listServices();
    services.clear();
    for (Service service : clusterSpecificServices) {
        ImmutableMap<String, String> labels = service.spec().labels();
        if (labels != null && Constants.PLUGIN_ID.equals(labels.get(Constants.CREATED_BY_LABEL_KEY))) {
            register(DockerService.fromService(service));
        }
    }
    refreshed = true;
}
 
Example #20
Source File: NameBasedServiceFilter.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 5 votes vote down vote up
/**
 * @see ServiceFilter#accept(Service)
 */
@Override
public boolean accept(Service service) {
    try {
        return serviceName.equals(service.spec().name());
    } catch (NullPointerException e) {
        return false;
    }
}
 
Example #21
Source File: NullServiceFilter.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 4 votes vote down vote up
/**
 * @see ServiceFilter#accept(Service)
 */
@Override
public boolean accept(Service service) {
    return true;
}
 
Example #22
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Override
public List<Service> listServices() throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  final WebTarget resource = resource().path("services");
  return request(GET, SERVICE_LIST, resource, resource.request(APPLICATION_JSON_TYPE));
}
 
Example #23
Source File: DiscoveredContainer.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 4 votes vote down vote up
public DiscoveredContainer(Network network, Service service, Task task, NetworkAttachment relevantNetworkAttachment) {
    this.network = network;
    this.service = service;
    this.task = task;
    this.relevantNetworkAttachment = relevantNetworkAttachment;
}
 
Example #24
Source File: SwarmDiscoveryUtil.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 3 votes vote down vote up
/**
 * Discover containers on the relevant networks that match the given
 * service criteria, using additionally a NullServiceFilter
 *
 * @param docker
 * @param relevantNetIds2Networks
 * @param criteria
 * @return set of DiscoveredContainer instances
 * @throws Exception
 */
private Set<DiscoveredContainer> discoverContainersViaCriteria(DockerClient docker,
                                                               Map<String, Network> relevantNetIds2Networks,
                                                               Service.Criteria criteria) throws Exception {
    // no ServiceFilter provided, so use one with no constraints
    return discoverContainersViaCriteria(docker, relevantNetIds2Networks, criteria, NullServiceFilter.getInstance());
}
 
Example #25
Source File: UserServiceService.java    From paas with Apache License 2.0 2 votes vote down vote up
/**
 * 查询服务详情
 * @author hf
 * @since 2018/7/13 9:25
 */
Service inspectById(String id);
 
Example #26
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * List services that match the given criteria. Only available in Docker API &gt;= 1.24.
 *
 * @param criteria Service listing and filtering options.
 * @return A list of {@link Service}s
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
List<Service> listServices(Service.Criteria criteria)
        throws DockerException, InterruptedException;
 
Example #27
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * List all services. Only available in Docker API &gt;= 1.24.
 *
 * @return A list of services.
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
List<Service> listServices() throws DockerException, InterruptedException;
 
Example #28
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Inspect an existing service. Only available in Docker API &gt;= 1.24.
 *
 * @param serviceId the id of the service to inspect
 * @return Info about the service
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
Service inspectService(String serviceId) throws DockerException, InterruptedException;
 
Example #29
Source File: AbstractServiceFilter.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 2 votes vote down vote up
/**
 * @param service Service returned from criteria-based /services request
 * @return
 * @see ServiceFilter#reject(Service)
 */
@Override
public boolean reject(Service service) {
    return !accept(service);
}
 
Example #30
Source File: ServiceFilter.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 2 votes vote down vote up
/**
 * Apply criteria and return true if this service meets the criteria.
 *
 * @param service Service returned from criteria-based /services request
 * @return true if this Service meets additional criteria necessary for consideration
 */
boolean accept(Service service);