com.spotify.docker.client.messages.ServiceCreateResponse Java Examples

The following examples show how to use com.spotify.docker.client.messages.ServiceCreateResponse. 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: 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 #2
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceCreateResponse createService(final ServiceSpec spec,
                                           final RegistryAuth config)
    throws DockerException, InterruptedException {
  assertApiVersionIsAbove("1.24");
  final WebTarget resource = resource().path("services").path("create");

  try {
    return request(POST, ServiceCreateResponse.class, resource,
                   resource.request(APPLICATION_JSON_TYPE)
                       .header("X-Registry-Auth", authHeader(config)), Entity.json(spec));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 406:
        throw new DockerException("Server error or node is not part of swarm.", e);
      case 409:
        throw new DockerException("Name conflicts with an existing object.", e);
      default:
        throw e;
    }
  }
}
 
Example #3
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateServiceWithWarnings() throws Exception {
  final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);

  // build() calls /version to check what format of header to send
  enqueueServerApiVersion("1.25");
  enqueueServerApiResponse(201, "fixtures/1.25/createServiceResponse.json");

  final TaskSpec taskSpec = TaskSpec.builder()
      .containerSpec(ContainerSpec.builder()
          .image("this_image_is_not_found_in_the_registry")
          .build())
      .build();

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

  final ServiceCreateResponse response = dockerClient.createService(spec);
  assertThat(response.id(), is(notNullValue()));
  assertThat(response.warnings(), is(hasSize(1)));
  assertThat(response.warnings(),
      contains("unable to pin image this_image_is_not_found_in_the_registry to digest"));
}
 
Example #4
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 #5
Source File: DockerService.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 4 votes vote down vote up
public static DockerService create(CreateAgentRequest request, PluginSettings settings, DockerClient docker) throws InterruptedException, DockerException {
    String serviceName = UUID.randomUUID().toString();

    HashMap<String, String> labels = labelsFrom(request);
    String imageName = image(request.properties());
    String[] env = environmentFrom(request, settings, serviceName);

    final ContainerSpec.Builder containerSpecBuilder = ContainerSpec.builder()
            .image(imageName)
            .env(env);

    if (StringUtils.isNotBlank(request.properties().get("Command"))) {
        containerSpecBuilder.command(splitIntoLinesAndTrimSpaces(request.properties().get("Command")).toArray(new String[]{}));
    }

    if (dockerApiVersionAtLeast(docker, "1.26")) {
        containerSpecBuilder.hosts(new Hosts().hosts(request.properties().get("Hosts")));
        final DockerMounts dockerMounts = DockerMounts.fromString(request.properties().get("Mounts"));
        containerSpecBuilder.mounts(dockerMounts.toMount());
        final DockerSecrets dockerSecrets = DockerSecrets.fromString(request.properties().get("Secrets"));
        containerSpecBuilder.secrets(dockerSecrets.toSecretBind(docker.listSecrets()));
    } else {
        LOG.warn(format("Detected docker version and api version is {0} and {1} respectively. Docker with api version 1.26 or above is required to use volume mounts, secrets and host file entries. Please refer https://docs.docker.com/engine/api/v1.32/#section/Versioning for more information about docker release.", docker.version().version(), docker.version().apiVersion()));
    }

    Driver.Builder driverBuilder = Driver.builder()
            .name(request.properties().get("LogDriver"))
            .options(Util.linesToMap(request.properties().get("LogDriverOptions")));

    TaskSpec taskSpec = TaskSpec.builder()
            .containerSpec(containerSpecBuilder.build())
            .resources(resourceRequirements(request))
            .placement(Placement.create(Util.linesToList(request.properties().get("Constraints"))))
            .logDriver(StringUtils.isBlank(request.properties().get("LogDriver")) ? null : driverBuilder.build())
            .build();

    ServiceSpec serviceSpec = ServiceSpec.builder()
            .name(serviceName)
            .labels(labels)
            .taskTemplate(taskSpec)
            .networks(Networks.fromString(request.properties().get("Networks"), docker.listNetworks()))
            .build();

    ServiceCreateResponse service = docker.createService(serviceSpec);

    String id = service.id();

    Service serviceInfo = docker.inspectService(id);

    LOG.debug("Created service " + serviceInfo.spec().name());
    return new DockerService(serviceName,
            serviceInfo.createdAt(),
            request.properties(),
            request.environment(),
            request.jobIdentifier());
}
 
Example #6
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Override
public ServiceCreateResponse createService(ServiceSpec spec)
    throws DockerException, InterruptedException {
  return createService(spec, registryAuthSupplier.authForSwarm());
}
 
Example #7
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateServiceWithConfig() throws Exception {
  final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);

  // build() calls /version to check what format of header to send
  enqueueServerApiVersion("1.30");
  enqueueServerApiResponse(201, "fixtures/1.30/configCreateResponse.json");

  final ConfigSpec configSpec = ConfigSpec
      .builder()
      .data(Base64.encodeAsString("foobar"))
      .name("foo.yaml")
      .build();

  final ConfigCreateResponse configCreateResponse = dockerClient.createConfig(configSpec);
  assertThat(configCreateResponse.id(), equalTo("ktnbjxoalbkvbvedmg1urrz8h"));

  final ConfigBind configBind = ConfigBind.builder()
      .configName(configSpec.name())
      .configId(configCreateResponse.id())
      .file(ConfigFile.builder()
        .gid("1000")
        .uid("1000")
        .mode(600L)
        .name(configSpec.name())
        .build()
      ).build();

  final TaskSpec taskSpec = TaskSpec.builder()
      .containerSpec(ContainerSpec.builder()
          .image("this_image_is_found_in_the_registry")
          .configs(ImmutableList.of(configBind))
          .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"));
}
 
Example #8
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new service. Only available in Docker API &gt;= 1.24.
 *
 * @param spec the service spec
 * @return Service creation result with service id.
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
ServiceCreateResponse createService(ServiceSpec spec)
        throws DockerException, InterruptedException;
 
Example #9
Source File: DockerClient.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new service. Only available in Docker API &gt;= 1.24.
 *
 * @param spec       the service spec
 * @param registryAuth the registry authentication configuration
 * @return Service creation result with service id.
 * @throws DockerException      if a server error occurred (500)
 * @throws InterruptedException If the thread is interrupted
 */
ServiceCreateResponse createService(ServiceSpec spec, RegistryAuth registryAuth)
        throws DockerException, InterruptedException;