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

The following examples show how to use com.spotify.docker.client.messages.swarm.Task. 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: 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 #2
Source File: TaskStatus.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
public TaskStatus(Task task) {
    id = task.id();
    state = task.status().state();
    if ("failed".equals(state)) {
        message = task.status().err();
    } else {
        message = task.status().message();
    }

    if (task.status().containerStatus() != null) {
        if (StringUtils.isNotBlank(task.status().containerStatus().containerId())) {
            containerId = task.status().containerStatus().containerId().substring(0, 12);
        }
        exitCode = task.status().containerStatus().exitCode();

        if (task.status().containerStatus().pid() == null) {
            pid = "-";
        } else {
            pid = task.status().containerStatus().pid().toString();
        }
    }
}
 
Example #3
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 #4
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 #5
Source File: DockerBasedService.java    From pravega with Apache License 2.0 5 votes vote down vote up
private boolean isSynced() {
    int taskRunningCount = 0;
    try {
        Task.Criteria taskCriteria = Task.Criteria.builder().serviceName(serviceName).build();
        List<Task> taskList = Exceptions.handleInterruptedCall(
                () -> dockerClient.listTasks(taskCriteria));
        log.info("Task list size {}", taskList.size());
        if (!taskList.isEmpty()) {
            for (int j = 0; j < taskList.size(); j++) {
                log.info("Task id {}", taskList.get(j).id());
                String state = taskList.get(j).status().state();
                log.info("Task state {}", state);
                if (state.equals(TaskStatus.TASK_STATE_RUNNING)) {
                    taskRunningCount++;
                }
            }
        }
        long replicas = getReplicas();
        log.info("Replicas {}", replicas);
        log.info("Task running count {}", taskRunningCount);
        if (((long) taskRunningCount) == replicas) {
            return true;
        }
    } catch (DockerException e) {
        log.error("Unable to list docker services", e);
    }
    log.info("Service is not synced");
    return false;
}
 
Example #6
Source File: DockerBasedService.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public List<URI> getServiceDetails() {
    List<URI> uriList = new ArrayList<>();
    try {
        Task.Criteria taskCriteria = Task.Criteria.builder().taskName(serviceName).build();
        List<Task> taskList = Exceptions.handleInterruptedCall(() -> dockerClient.listTasks(taskCriteria));
        log.info("Task size {}", taskList.size());

        if (!taskList.isEmpty()) {
            log.info("Network addresses {}", taskList.get(0).networkAttachments().get(0).addresses().get(0));
            for (int i = 0; i < taskList.size(); i++) {
                log.info("task {}", taskList.get(i).name());
                if (taskList.get(i).status().state().equals(TaskStatus.TASK_STATE_RUNNING)) {
                    String[] uriArray = taskList.get(i).networkAttachments().get(0).addresses().get(0).split("/");
                    ImmutableList<PortConfig> numPorts = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(getServiceID()).endpoint().spec().ports());
                    for (int k = 0; k < numPorts.size(); k++) {
                        int port = numPorts.get(k).publishedPort();
                        log.info("Port {}", port);
                        log.info("Uri list {}", uriArray[0]);
                        URI uri = URI.create("tcp://" + uriArray[0] + ":" + port);
                        uriList.add(uri);
                    }
                }
            }
        }
    } catch (DockerException e) {
        log.error("Unable to list service details", e);
    }
    return uriList;
}
 
Example #7
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public Task inspectTask(final String taskId) throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  try {
    final WebTarget resource = resource().path("tasks").path(taskId);
    return request(GET, Task.class, resource, resource.request(APPLICATION_JSON_TYPE));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 404:
        throw new TaskNotFoundException(taskId);
      default:
        throw e;
    }
  }
}
 
Example #8
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public List<Task> listTasks(final Task.Criteria criteria)
    throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  final Map<String, List<String>> filters = new HashMap<>();

  if (criteria.taskId() != null) {
    filters.put("id", Collections.singletonList(criteria.taskId()));
  }
  if (criteria.taskName() != null) {
    filters.put("name", Collections.singletonList(criteria.taskName()));
  }
  if (criteria.serviceName() != null) {
    filters.put("service", Collections.singletonList(criteria.serviceName()));
  }
  if (criteria.nodeId() != null) {
    filters.put("node", Collections.singletonList(criteria.nodeId()));
  }
  if (criteria.label() != null) {
    filters.put("label", Collections.singletonList(criteria.label()));
  }
  if (criteria.desiredState() != null) {
    filters.put("desired-state", Collections.singletonList(criteria.desiredState()));
  }

  WebTarget resource = resource().path("tasks");
  resource = resource.queryParam("filters", urlEncodeFilters(filters));
  return request(GET, TASK_LIST, resource, resource.request(APPLICATION_JSON_TYPE));
}
 
Example #9
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testInspectTask() throws Exception {
  final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);

  enqueueServerApiVersion("1.24");
  enqueueServerApiResponse(200, "fixtures/1.24/task.json");

  final Task task = dockerClient.inspectTask("0kzzo1i0y4jz6027t0k7aezc7");

  assertThat(task, is(pojo(Task.class)
      .where("id", is("0kzzo1i0y4jz6027t0k7aezc7"))
      .where("version", is(pojo(Version.class)
          .where("index", is(71L))
      ))
      .where("createdAt", is(Date.from(Instant.parse("2016-06-07T21:07:31.171892745Z"))))
      .where("updatedAt", is(Date.from(Instant.parse("2016-06-07T21:07:31.376370513Z"))))
      .where("spec", is(pojo(TaskSpec.class)
          .where("containerSpec", is(pojo(ContainerSpec.class)
              .where("image", is("redis"))
          ))
          .where("resources", is(pojo(ResourceRequirements.class)
              .where("limits",
                  is(pojo(com.spotify.docker.client.messages.swarm.Resources.class)))
              .where("reservations",
                  is(pojo(com.spotify.docker.client.messages.swarm.Resources.class)))
          ))
      ))
  ));
}
 
Example #10
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 #11
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Override
public List<Task> listTasks() throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  final WebTarget resource = resource().path("tasks");
  return request(GET, TASK_LIST, resource, resource.request(APPLICATION_JSON_TYPE));
}
 
Example #12
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testListTaskWithCriteria() throws Exception {
  final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);

  enqueueServerApiVersion("1.24");
  enqueueServerApiResponse(200, "fixtures/1.24/tasks.json");
  final List<Task> tasks = dockerClient.listTasks();
  // Throw away the first request that gets the docker server version
  takeRequestImmediately();
  final RecordedRequest recordedRequest = takeRequestImmediately();
  assertThat(recordedRequest.getRequestUrl().querySize(), is(0));
  assertThat(tasks, contains(
      pojo(Task.class)
          .where("id", is("0kzzo1i0y4jz6027t0k7aezc7")),
      pojo(Task.class)
          .where("id", is("1yljwbmlr8er2waf8orvqpwms"))
  ));

  enqueueServerApiVersion("1.24");
  enqueueServerApiResponse(200, "fixtures/1.24/tasks.json");
  final String taskId = "task-1";
  dockerClient.listTasks(Task.find().taskId(taskId).build());
  takeRequestImmediately();
  final RecordedRequest recordedRequest2 = takeRequestImmediately();
  final HttpUrl requestUrl2 = recordedRequest2.getRequestUrl();
  assertThat(requestUrl2.querySize(), is(1));
  final JsonNode requestJson2 =
      toJson(recordedRequest2.getRequestUrl().queryParameter("filters"));
  assertThat(requestJson2, is(jsonObject()
      .where("id", is(jsonArray(
          contains(jsonText(taskId)))))));

  enqueueServerApiVersion("1.24");
  enqueueServerApiResponse(200, "fixtures/1.24/tasks.json");
  final String serviceName = "service-1";
  dockerClient.listTasks(Task.find().serviceName(serviceName).build());
  takeRequestImmediately();
  final RecordedRequest recordedRequest3 = takeRequestImmediately();
  final HttpUrl requestUrl3 = recordedRequest3.getRequestUrl();
  assertThat(requestUrl3.querySize(), is(1));
  final JsonNode requestJson3 =
      toJson(recordedRequest3.getRequestUrl().queryParameter("filters"));
  assertThat(requestJson3, is(jsonObject()
      .where("service", is(jsonArray(
          contains(jsonText(serviceName)))))));
}
 
Example #13
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Inspect an existing task. Only available in Docker API &gt;= 1.24.
 *
 * @param taskId the id of the task to inspect
 * @return Info about the task
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
Task inspectTask(String taskId)
        throws DockerException, InterruptedException;
 
Example #14
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * List all tasks. Only available in Docker API &gt;= 1.24.
 *
 * @return A list of tasks.
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
List<Task> listTasks()
        throws DockerException, InterruptedException;
 
Example #15
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * List tasks that match the given criteria. Only available in Docker API &gt;= 1.24.
 *
 * @param criteria {@link Task.Criteria}
 * @return A list of tasks.
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
List<Task> listTasks(Task.Criteria criteria)
        throws DockerException, InterruptedException;