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

The following examples show how to use io.fabric8.kubernetes.client.utils.Utils. 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: OperationContext.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public OperationContext(OkHttpClient client, Config config, String plural, String namespace, String name, String apiGroupName, String apiGroupVersion, boolean cascading, Object item, Map<String, String> labels, Map<String, String[]> labelsNot, Map<String, String[]> labelsIn, Map<String, String[]> labelsNotIn, Map<String, String> fields, Map<String, String[]> fieldsNot, String resourceVersion, boolean reloadingFromServer, long gracePeriodSeconds, DeletionPropagation propagationPolicy, long watchRetryInitialBackoffMillis, double watchRetryBackoffMultiplier) {
  this.client = client;
  this.config = config;
  this.plural = plural;
  this.namespace = Utils.isNotNullOrEmpty(namespace) ? namespace : (config != null ? config.getNamespace() : null);
  this.name = name;
  this.cascading = cascading;
  this.labels = labels != null ? labels : new HashMap<>();
  this.labelsNot = labelsNot != null ? labelsNot : new HashMap<>();
  this.labelsIn = labelsIn != null ? labelsIn : new HashMap<>();
  this.labelsNotIn = labelsNotIn != null ? labelsNotIn : new HashMap<>();
  this.fields = fields != null ? fields : new HashMap<>();
  this.fieldsNot = fieldsNot != null ? fieldsNot : new HashMap<>();
  this.resourceVersion = resourceVersion;
  this.reloadingFromServer = reloadingFromServer;
  this.gracePeriodSeconds = gracePeriodSeconds;
  this.propagationPolicy = propagationPolicy;
  this.watchRetryInitialBackoffMillis = watchRetryInitialBackoffMillis;
  this.watchRetryBackoffMultiplier = watchRetryBackoffMultiplier;
  this.item = item;
  this.apiGroupName =  ApiVersionUtil.apiGroup(item, apiGroupName);
  this.apiGroupVersion = ApiVersionUtil.apiVersion(item, apiGroupVersion);
}
 
Example #2
Source File: V2beta2HorizontalPodAutoscalerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLabels() {
  server.expect().withPath("/apis/autoscaling/v2beta2/namespaces/test/horizontalpodautoscalers?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new HorizontalPodAutoscalerListBuilder().build()).once();
  server.expect().withPath("/apis/autoscaling/v2beta2/namespaces/ns1/horizontalpodautoscalers?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new HorizontalPodAutoscalerListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  HorizontalPodAutoscalerList horizontalPodAutoscalerList = client.autoscaling().v2beta2().horizontalPodAutoscalers()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();
  assertNotNull(horizontalPodAutoscalerList);
  assertEquals(0, horizontalPodAutoscalerList.getItems().size());

  horizontalPodAutoscalerList = client.autoscaling().v2beta2().horizontalPodAutoscalers().inNamespace("ns1")
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();
  assertNotNull(horizontalPodAutoscalerList);
  assertEquals(3, horizontalPodAutoscalerList.getItems().size());
}
 
Example #3
Source File: Config.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static boolean tryNamespaceFromPath(Config config) {
  LOGGER.debug("Trying to configure client namespace from Kubernetes service account namespace path...");
  if (Utils.getSystemPropertyOrEnvVar(KUBERNETES_TRYNAMESPACE_PATH_SYSTEM_PROPERTY, true)) {
    String serviceAccountNamespace = Utils.getSystemPropertyOrEnvVar(KUBERNETES_NAMESPACE_FILE, KUBERNETES_NAMESPACE_PATH);
    boolean serviceAccountNamespaceExists = Files.isRegularFile(new File(serviceAccountNamespace).toPath());
    if (serviceAccountNamespaceExists) {
      LOGGER.debug("Found service account namespace at: [" + serviceAccountNamespace + "].");
      try {
        String namespace = new String(Files.readAllBytes(new File(serviceAccountNamespace).toPath()));
        config.setNamespace(namespace.replace(System.lineSeparator(), ""));
        return true;
      } catch (IOException e) {
        LOGGER.error("Error reading service account namespace from: [" + serviceAccountNamespace + "].", e);
      }
    } else {
      LOGGER.debug("Did not find service account namespace at: [" + serviceAccountNamespace + "]. Ignoring.");
    }
  }
  return false;
}
 
Example #4
Source File: Config.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static boolean tryKubeConfig(Config config, String context) {
  LOGGER.debug("Trying to configure client from Kubernetes config...");
  if (!Utils.getSystemPropertyOrEnvVar(KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, true)) {
    return false;
  }
  File kubeConfigFile = new File(getKubeconfigFilename());
  if (!kubeConfigFile.isFile()) {
    LOGGER.debug("Did not find Kubernetes config at: [{}]. Ignoring.", kubeConfigFile.getPath());
    return false;
  }
  LOGGER.debug("Found for Kubernetes config at: [{}].", kubeConfigFile.getPath());
  String kubeconfigContents = getKubeconfigContents(kubeConfigFile);
  if (kubeconfigContents == null) {
    return false;
  }
  loadFromKubeconfig(config, context, kubeconfigContents, kubeConfigFile.getPath());
  return true;
}
 
Example #5
Source File: Config.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static String getKeyAlgorithm(String clientKeyFile, String clientKeyData) {
  // Check if any system property is set
  if(Utils.getSystemPropertyOrEnvVar(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY) != null) {
    return Utils.getSystemPropertyOrEnvVar(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY);
  }

  // Detect algorithm
  try {
    InputStream keyInputStream = CertUtils.getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
    if(keyInputStream != null) {
      return getKeyAlgorithm(keyInputStream);
    }
  } catch(IOException exception) {
    LOGGER.debug("Failure in determining private key algorithm type, defaulting to RSA ", exception.getMessage());
  }
  return null;
}
 
Example #6
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    Collection<? extends Certificate> certificates = certFactory.generateCertificates(certInputStream);
    PrivateKey privateKey = loadKey(keyInputStream, clientKeyAlgo);

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (Utils.isNotNullOrEmpty(keyStoreFile)){
      keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
      loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = certificates.stream().map(cert->((X509Certificate)cert).getIssuerX500Principal().getName()).collect(Collectors.joining("_"));
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, certificates.toArray(new Certificate[0]));

    return keyStore;
}
 
Example #7
Source File: BaseClient.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public BaseClient(final OkHttpClient httpClient, Config config) throws KubernetesClientException {
  try {
    this.httpClient = httpClient;
    this.namespace = config.getNamespace();
    this.configuration = config;
    this.apiVersion = config.getApiVersion();
    if (config.getMasterUrl() == null) {
      throw new KubernetesClientException("Unknown Kubernetes master URL - " +
        "please set with the builder, or set with either system property \"" + Config.KUBERNETES_MASTER_SYSTEM_PROPERTY + "\"" +
        " or environment variable \"" + Utils.convertSystemPropertyNameToEnvVar(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY) + "\"");
    }
    this.masterUrl = new URL(config.getMasterUrl());
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #8
Source File: BaseClient.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
  ConnectionPool connectionPool = httpClient.connectionPool();
  Dispatcher dispatcher = httpClient.dispatcher();
  ExecutorService executorService = httpClient.dispatcher() != null ? httpClient.dispatcher().executorService() : null;

  if (dispatcher != null) {
    dispatcher.cancelAll();
  }

  if (connectionPool != null) {
    connectionPool.evictAll();
  }

  Utils.shutdownExecutorService(executorService);
}
 
Example #9
Source File: KubernetesDiscoveryClient.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceInstance getLocalServiceInstance() {
    String serviceName = properties.getServiceName();
    String podName = System.getenv(HOSTNAME);
    ServiceInstance defaultInstance = new DefaultServiceInstance(serviceName, "localhost", 8080, false);

    Endpoints endpoints = client.endpoints().withName(serviceName).get();
    if (Utils.isNullOrEmpty(podName) || endpoints == null) {
        return defaultInstance;
    }
    try {
        return endpoints.getSubsets()
                .stream()
                .filter(s -> s.getAddresses().get(0).getTargetRef().getName().equals(podName))
                .map(s -> (ServiceInstance) new KubernetesServiceInstance(serviceName,
                        s.getAddresses().stream().findFirst().orElseThrow(IllegalStateException::new),
                        s.getPorts().stream().findFirst().orElseThrow(IllegalStateException::new),
                        false))
                .findFirst().orElse(defaultInstance);
    } catch (Throwable t) {
        return defaultInstance;
    }
}
 
Example #10
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isStatefulSetReady(StatefulSet ss) {
  Utils.checkNotNull(ss, "StatefulSet can't be null.");
  StatefulSetSpec spec = ss.getSpec();
  StatefulSetStatus status = ss.getStatus();

  if (status == null || status.getReplicas() == null || status.getReadyReplicas() == null) {
    return false;
  }

  //Can be true in testing, so handle it to make test writing easier.
  if (spec == null || spec.getReplicas() == null) {
    return false;
  }

  return spec.getReplicas().intValue() == status.getReplicas()
    && spec.getReplicas().intValue() == status.getReadyReplicas();
}
 
Example #11
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isDeploymentConfigReady(DeploymentConfig d) {
  Utils.checkNotNull(d, "Deployment can't be null.");
  DeploymentConfigSpec spec = d.getSpec();
  DeploymentConfigStatus status = d.getStatus();

  if (status == null || status.getReplicas() == null || status.getAvailableReplicas() == null) {
    return false;
  }

  //Can be true in testing, so handle it to make test writing easier.
  if (spec == null || spec.getReplicas() == null) {
    return false;
  }

  return spec.getReplicas().intValue() == status.getReplicas() &&
    spec.getReplicas().intValue() <= status.getAvailableReplicas();
}
 
Example #12
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isReplicationControllerReady(ReplicationController r) {
  Utils.checkNotNull(r, "ReplicationController can't be null.");
  ReplicationControllerSpec spec = r.getSpec();
  ReplicationControllerStatus status = r.getStatus();

  if (status == null || status.getReadyReplicas() == null) {
    return false;
  }

  //Can be true in testing, so handle it to make test writing easier.
  if (spec == null || spec.getReplicas() == null) {
    return false;
  }

  return spec.getReplicas().intValue() == status.getReadyReplicas();
}
 
Example #13
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isEndpointsReady(Endpoints e) {
  Utils.checkNotNull(e, "Endpoints can't be null.");
  String name = e.getMetadata().getName();
  Utils.checkNotNull(name, "Endpoints name can't be null.");

  if (e.getSubsets() == null) {
    return false;
  }

  for (EndpointSubset subset : e.getSubsets()) {
    if(!subset.getAddresses().isEmpty() && !subset.getPorts().isEmpty()) {
      return true;
    }
  }
  return false;
}
 
Example #14
Source File: KubernetesAttributesExtractor.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
protected AttributeSet extractMetadataAttributes(HasMetadata hasMetadata) {
    AttributeSet metadataAttributes = new AttributeSet();
    if (!Utils.isNullOrEmpty(hasMetadata.getMetadata().getName())) {
      metadataAttributes = metadataAttributes.add(new Attribute(NAME, hasMetadata.getMetadata().getName()));
    }

    if (!Utils.isNullOrEmpty(hasMetadata.getMetadata().getNamespace())) {
        metadataAttributes = metadataAttributes.add(new Attribute(NAMESPACE, hasMetadata.getMetadata().getNamespace()));
    }

  if (hasMetadata.getMetadata().getLabels() != null) {
    for (Map.Entry<String, String> label : hasMetadata.getMetadata().getLabels().entrySet()) {
      metadataAttributes = metadataAttributes.add(new Attribute(LABEL_KEY_PREFIX + label.getKey(), label.getValue()));
    }
  }
  return metadataAttributes;
}
 
Example #15
Source File: V1HorizontalPodAutoscalerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLabels() {
  server.expect().withPath("/apis/autoscaling/v1/namespaces/test/horizontalpodautoscalers?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new HorizontalPodAutoscalerListBuilder().build()).once();
  server.expect().withPath("/apis/autoscaling/v1/namespaces/ns1/horizontalpodautoscalers?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new HorizontalPodAutoscalerListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  HorizontalPodAutoscalerList horizontalPodAutoscalerList = client.autoscaling().v1().horizontalPodAutoscalers()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();
  assertNotNull(horizontalPodAutoscalerList);
  assertEquals(0, horizontalPodAutoscalerList.getItems().size());

  horizontalPodAutoscalerList = client.autoscaling().v1().horizontalPodAutoscalers().inNamespace("ns1")
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();
  assertNotNull(horizontalPodAutoscalerList);
  assertEquals(3, horizontalPodAutoscalerList.getItems().size());
}
 
Example #16
Source File: MetricsTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testNodeMetricWithLabels() {
  // Given
  server.expect().get().withPath("/apis/metrics.k8s.io/v1beta1/nodes?labelSelector=" + Utils.toUrlEncoded("ss=true,cs=true"))
    .andReturn(200, new NodeMetricsListBuilder().withItems(getNodeMetric()).build()).once();

  KubernetesClient client = server.getClient();
  Map<String,Object> lablesMap = new HashMap();
  lablesMap.put("ss", "true");
  lablesMap.put("cs", "true");

  // When
  NodeMetricsList nodeMetricList = client.top().nodes().metrics(lablesMap);

  // Then
  assertEquals(1, nodeMetricList.getItems().size());
}
 
Example #17
Source File: V2beta1HorizontalPodAutoscalerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLabels() {
  server.expect().withPath("/apis/autoscaling/v2beta1/namespaces/test/horizontalpodautoscalers?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new HorizontalPodAutoscalerListBuilder().build()).once();
  server.expect().withPath("/apis/autoscaling/v2beta1/namespaces/ns1/horizontalpodautoscalers?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new HorizontalPodAutoscalerListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  HorizontalPodAutoscalerList horizontalPodAutoscalerList = client.autoscaling().v2beta1().horizontalPodAutoscalers()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();
  assertNotNull(horizontalPodAutoscalerList);
  assertEquals(0, horizontalPodAutoscalerList.getItems().size());

  horizontalPodAutoscalerList = client.autoscaling().v2beta1().horizontalPodAutoscalers().inNamespace("ns1")
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();
  assertNotNull(horizontalPodAutoscalerList);
  assertEquals(3, horizontalPodAutoscalerList.getItems().size());
}
 
Example #18
Source File: EndpointsTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLabels() {
  server.expect().withPath("/api/v1/namespaces/test/endpoints?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new EndpointsListBuilder().build()).once();
  server.expect().withPath("/api/v1/namespaces/ns1/endpoints?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new EndpointsListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  EndpointsList endpointsList = client.endpoints()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();
  assertNotNull(endpointsList);
  assertEquals(0, endpointsList.getItems().size());

  endpointsList = client.endpoints().inNamespace("ns1")
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();
  assertNotNull(endpointsList);
  assertEquals(2, endpointsList.getItems().size());
}
 
Example #19
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithFields() {
 server.expect().withPath("/api/v1/namespaces/test/pods?fieldSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3!=value3,key3!=value4")).andReturn(200, new PodListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  PodList podList = client.pods()
    .withField("key1", "value1")
    .withField("key2","value2")
    .withoutField("key3","value3")
    .withoutField("key3", "value4")
    .list();


  assertNotNull(podList);
  assertEquals(2, podList.getItems().size());
}
 
Example #20
Source File: RawCustomResourceOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> makeCall(String url, String body, HttpCallMethod callMethod) {
  Request request = (body == null) ? getRequest(url, callMethod) : getRequest(url, body, callMethod);
  try (Response response = client.newCall(request).execute()) {
    if (response.isSuccessful()) {
      String respBody = response.body().string();
      if(Utils.isNullOrEmpty(respBody))
        return new HashMap<>();
      else
        return objectMapper.readValue(respBody, HashMap.class);
    } else {
      throw requestFailure(request, createStatus(response));
    }
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #21
Source File: PriorityClassTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLables() {
  server.expect().withPath("/apis/scheduling.k8s.io/v1beta1/priorityclasses?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new PriorityClassListBuilder().build()).always();
  server.expect().withPath("/apis/scheduling.k8s.io/v1beta1/priorityclasses?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new PriorityClassListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();

  PriorityClassList priorityClassList = client.scheduling().priorityClass()
    .withLabel("key1", "value1")
    .withLabel("key2", "value2")
    .list();
  assertEquals(3, priorityClassList.getItems().size());

  priorityClassList = client.scheduling().priorityClass()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();
  assertEquals(0, priorityClassList.getItems().size());
}
 
Example #22
Source File: NamespaceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLables() {
  server.expect().withPath("/api/v1/namespaces?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new NamespaceListBuilder().build()).always();
  server.expect().withPath("/api/v1/namespaces?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new NamespaceListBuilder().addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();

  NamespaceList namespaceList = client.namespaces()
    .withLabel("key1", "value1")
    .withLabel("key2", "value2")
    .list();
  assertEquals(3, namespaceList.getItems().size());

  namespaceList = client.namespaces()
    .withLabel("key1", "value1")
    .withLabel("key2", "value2")
    .withLabel("key3", "value3")
    .list();
  assertEquals(0, namespaceList.getItems().size());
}
 
Example #23
Source File: PersistentVolumeClaimTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testListWithlabels() {
  server.expect().withPath("/api/v1/namespaces/test/persistentvolumeclaims?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new PersistentVolumeClaimListBuilder().build()).once();

  server.expect().withPath("/api/v1/namespaces/test/persistentvolumeclaims?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new PersistentVolumeClaimListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  PersistentVolumeClaimList persistentVolumeClaimList = client.persistentVolumeClaims().inNamespace("test")
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();
  assertNotNull(persistentVolumeClaimList);
  assertEquals(0, persistentVolumeClaimList.getItems().size());

  persistentVolumeClaimList = client.persistentVolumeClaims().inNamespace("test")
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();
  assertNotNull(persistentVolumeClaimList);
  assertEquals(3, persistentVolumeClaimList.getItems().size());
}
 
Example #24
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static KeyStore createTrustStore(InputStream pemInputStream, String trustStoreFile, char[] trustStorePassphrase) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
  KeyStore trustStore = KeyStore.getInstance("JKS");

  if (Utils.isNotNullOrEmpty(trustStoreFile)) {
    trustStore.load(new FileInputStream(trustStoreFile), trustStorePassphrase);
  } else {
    loadDefaultTrustStoreFile(trustStore, trustStorePassphrase);
  }

  while (pemInputStream.available() > 0) {
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);
    String alias = cert.getSubjectX500Principal().getName() + "_" + cert.getSerialNumber().toString(16);
    trustStore.setCertificateEntry(alias, cert);
  }
  return trustStore;
}
 
Example #25
Source File: UtilsTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("interpolateString, String with mixed placeholders and parameters, should return interpolated input")
void interpolateStringWithParametersTest() {
  // Given
  final String input = "This is a \"${SINGLE_CURLY_BRACE}\" and the following is code ${NOT_REPLACED}: \"${{RENDER_UNQUOTED}}\" ${{ALREADY_UNQUOTED}}";
  final Map<String, String> parameters = new HashMap<>();
  parameters.put("SINGLE_CURLY_BRACE", "template string");
  parameters.put("RENDER_UNQUOTED", "'1' === '1';");
  parameters.put("ALREADY_UNQUOTED", "/* END */");
  parameters.put("NOT_THERE", "/* END */");
  parameters.put(null, "NULL key is ignored");
  parameters.put("NULL_VALUE", null);
  // When
  final String result = Utils.interpolateString(input, parameters);
  // Then
  assertEquals("This is a \"template string\" and the following is code ${NOT_REPLACED}: '1' === '1'; /* END */", result);
}
 
Example #26
Source File: PersistentVolumeTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithLables() {
  server.expect().withPath("/api/v1/persistentvolumes?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new PersistentVolumeListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  PersistentVolumeList persistentVolumeList = client.persistentVolumes()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();

  assertNotNull(persistentVolumeList);
  assertEquals(3, persistentVolumeList.getItems().size());
}
 
Example #27
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
protected <T> String checkNamespace(T item) {
  String operationNs = getNamespace();
  String itemNs = (item instanceof HasMetadata && ((HasMetadata)item).getMetadata() != null) ? ((HasMetadata) item).getMetadata().getNamespace() : null;
  if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) {
    if (!isResourceNamespaced()) {
      return null;
    } else {
      throw new KubernetesClientException("Namespace not specified. But operation requires namespace.");
    }
  } else if (Utils.isNullOrEmpty(itemNs)) {
    return operationNs;
  } else if (Utils.isNullOrEmpty(operationNs)) {
    return itemNs;
  } else if (itemNs.equals(operationNs)) {
    return itemNs;
  }
  throw new KubernetesClientException("Namespace mismatch. Item namespace:" + itemNs + ". Operation namespace:" + operationNs + ".");
}
 
Example #28
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public T createOrReplace(T... items) {
  T item = getItem();
  if (items.length > 1) {
    throw new IllegalArgumentException("Too many items to create.");
  } else if (items.length == 1) {
    item = items[0];
  }

  if (item == null) {
    throw new IllegalArgumentException("Nothing to create.");
  }

  if (Utils.isNullOrEmpty(name) && item instanceof HasMetadata) {
    return withName(((HasMetadata)item).getMetadata().getName()).createOrReplace(item);
  }
  if (fromServer().get() == null) {
    return create(item);
  } else {
    return replace(item);
  }
}
 
Example #29
Source File: LoadExample.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static String display(HasMetadata item) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    if (Utils.isNotNullOrEmpty(item.getKind())) {
        sb.append("Kind:").append(item.getKind());
    }
    if (Utils.isNotNullOrEmpty(item.getMetadata().getName())) {
        sb.append("Name:").append(item.getMetadata().getName());
    }

    if (item.getMetadata().getLabels()!=null && !item.getMetadata().getLabels().isEmpty()) {
        sb.append("Labels: [ ");
        for (Map.Entry<String,String> entry : item.getMetadata().getLabels().entrySet()) {
            sb.append(entry.getKey()).append(":").append(entry.getValue()).append(" ");
        }
        sb.append("]");
    }
    sb.append(" ]");
    return sb.toString();

}
 
Example #30
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected <T> String checkName(T item) {
  String operationName = getName();
  String itemName = item instanceof HasMetadata ? ((HasMetadata) item).getMetadata().getName() : null;
  if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) {
    return null;
  } else if (Utils.isNullOrEmpty(itemName)) {
    return operationName;
  } else if (Utils.isNullOrEmpty(operationName)) {
    return itemName;
  } else if (itemName.equals(operationName)) {
    return itemName;
  }
  throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + ".");
}