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

The following examples show how to use io.fabric8.kubernetes.client.utils.Serialization. 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: OpenshiftAdapterSupport.java    From kubernetes-client with 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 #2
Source File: OpenshiftAdapterSupport.java    From kubernetes-client with 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 #3
Source File: WatchHTTPManager.java    From kubernetes-client with 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 #4
Source File: CustomTemplatePodTemplateProvider.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: CustomTemplatePodTemplateProvider.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
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 File: OperationSupport.java    From kubernetes-client with 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 #8
Source File: KubernetesTestUtil.java    From kubernetes-plugin with 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 #9
Source File: PodTemplateUtils.java    From kubernetes-plugin with 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 #10
Source File: KubernetesAttributesExtractor.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: AdmissionReviewTest.java    From kubernetes-client with 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 #12
Source File: KubernetesAttributesExtractor.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: AdmissionReviewTest.java    From kubernetes-client with 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 #14
Source File: IntegrationTestSupport.java    From java-operator-sdk with 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 #15
Source File: AdmissionReviewTest.java    From kubernetes-client with 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 #16
Source File: ConfigTest.java    From kubernetes-client with 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 #17
Source File: OpenShiftConfigTest.java    From kubernetes-client with 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 #18
Source File: WebServerController.java    From java-operator-sdk with 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 #19
Source File: AllContainersRunningPodWatcher.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #20
Source File: KubernetesSlave.java    From kubernetes-plugin with 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 #21
Source File: KubernetesEnvironmentProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
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 #22
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultKubernetesClient fromConfig(String config) {
  return new DefaultKubernetesClient(Serialization.unmarshal(config, Config.class));
}
 
Example #23
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultOpenShiftClient fromConfig(InputStream is) {
  return new DefaultOpenShiftClient(Serialization.unmarshal(is, OpenShiftConfig.class));
}
 
Example #24
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultOpenShiftClient fromConfig(String config) {
  return new DefaultOpenShiftClient(Serialization.unmarshal(config, OpenShiftConfig.class));
}
 
Example #25
Source File: CrdDeployer.java    From abstract-operator with 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 #26
Source File: ConfigMapLock.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public ConfigMapLock(String configMapNamespace, String configMapName, String identity) {
  this.configMapNamespace = Objects.requireNonNull(configMapNamespace, "configMapNamespace is required");
  this.configMapName = Objects.requireNonNull(configMapName, "configMapName is required");
  this.identity = Objects.requireNonNull(identity, "identity is required");
  objectMapper = Serialization.jsonMapper();
}
 
Example #27
Source File: KubeConfigUtils.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static Config parseConfigFromString(String contents) throws IOException {
  ObjectMapper mapper = Serialization.yamlMapper();
  return mapper.readValue(contents, Config.class);
}
 
Example #28
Source File: KubeConfigUtils.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static Config parseConfig(File file) throws IOException {
  ObjectMapper mapper = Serialization.yamlMapper();
  return mapper.readValue(file, Config.class);
}
 
Example #29
Source File: Config.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static boolean loadFromKubeconfig(Config config, String context, String kubeconfigContents, String kubeconfigPath) {
  try {
    io.fabric8.kubernetes.api.model.Config kubeConfig = KubeConfigUtils.parseConfigFromString(kubeconfigContents);
    config.setContexts(kubeConfig.getContexts());
    Context currentContext = setCurrentContext(context, config, kubeConfig);
    Cluster currentCluster = KubeConfigUtils.getCluster(kubeConfig, currentContext);
    if (currentContext != null) {
        config.setNamespace(currentContext.getNamespace());
    }
    if (currentCluster != null) {
      config.setMasterUrl(currentCluster.getServer());
      config.setTrustCerts(currentCluster.getInsecureSkipTlsVerify() != null && currentCluster.getInsecureSkipTlsVerify());
      config.setDisableHostnameVerification(currentCluster.getInsecureSkipTlsVerify() != null && currentCluster.getInsecureSkipTlsVerify());
      config.setCaCertData(currentCluster.getCertificateAuthorityData());
      AuthInfo currentAuthInfo = KubeConfigUtils.getUserAuthInfo(kubeConfig, currentContext);
      if (currentAuthInfo != null) {
        // rewrite tls asset paths if needed
        String caCertFile = currentCluster.getCertificateAuthority();
        String clientCertFile = currentAuthInfo.getClientCertificate();
        String clientKeyFile = currentAuthInfo.getClientKey();
        if (kubeconfigPath != null && !kubeconfigPath.isEmpty()) {
          caCertFile = absolutify(new File(kubeconfigPath), currentCluster.getCertificateAuthority());
          clientCertFile = absolutify(new File(kubeconfigPath), currentAuthInfo.getClientCertificate());
          clientKeyFile = absolutify(new File(kubeconfigPath), currentAuthInfo.getClientKey());
        }
        config.setCaCertFile(caCertFile);
        config.setClientCertFile(clientCertFile);
        config.setClientCertData(currentAuthInfo.getClientCertificateData());
        config.setClientKeyFile(clientKeyFile);
        config.setClientKeyData(currentAuthInfo.getClientKeyData());
        config.setOauthToken(currentAuthInfo.getToken());
        config.setUsername(currentAuthInfo.getUsername());
        config.setPassword(currentAuthInfo.getPassword());

        if (Utils.isNullOrEmpty(config.getOauthToken()) && currentAuthInfo.getAuthProvider() != null) {
          if (currentAuthInfo.getAuthProvider().getConfig() != null) {
            if (!Utils.isNullOrEmpty(currentAuthInfo.getAuthProvider().getConfig().get(ACCESS_TOKEN))) {
              // GKE token
              config.setOauthToken(currentAuthInfo.getAuthProvider().getConfig().get(ACCESS_TOKEN));
            } else if (!Utils.isNullOrEmpty(currentAuthInfo.getAuthProvider().getConfig().get(ID_TOKEN))) {
              // OpenID Connect token
              config.setOauthToken(currentAuthInfo.getAuthProvider().getConfig().get(ID_TOKEN));
            }
          }
        } else if (config.getOauthTokenProvider() == null) {  // https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins
          ExecConfig exec = currentAuthInfo.getExec();
          if (exec != null) {
            String apiVersion = exec.getApiVersion();
            if ("client.authentication.k8s.io/v1alpha1".equals(apiVersion) || "client.authentication.k8s.io/v1beta1".equals(apiVersion)) {
              List<String> argv = new ArrayList<String>();
              String command = exec.getCommand();
              if (command.contains("/") && !command.startsWith("/") && kubeconfigPath != null && !kubeconfigPath.isEmpty()) {
                // Appears to be a relative path; normalize. Spec is vague about how to detect this situation.
                command = Paths.get(kubeconfigPath).resolveSibling(command).normalize().toString();
              }
              argv.add(command);
              List<String> args = exec.getArgs();
              if (args != null) {
                argv.addAll(args);
              }
              ProcessBuilder pb = new ProcessBuilder(argv);
              List<ExecEnvVar> env = exec.getEnv();
              if (env != null) {
                Map<String, String> environment = pb.environment();
                env.forEach(var -> environment.put(var.getName(), var.getValue()));
              }
              // TODO check behavior of tty & stdin
              Process p = pb.start();
              if (p.waitFor() != 0) {
                LOGGER.warn(IOHelpers.readFully(p.getErrorStream()));
              }
              ExecCredential ec = Serialization.unmarshal(p.getInputStream(), ExecCredential.class);
              if (!apiVersion.equals(ec.apiVersion)) {
                LOGGER.warn("Wrong apiVersion {} vs. {}", ec.apiVersion, apiVersion);
              }
              if (ec.status != null && ec.status.token != null) {
                config.setOauthToken(ec.status.token);
              } else {
                LOGGER.warn("No token returned");
              }
            } else { // TODO v1beta1?
              LOGGER.warn("Unsupported apiVersion: {}", apiVersion);
            }
          }
        }

        config.getErrorMessages().put(401, "Unauthorized! Token may have expired! Please log-in again.");
        config.getErrorMessages().put(403, "Forbidden! User " + (currentContext != null? currentContext.getUser() : "") + " doesn't have permission.");
      }
      return true;
    }
  } catch (Exception e) {
    LOGGER.error("Failed to parse the kubeconfig.", e);
  }

  return false;
}
 
Example #30
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultKubernetesClient fromConfig(InputStream is) {
  return new DefaultKubernetesClient(Serialization.unmarshal(is, Config.class));
}