Java Code Examples for io.fabric8.kubernetes.client.utils.Serialization

The following examples show how to use io.fabric8.kubernetes.client.utils.Serialization. These examples are extracted from open source projects. 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
@Used("tests")
/* package local for tests */ Pod getPodTemplateInternal(@NotNull final CloudInstanceUserData cloudInstanceUserData,
                                  @NotNull final String imageId,
                                  @NotNull final String namespace,
                                  final String instanceName,
                                  String spec) {
    spec = spec.replaceAll("%instance\\.id%", instanceName);

    if (StringUtil.isEmpty(spec)) {
        throw new KubeCloudException("Custom pod template spec is not specified for image " + imageId);
    }

    final PodTemplateSpec podTemplateSpec = Serialization.unmarshal(
      new ByteArrayInputStream(spec.getBytes()),
      PodTemplateSpec.class
    );

    return patchedPodTemplateSpec(podTemplateSpec,
                                  instanceName,
                                  namespace,
                                  myServerSettings.getServerUUID(),
                                  imageId,
                                  cloudInstanceUserData);
}
 
Example 2
@Nullable
@Override
public PersistentVolumeClaim getPVC(@NotNull final String instanceName,
                                    @NotNull final KubeCloudImage kubeCloudImage) {
    String pvcTemplate = kubeCloudImage.getPVCTemplate();
    if (StringUtil.isEmpty(pvcTemplate)){
        return null;
    }
    pvcTemplate = pvcTemplate.replaceAll("%instance\\.id%", instanceName);
    final PersistentVolumeClaim pvc = Serialization.unmarshal(
      new ByteArrayInputStream(pvcTemplate.getBytes()),
      PersistentVolumeClaim.class
    );

    return pvc;
}
 
Example 3
Source Project: kubernetes-plugin   Source File: PodTemplateUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Pod parseFromYaml(String yaml) {
    String s = yaml;
    try (KubernetesClient client = new DefaultKubernetesClient()) {
        // JENKINS-57116
        if (StringUtils.isBlank(s)) {
            LOGGER.log(Level.WARNING, "[JENKINS-57116] Trying to parse invalid yaml: \"{0}\"", yaml);
            s = "{}";
        }
        Pod podFromYaml;
        try (InputStream is = new ByteArrayInputStream(s.getBytes(UTF_8))) {
            podFromYaml = client.pods().load(is).get();
        } catch (IOException | KubernetesClientException e) {
            throw new RuntimeException(String.format("Failed to parse yaml: \"%s\"", yaml), e);
        }
        LOGGER.finest(() -> "Parsed pod template from yaml: " + Serialization.asYaml(podFromYaml));
        // yaml can be just a fragment, avoid NPEs
        if (podFromYaml.getMetadata() == null) {
            podFromYaml.setMetadata(new ObjectMeta());
        }
        if (podFromYaml.getSpec() == null) {
            podFromYaml.setSpec(new PodSpec());
        }
        return podFromYaml;
    }
}
 
Example 4
Source Project: kubernetes-plugin   Source File: KubernetesTestUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void createSecret(KubernetesClient client, String namespace) {
    Secret secret = new SecretBuilder()
            .withStringData(ImmutableMap.of(SECRET_KEY, CONTAINER_ENV_VAR_FROM_SECRET_VALUE)).withNewMetadata()
            .withName("container-secret").endMetadata().build();
    secret = client.secrets().inNamespace(namespace).createOrReplace(secret);

    LOGGER.log(Level.INFO, "Created container secret: " + Serialization.asYaml(secret));
    secret = new SecretBuilder().withStringData(ImmutableMap.of(SECRET_KEY, POD_ENV_VAR_FROM_SECRET_VALUE))
            .withNewMetadata().withName("pod-secret").endMetadata().build();
    secret = client.secrets().inNamespace(namespace).createOrReplace(secret);
    LOGGER.log(Level.INFO, "Created pod secret: " + Serialization.asYaml(secret));

    secret = new SecretBuilder().withStringData(ImmutableMap.of(SECRET_KEY, ""))
            .withNewMetadata().withName("empty-secret").endMetadata().build();
    secret = client.secrets().inNamespace(namespace).createOrReplace(secret);
    LOGGER.log(Level.INFO, "Created pod secret: " + Serialization.asYaml(secret));
}
 
Example 5
Source Project: kubernetes-client   Source File: OperationSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Send an http request and handle the response, optionally performing placeholder substitution to the response.
 *
 * @param client               OkHttp client provided
 * @param requestBuilder       Request builder
 * @param type                 Type of object provided
 * @param parameters           A hashmap containing parameters
 * @param <T>                  Template argument provided
 *
 * @return                      Returns a de-serialized object as api server response of provided type.
 * @throws ExecutionException   Execution Exception
 * @throws InterruptedException Interrupted Exception
 * @throws KubernetesClientException KubernetesClientException
 * @throws IOException IOException
 */
protected <T> T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
  VersionUsageUtils.log(this.resourceT, this.apiGroupVersion);
  Request request = requestBuilder.build();
  Response response = client.newCall(request).execute();
  try (ResponseBody body = response.body()) {
    assertResponseCode(request, response);
    if (type != null) {
      try (InputStream bodyInputStream = body.byteStream()) {
        return Serialization.unmarshal(bodyInputStream, type, parameters);
      }
    } else {
      return null;
    }
  } catch (Exception e) {
    if (e instanceof KubernetesClientException) {
      throw e;
    }
    throw requestException(request, e);
  } finally {
    if(response != null && response.body() != null) {
      response.body().close();
    }
  }
}
 
Example 6
public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(OkHttpClient client, Config config, String namespace, String explicitNamespace, Boolean fromServer, Boolean deletingExisting, List<Visitor> visitors, Object item, InputStream inputStream, Map<String, String> parameters, long gracePeriodSeconds, DeletionPropagation propagationPolicy, Boolean cascading, long watchRetryInitialBackoffMillis, double watchRetryBackoffMultiplier) {
    super(client, config);
    this.fallbackNamespace = namespace;
    this.explicitNamespace = explicitNamespace;
    this.fromServer = fromServer;
    this.deletingExisting = deletingExisting;
    this.visitors = visitors != null ? new ArrayList<>(visitors) : new ArrayList<>();
    this.watchRetryInitialBackoffMillis = watchRetryInitialBackoffMillis;
    this.watchRetryBackoffMultiplier = watchRetryBackoffMultiplier;

  if (item != null) {
      this.item = item;
    } else if (inputStream != null) {
      this.item = Serialization.unmarshal(inputStream, parameters);
    } else {
      throw new IllegalArgumentException("Need to either specify an Object or an InputStream.");
    }

    this.inputStream = inputStream;
    this.cascading = cascading;
    this.gracePeriodSeconds = gracePeriodSeconds;
    this.propagationPolicy = propagationPolicy;
    this.visitors.add(new ChangeNamespace(explicitNamespace, fallbackNamespace));
}
 
Example 7
Source Project: kubernetes-client   Source File: WatchHTTPManager.java    License: Apache License 2.0 6 votes vote down vote up
protected static WatchEvent readWatchEvent(String messageSource) throws IOException {
  WatchEvent event = Serialization.unmarshal(messageSource, WatchEvent.class);
  KubernetesResource object = null;
  if (event != null) {
    object = event.getObject();;
  }
  // when watching API Groups we don't get a WatchEvent resource
  // so the object will be null
  // so lets try parse the message as a KubernetesResource
  // as it will probably be a list of resources like a BuildList
  if (object == null) {
    object = Serialization.unmarshal(messageSource, KubernetesResource.class);
    if (event == null) {
      event = new WatchEvent(object, "MODIFIED");
    } else {
      event.setObject(object);
    }
  }
  if (event.getType() == null) {
    event.setType("MODIFIED");
  }
  return event;
}
 
Example 8
Source Project: kubernetes-client   Source File: OpenshiftAdapterSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check if OpenShift API Groups are available
 * @param client   The client.
 * @return         True if the new <code>/apis/*.openshift.io/</code> APIs are found in the root paths.
 */
static boolean isOpenShiftAPIGroups(Client client) {
  URL masterUrl = client.getMasterUrl();

  OkHttpClient httpClient = ((BaseClient)client).getHttpClient();
  try {
    Request.Builder requestBuilder = new Request.Builder()
      .get()
      .url(URLUtils.join(masterUrl.toString(), APIS));
    Response response = httpClient.newCall(requestBuilder.build()).execute();
    APIGroupList apiGroupList = Serialization.unmarshal(response.body().string(), APIGroupList.class);

    for (APIGroup apiGroup : apiGroupList.getGroups()) {
      if (apiGroup.getName().endsWith("openshift.io")) {
        return true;
      }
    }
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return false;
}
 
Example 9
Source Project: kubernetes-client   Source File: OpenshiftAdapterSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check if OpenShift API Groups are available
 * @param httpClient   The httpClient.
 * @param masterUrl    The master url.
 * @return             True if the new <code>/apis/*.openshift.io/</code> APIs are found in the root paths.
 */
static boolean isOpenShiftAPIGroups(OkHttpClient httpClient, String masterUrl) {
  try {
    Request.Builder requestBuilder = new Request.Builder()
      .get()
      .url(URLUtils.join(masterUrl, APIS));
    Response response = httpClient.newCall(requestBuilder.build()).execute();
    APIGroupList apiGroupList = Serialization.unmarshal(response.body().string(), APIGroupList.class);

    for (APIGroup apiGroup : apiGroupList.getGroups()) {
      if (apiGroup.getName().endsWith("openshift.io")) {
        return true;
      }
    }
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return false;
}
 
Example 10
Source Project: java-operator-sdk   Source File: IntegrationTestSupport.java    License: Apache License 2.0 5 votes vote down vote up
private <T> T loadYaml(Class<T> clazz, String yaml) {
    try (InputStream is = getClass().getResourceAsStream(yaml)) {
        return Serialization.unmarshal(is, clazz);
    } catch (IOException ex) {
        throw new IllegalStateException("Cannot find yaml on classpath: " + yaml);
    }
}
 
Example 11
Source Project: java-operator-sdk   Source File: WebServerController.java    License: Apache License 2.0 5 votes vote down vote up
private <T> T loadYaml(Class<T> clazz, String yaml) {
    try (InputStream is = getClass().getResourceAsStream(yaml)) {
        return Serialization.unmarshal(is, clazz);
    } catch (IOException ex) {
        throw new IllegalStateException("Cannot find yaml on classpath: " + yaml);
    }
}
 
Example 12
private String asYaml(List<HasMetadata> list) throws DevfileRecipeFormatException {
  try {
    return Serialization.asYaml(new KubernetesListBuilder().withItems(list).build());
  } catch (KubernetesClientException e) {
    throw new DevfileRecipeFormatException(
        format(
            "Unable to deserialize objects to store them in workspace config. Error: %s",
            e.getMessage()),
        e);
  }
}
 
Example 13
Source Project: kubernetes-plugin   Source File: KubernetesSlave.java    License: Apache License 2.0 5 votes vote down vote up
private String podAsYaml() {
    String x = Serialization.asYaml(pod);
    Computer computer = toComputer();
    if (computer instanceof SlaveComputer) {
        SlaveComputer sc = (SlaveComputer) computer;
        return x.replaceAll(sc.getJnlpMac(),"********");
    }
    return x;
}
 
Example 14
/**
 * Wait until all pod containers are running
 * 
 * @return the pod
 * @throws IllegalStateException
 *             if pod or containers are no longer running
 * @throws KubernetesClientTimeoutException
 *             if time ran out
 */
private Pod periodicAwait(int i, long started, long interval, long amount) {
    Pod pod = client.pods().inNamespace(this.pod.getMetadata().getNamespace())
            .withName(this.pod.getMetadata().getName()).get();
    if (pod == null) {
        throw new IllegalStateException(String.format("Pod is no longer available: %s/%s",
                this.pod.getMetadata().getNamespace(), this.pod.getMetadata().getName()));
    } else {
        LOGGER.finest(() -> "Updating pod for " + this.pod.getMetadata().getNamespace() + "/" + this.pod.getMetadata().getName() + " : " + Serialization.asYaml(pod));
        this.pod = pod;
    }
    List<ContainerStatus> terminatedContainers = PodUtils.getTerminatedContainers(pod);
    if (!terminatedContainers.isEmpty()) {
        throw new IllegalStateException(String.format("Pod has terminated containers: %s/%s (%s)",
                this.pod.getMetadata().getNamespace(),
                this.pod.getMetadata().getName(),
                terminatedContainers.stream()
                        .map(ContainerStatus::getName)
                        .collect(joining(", ")
                        )));
    }
    if (areAllContainersRunning(pod)) {
        return pod;
    }
    try {
        return awaitWatcher(interval, TimeUnit.MILLISECONDS);
    } catch (KubernetesClientTimeoutException e) {
        if (i <= 0) {
            throw e;
        }
    }

    long remaining = (started + amount) - System.currentTimeMillis();
    long next = Math.max(0, Math.min(remaining, interval));
    return periodicAwait(i - 1, started, next, amount);
}
 
Example 15
private static HasMetadata toKubernetesResource(String s) {
  try (InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8.name()))) {
    return Serialization.unmarshal(stream);
  } catch (Exception e) {
    return toRawHasMetadata(s);
  }
}
 
Example 16
private static HasMetadata toRawHasMetadata(String s) {
  try (InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8.name()))) {
    return Serialization.jsonMapper().readValue(stream, FallbackHasMetadata.class);
  } catch (Exception e) {
    return null;
  }
}
 
Example 17
Source Project: kubernetes-client   Source File: AdmissionReviewTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Should be able to deserialize from AdmissionRequest option set to CreateOption")
public void testJacksonParsingWithCreateOptions() throws IOException {
  InputStream jsonStream = getClass().getResourceAsStream("/admissionreview.json");
  AdmissionReview admissionReview = Serialization.unmarshal(jsonStream, AdmissionReview.class);
  assertEquals("CREATE", admissionReview.getRequest().getOperation());
  assertRequest(admissionReview);
}
 
Example 18
Source Project: kubernetes-client   Source File: AdmissionReviewTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Should be able to deserialize from AdmissionRequest option set to UpdateOption")
public void testJacksonParsingWithUpdateOptions() throws IOException {
  InputStream jsonStream = getClass().getResourceAsStream("/admissionreview-withupdateoptions.json");
  AdmissionReview admissionReview = Serialization.unmarshal(jsonStream, AdmissionReview.class);
  assertEquals("UPDATE", admissionReview.getRequest().getOperation());
  assertRequest(admissionReview);
}
 
Example 19
Source Project: kubernetes-client   Source File: AdmissionReviewTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Should be able to deserialize from AdmissionRequest option set to PatchOption")
public void testJacksonParsingWithPathOptions() throws IOException {
  InputStream jsonStream = getClass().getResourceAsStream("/admissionreview-withpatchoptions.json");
  AdmissionReview admissionReview = Serialization.unmarshal(jsonStream, AdmissionReview.class);
  assertEquals("PATCH", admissionReview.getRequest().getOperation());
  assertRequest(admissionReview);
}
 
Example 20
Source Project: kubernetes-client   Source File: ConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInstantiateClientUsingSerializeDeserialize() throws MalformedURLException {
  DefaultKubernetesClient original = new DefaultKubernetesClient();
  String json = Serialization.asJson(original.getConfiguration());
  DefaultKubernetesClient copy = DefaultKubernetesClient.fromConfig(json);

  assertEquals(original.getConfiguration().getMasterUrl(), copy.getConfiguration().getMasterUrl());
  assertEquals(original.getConfiguration().getOauthToken(), copy.getConfiguration().getOauthToken());
  assertEquals(original.getConfiguration().getNamespace(), copy.getConfiguration().getNamespace());
  assertEquals(original.getConfiguration().getUsername(), copy.getConfiguration().getUsername());
  assertEquals(original.getConfiguration().getPassword(), copy.getConfiguration().getPassword());
}
 
Example 21
Source Project: kubernetes-client   Source File: OpenShiftConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldInstantiateClientUsingSerializeDeserialize() throws MalformedURLException {
  DefaultOpenShiftClient original = new DefaultOpenShiftClient();
  String json = Serialization.asJson(original.getConfiguration());
  DefaultOpenShiftClient copy = DefaultOpenShiftClient.fromConfig(json);

  Assert.assertEquals(original.getConfiguration().getMasterUrl(), copy.getConfiguration().getMasterUrl());
  Assert.assertEquals(original.getConfiguration().getOauthToken(), copy.getConfiguration().getOauthToken());
  Assert.assertEquals(original.getConfiguration().getNamespace(), copy.getConfiguration().getNamespace());
  Assert.assertEquals(original.getConfiguration().getUsername(), copy.getConfiguration().getUsername());
  Assert.assertEquals(original.getConfiguration().getPassword(), copy.getConfiguration().getPassword());
}
 
Example 22
Source Project: abstract-operator   Source File: CrdDeployer.java    License: Apache License 2.0 4 votes vote down vote up
public CustomResourceDefinition initCrds(KubernetesClient client,
                                                String prefix,
                                                String entityName,
                                                String[] shortNames,
                                                String pluralName,
                                                String[] additionalPrinterColumnNames,
                                                String[] additionalPrinterColumnPaths,
                                                String[] additionalPrinterColumnTypes,
                                                Class<? extends EntityInfo> infoClass,
                                                boolean isOpenshift) {
    final String newPrefix = prefix.substring(0, prefix.length() - 1);
    CustomResourceDefinition crdToReturn;

    Serialization.jsonMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    List<CustomResourceDefinition> crds = client.customResourceDefinitions()
            .list()
            .getItems()
            .stream()
            .filter(p -> entityName.equals(p.getSpec().getNames().getKind()) && newPrefix.equals(p.getSpec().getGroup()))
            .collect(Collectors.toList());
    if (!crds.isEmpty()) {
        crdToReturn = crds.get(0);
        log.info("CustomResourceDefinition for {} has been found in the K8s, so we are skipping the creation.", entityName);
    } else {
        log.info("Creating CustomResourceDefinition for {}.", entityName);
        JSONSchemaProps schema = JSONSchemaReader.readSchema(infoClass);
        CustomResourceDefinitionFluent.SpecNested<CustomResourceDefinitionBuilder> builder;

        if (schema != null) {
            removeDefaultValues(schema);
            builder = getCRDBuilder(newPrefix,
                                    entityName,
                                    shortNames,
                                    pluralName)
                    .withNewValidation()
                    .withNewOpenAPIV3SchemaLike(schema)
                    .endOpenAPIV3Schema()
                    .endValidation();
        } else {
            builder = getCRDBuilder(newPrefix,
                                    entityName,
                                    shortNames,
                                    pluralName);
        }
        if (additionalPrinterColumnNames != null && additionalPrinterColumnNames.length > 0) {
            for (int i = 0; i < additionalPrinterColumnNames.length; i++) {
                builder = builder.addNewAdditionalPrinterColumn().withName(additionalPrinterColumnNames[i]).withJSONPath(additionalPrinterColumnPaths[i]).endAdditionalPrinterColumn();
            }
        }
        crdToReturn = builder.endSpec().build();
        try {
            if (schema != null) {
                // https://github.com/fabric8io/kubernetes-client/issues/1486
                crdToReturn.getSpec().getValidation().getOpenAPIV3Schema().setDependencies(null);
            }

            client.customResourceDefinitions().createOrReplace(crdToReturn);
        } catch (KubernetesClientException e) {
            // old version of K8s/openshift -> don't use schema validation
            log.warn("Consider upgrading the {}. Your version doesn't support schema validation for custom resources."
                    , isOpenshift ? "OpenShift" : "Kubernetes");
            crdToReturn = getCRDBuilder(newPrefix,
                                        entityName,
                                        shortNames,
                                        pluralName)
                    .endSpec()
                    .build();
            client.customResourceDefinitions().createOrReplace(crdToReturn);
        }
    }

    // register the new crd for json serialization
    io.fabric8.kubernetes.internal.KubernetesDeserializer.registerCustomKind(newPrefix + "/" + crdToReturn.getSpec().getVersion() + "#" + entityName, InfoClass.class);
    io.fabric8.kubernetes.internal.KubernetesDeserializer.registerCustomKind(newPrefix + "/" + crdToReturn.getSpec().getVersion() + "#" + entityName + "List", CustomResourceList.class);

    return crdToReturn;
}
 
Example 23
Source Project: enmasse   Source File: IoTUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static void waitForIoTProjectReady(Kubernetes kubernetes, IoTProject project) throws Exception {
    boolean isReady = false;
    TimeoutBudget budget = new TimeoutBudget(15, TimeUnit.MINUTES);
    var iotProjectClient = kubernetes.getIoTProjectClient(project.getMetadata().getNamespace());
    while (budget.timeLeft() >= 0 && !isReady) {
        project = iotProjectClient.withName(project.getMetadata().getName()).get();
        isReady = project.getStatus() != null && "Active".equals(project.getStatus().getPhase());
        if (!isReady) {
            log.info("Waiting until IoTProject: '{}' will be in ready state -> {}", project.getMetadata().getName(),
                    project.getStatus() != null ? project.getStatus().getPhase() : null);
            Thread.sleep(10000);
        }
    }

    final String jsonStatus = project.getStatus() != null ? Serialization.asJson(project.getStatus()) : "Project doesn't have status";
    if (!isReady) {
        throw new IllegalStateException("IoTProject " + project.getMetadata().getName() + " is not in Ready state within timeout: " + jsonStatus);
    }

    // refresh
    log.info("IoTProject is ready - phase: {} -> {}", project.getStatus().getPhase(), jsonStatus);

    if (project.getSpec().getDownstreamStrategy() != null
            && project.getSpec().getDownstreamStrategy().getManagedStrategy() != null
            && project.getSpec().getDownstreamStrategy().getManagedStrategy().getAddressSpace() != null
            && project.getSpec().getDownstreamStrategy().getManagedStrategy().getAddressSpace().getName() != null) {
        var addressSpaceName = project.getSpec().getDownstreamStrategy().getManagedStrategy().getAddressSpace().getName();
        var addressSpace = Kubernetes.getInstance().getAddressSpaceClient(project.getMetadata().getNamespace()).withName(addressSpaceName).get();
        Objects.requireNonNull(addressSpace, () -> String.format("Unable to find addressSpace: %s", addressSpaceName));
        assertNotNull(addressSpace);
        assertNotNull(addressSpace.getStatus());
        assertTrue(addressSpace.getStatus().isReady());
    }

    // the project is ready, so we need to check a few things

    assertNotNull(project.getStatus());
    assertNotNull(project.getStatus().getDownstreamEndpoint());
    assertThat(project.getStatus().getDownstreamEndpoint().getHost(), not(emptyOrNullString()));
    assertThat(project.getStatus().getDownstreamEndpoint().getUsername(), not(emptyOrNullString()));
    assertThat(project.getStatus().getDownstreamEndpoint().getPassword(), not(emptyOrNullString()));
    assertThat(project.getStatus().getDownstreamEndpoint().getPort(), not(is(0)));
}
 
Example 24
Source Project: kubernetes-plugin   Source File: PodTemplateUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
     * Combines a Pod with its parent.
     * @param parent        The parent Pod (nullable).
     * @param template      The child Pod
     */
    public static Pod combine(Pod parent, Pod template) {
        Preconditions.checkNotNull(template, "Pod template should not be null");
        if (parent == null) {
            return template;
        }

        LOGGER.finest(() -> "Combining pods, parent: " + Serialization.asYaml(parent) + " template: " + Serialization.asYaml(template));

        Map<String, String> nodeSelector = mergeMaps(parent.getSpec().getNodeSelector(),
                template.getSpec().getNodeSelector());
        String serviceAccount = Strings.isNullOrEmpty(template.getSpec().getServiceAccount())
                ? parent.getSpec().getServiceAccount()
                : template.getSpec().getServiceAccount();

        Boolean hostNetwork = template.getSpec().getHostNetwork() != null
                ? template.getSpec().getHostNetwork()
                : parent.getSpec().getHostNetwork();

        Map<String, String> podAnnotations = mergeMaps(parent.getMetadata().getAnnotations(),
                template.getMetadata().getAnnotations());
        Map<String, String> podLabels = mergeMaps(parent.getMetadata().getLabels(), template.getMetadata().getLabels());

        Set<LocalObjectReference> imagePullSecrets = new LinkedHashSet<>();
        imagePullSecrets.addAll(parent.getSpec().getImagePullSecrets());
        imagePullSecrets.addAll(template.getSpec().getImagePullSecrets());

        // Containers
        Map<String, Container> combinedContainers = new HashMap<>();
        Map<String, Container> parentContainers = parent.getSpec().getContainers().stream()
                .collect(toMap(c -> c.getName(), c -> c));
        combinedContainers.putAll(parentContainers);
        combinedContainers.putAll(template.getSpec().getContainers().stream()
                .collect(toMap(c -> c.getName(), c -> combine(parentContainers.get(c.getName()), c))));

        // Volumes
        List<Volume> combinedVolumes = combineVolumes(parent.getSpec().getVolumes(), template.getSpec().getVolumes());

        // Tolerations
        List<Toleration> combinedTolerations = Lists.newLinkedList();
        Optional.ofNullable(parent.getSpec().getTolerations()).ifPresent(combinedTolerations::addAll);
        Optional.ofNullable(template.getSpec().getTolerations()).ifPresent(combinedTolerations::addAll);

//        WorkspaceVolume workspaceVolume = template.isCustomWorkspaceVolumeEnabled() && template.getWorkspaceVolume() != null ? template.getWorkspaceVolume() : parent.getWorkspaceVolume();

        //Tool location node properties
//        List<ToolLocationNodeProperty> toolLocationNodeProperties = new ArrayList<>();
//        toolLocationNodeProperties.addAll(parent.getNodeProperties());
//        toolLocationNodeProperties.addAll(template.getNodeProperties());

        MetadataNested<PodBuilder> metadataBuilder = new PodBuilder(parent).withNewMetadataLike(parent.getMetadata()) //
                .withAnnotations(podAnnotations).withLabels(podLabels);
        if (!Strings.isNullOrEmpty(template.getMetadata().getName())) {
            metadataBuilder.withName(template.getMetadata().getName());
        }
        if (!Strings.isNullOrEmpty(template.getMetadata().getNamespace())) {
            metadataBuilder.withNamespace(template.getMetadata().getNamespace());
        }

        SpecNested<PodBuilder> specBuilder = metadataBuilder.endMetadata() //
                .withNewSpecLike(parent.getSpec()) //
                .withNodeSelector(nodeSelector) //
                .withServiceAccount(serviceAccount) //
                .withHostNetwork(hostNetwork) //
                .withContainers(Lists.newArrayList(combinedContainers.values())) //
                .withVolumes(combinedVolumes) //
                .withTolerations(combinedTolerations) //
                .withImagePullSecrets(Lists.newArrayList(imagePullSecrets));


        // Security context
        specBuilder.editOrNewSecurityContext()
                .withRunAsUser(
                        template.getSpec().getSecurityContext() != null && template.getSpec().getSecurityContext().getRunAsUser() != null ? template.getSpec().getSecurityContext().getRunAsUser() : (
                                parent.getSpec().getSecurityContext() != null && parent.getSpec().getSecurityContext().getRunAsUser() != null ? parent.getSpec().getSecurityContext().getRunAsUser() : null
                        )
                )
                .withRunAsGroup(
                        template.getSpec().getSecurityContext() != null && template.getSpec().getSecurityContext().getRunAsGroup() != null ? template.getSpec().getSecurityContext().getRunAsGroup() : (
                                parent.getSpec().getSecurityContext() != null && parent.getSpec().getSecurityContext().getRunAsGroup() != null ? parent.getSpec().getSecurityContext().getRunAsGroup() : null
                        )
                )
                .endSecurityContext();

        // podTemplate.setLabel(label);
//        podTemplate.setEnvVars(combineEnvVars(parent, template));
//        podTemplate.setWorkspaceVolume(workspaceVolume);
//        podTemplate.setNodeProperties(toolLocationNodeProperties);
//        podTemplate.setNodeUsageMode(nodeUsageMode);
//        podTemplate.setYaml(template.getYaml() == null ? parent.getYaml() : template.getYaml());

        Pod pod = specBuilder.endSpec().build();
        LOGGER.finest(() -> "Pods combined: " + Serialization.asYaml(pod));
        return pod;
    }
 
Example 25
Source Project: kubernetes-client   Source File: WatchEventsListener.java    License: Apache License 2.0 4 votes vote down vote up
public void sendWebSocketResponse(String object, String eventType) {
  WebSocketMessage message = toWebSocketMessage(context, new WatchEvent(Serialization.unmarshal(object, KubernetesResource.class), eventType));
  executor.schedule(() -> webSocketRef.get().send(message.getBody()), message.getDelay(), TimeUnit.SECONDS);
}
 
Example 26
public KubernetesCrudDispatcher(KubernetesCrudAttributesExtractor attributeExtractor, ResponseComposer responseComposer) {
  super(new Context(Serialization.jsonMapper()), attributeExtractor, responseComposer);
}
 
Example 27
Source Project: kubernetes-client   Source File: OperationSupport.java    License: Apache License 2.0 4 votes vote down vote up
protected static <T> T unmarshal(InputStream is) throws KubernetesClientException {
  return Serialization.unmarshal(is);
}
 
Example 28
Source Project: kubernetes-client   Source File: OperationSupport.java    License: Apache License 2.0 4 votes vote down vote up
protected static <T> T unmarshal(InputStream is, final Class<T> type) throws KubernetesClientException {
  return Serialization.unmarshal(is, type);
}
 
Example 29
Source Project: kubernetes-client   Source File: OperationSupport.java    License: Apache License 2.0 4 votes vote down vote up
protected static <T> T unmarshal(InputStream is, TypeReference<T> type) throws KubernetesClientException {
 return Serialization.unmarshal(is, type);
}
 
Example 30
public RawCustomResourceOperationsImpl(OkHttpClient client, Config config, CustomResourceDefinitionContext customResourceDefinition) {
  this.client = client;
  this.config = config;
  this.customResourceDefinition = customResourceDefinition;
  this.objectMapper = Serialization.jsonMapper();
}