io.fabric8.kubernetes.client.KubernetesClient Java Examples

The following examples show how to use io.fabric8.kubernetes.client.KubernetesClient. 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: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
private void testEnvironmentVariables(KubernetesSchedulerProperties kubernetesSchedulerProperties,
		Map<String, String> schedulerProperties, EnvVar[] expectedVars) {
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
	ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, schedulerProperties,
			null, getCommandLineArgs(), randomName(), testApplication());

	CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
	CronJobSpec cronJobSpec = cronJob.getSpec();

	Container container = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec().getContainers().get(0);

	assertTrue("Environment variables should not be empty", !container.getEnv().isEmpty());

	assertThat(container.getEnv()).contains(expectedVars);

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example #2
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiDetectionOpenshift(VertxTestContext context) throws InterruptedException {
    List<String> apis = new ArrayList<>();
    apis.add("/apis/route.openshift.io/v1");
    apis.add("/apis/build.openshift.io/v1");
    apis.add("/apis/apps.openshift.io/v1");
    apis.add("/apis/image.openshift.io/v1");

    HttpServer mockHttp = startMockApi(context, apis);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat(pfa.hasRoutes(), is(true));
        assertThat(pfa.hasBuilds(), is(true));
        assertThat(pfa.hasImages(), is(true));
        assertThat(pfa.hasApps(), is(true));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example #3
Source File: KubernetesNamespace.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void delete(String namespaceName, KubernetesClient client)
    throws InfrastructureException {
  try {
    client.namespaces().withName(namespaceName).withPropagationPolicy("Background").delete();
  } catch (KubernetesClientException e) {
    if (e.getCode() == 404) {
      LOG.warn(
          format(
              "Tried to delete namespace '%s' but it doesn't exist in the cluster.",
              namespaceName),
          e);
    } else if (e.getCode() == 409) {
      LOG.info(format("The namespace '%s' is currently being deleted.", namespaceName), e);
    } else {
      throw new KubernetesInfrastructureException(e);
    }
  }
}
 
Example #4
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a StatefulSet with PropagationPolicy=Background")
void testDeleteStatefulSet() throws InterruptedException {
  // Given
  server.expect().delete().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/mystatefulset")
    .andReturn(HttpURLConnection.HTTP_OK, new StatefulSetBuilder().build())
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.apps().statefulSets().inNamespace("ns1").withName("mystatefulset").delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
 
Example #5
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static void deleteOpenShiftEntities(KubernetesClient kubernetes, String namespace, Set<HasMetadata> entities, String s2iBuildNameSuffix, KitLogger log) {
    // For OpenShift cluster, also delete s2i buildconfig
    OpenShiftClient openshiftClient = OpenshiftHelper.asOpenShiftClient(kubernetes);
    if (openshiftClient == null) {
        return;
    }
    for (HasMetadata entity : entities) {
        if ("ImageStream".equals(KubernetesHelper.getKind(entity))) {
            ImageName imageName = new ImageName(entity.getMetadata().getName());
            String buildName = getS2IBuildName(imageName, s2iBuildNameSuffix);
            log.info("Deleting resource BuildConfig %s/%s and Builds", namespace, buildName);
            openshiftClient.builds().inNamespace(namespace).withLabel("buildconfig", buildName).delete();
            openshiftClient.buildConfigs().inNamespace(namespace).withName(buildName).delete();
        }
    }
}
 
Example #6
Source File: PatchService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static EntityPatcher<PersistentVolumeClaim> pvcPatcher() {
    return (KubernetesClient client, String namespace, PersistentVolumeClaim newObj, PersistentVolumeClaim oldObj) -> {
        if (UserConfigurationCompare.configEqual(newObj, oldObj)) {
            return oldObj;
        }
        DoneablePersistentVolumeClaim entity =
            client.persistentVolumeClaims()
                  .inNamespace(namespace)
                  .withName(oldObj.getMetadata().getName())
                  .edit();

        if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) {
            entity.withMetadata(newObj.getMetadata());
        }

        if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) {
                entity.withSpec(newObj.getSpec());
        }
        return entity.done();
    };
}
 
Example #7
Source File: PodTemplateTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should list all PodTemplate resources in some namespace")
public void testList() {
  // Given
  server.expect().get().withPath("/api/v1/namespaces/test/podtemplates")
    .andReturn(200, new PodTemplateListBuilder().withItems(getPodTemplate()).build())
    .once();
  KubernetesClient client = server.getClient();

  // When
  PodTemplateList podTemplateList = client.v1().podTemplates().inNamespace("test").list();

  // Then
  assertNotNull(podTemplateList);
  assertEquals(1, podTemplateList.getItems().size());
  assertEquals("pt1", podTemplateList.getItems().get(0).getMetadata().getName());
  assertEquals(1, podTemplateList.getItems().get(0).getTemplate().getSpec().getContainers().size());
}
 
Example #8
Source File: KubernetesPlatformPropertiesTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void deserializationTest() {
	Map<String, KubernetesDeployerProperties> k8sAccounts = this.kubernetesPlatformProperties.getAccounts();
	KubernetesClient devK8sClient = KubernetesClientFactory.getKubernetesClient(k8sAccounts.get("dev"));
	KubernetesClient qaK8sClient = KubernetesClientFactory.getKubernetesClient(k8sAccounts.get("qa"));
	assertThat(k8sAccounts).hasSize(2);
	assertThat(k8sAccounts).containsKeys("dev", "qa");
	assertThat(devK8sClient.getNamespace()).isEqualTo("dev1");
	assertThat(devK8sClient.getMasterUrl().toString()).isEqualTo("https://192.168.0.1:8443");
	assertThat(qaK8sClient.getMasterUrl().toString()).isEqualTo("https://192.168.0.2:8443");
	assertThat(k8sAccounts.get("dev").getImagePullPolicy()).isEqualTo(ImagePullPolicy.Always);
	assertThat(k8sAccounts.get("dev").getEntryPointStyle()).isEqualTo(EntryPointStyle.exec);
	assertThat(k8sAccounts.get("dev").getLimits().getCpu()).isEqualTo("4");
	assertThat(k8sAccounts.get("qa").getImagePullPolicy()).isEqualTo(ImagePullPolicy.IfNotPresent);
	assertThat(k8sAccounts.get("qa").getEntryPointStyle()).isEqualTo(EntryPointStyle.boot);
	assertThat(k8sAccounts.get("qa").getLimits().getMemory()).isEqualTo("1024m");
}
 
Example #9
Source File: KubernetesClusterTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateKubernetesClusterObject() throws Exception {
    final KubernetesClient kubernetesClient = mock(KubernetesClient.class);

    NodeOperationsImpl nodes = mock(NodeOperationsImpl.class);
    PodOperationsImpl pods = mock(PodOperationsImpl.class);

    when(nodes.list()).thenReturn(new NodeList());
    when(kubernetesClient.nodes()).thenReturn(nodes);

    when(pods.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)).thenReturn(pods);
    when(pods.list()).thenReturn(new PodList());
    when(kubernetesClient.pods()).thenReturn(pods);

    final KubernetesCluster cluster = new KubernetesCluster(kubernetesClient);

    verify(kubernetesClient, times(1)).nodes();
    verify(kubernetesClient, times(1)).pods();
}
 
Example #10
Source File: KubernetesLauncher.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Log the last lines of containers logs
 */
private void logLastLines(@CheckForNull List<ContainerStatus> containers, String podId, String namespace, KubernetesSlave slave,
        Map<String, Integer> errors, KubernetesClient client) {
    if (containers != null) {
        for (ContainerStatus containerStatus : containers) {
            String containerName = containerStatus.getName();
            PrettyLoggable<String, LogWatch> tailingLines = client.pods().inNamespace(namespace).withName(podId)
                    .inContainer(containerStatus.getName()).tailingLines(30);
            String log = tailingLines.getLog();
            if (!StringUtils.isBlank(log)) {
                String msg = errors != null ? String.format(" exited with error %s", errors.get(containerName)) : "";
                LOGGER.log(Level.SEVERE, "Error in provisioning; agent={0}, template={1}. Container {2}{3}. Logs: {4}",
                        new Object[]{slave, slave.getTemplate(), containerName, msg, tailingLines.getLog()});
            }
        }
    }
}
 
Example #11
Source File: LoadTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceGetFromLoadWhenMultipleDocumentsWithDelimiter() throws Exception {
  // given
  KubernetesClient client = server.getClient();

  // when
  List<HasMetadata> result = client.load(getClass().getResourceAsStream("/multiple-document-template.yml")).get();

  // then
  assertNotNull(result);
  assertEquals(6, result.size());
  HasMetadata deploymentResource = result.get(1);
  assertEquals("apps/v1", deploymentResource.getApiVersion());
  assertEquals("Deployment", deploymentResource.getKind());
  assertEquals("redis-master", deploymentResource.getMetadata().getName());
}
 
Example #12
Source File: LeaseLock.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <C extends Namespaceable<C> & KubernetesClient> void create(
  C client, LeaderElectionRecord leaderElectionRecord) throws LockException {

  try {
    client.inNamespace(leaseNamespace).leases().withName(leaseName).createNew()
      .withNewMetadata().withNamespace(leaseNamespace).withName(leaseName).endMetadata()
      .withNewSpec()
      .withHolderIdentity(leaderElectionRecord.getHolderIdentity())
      .withLeaseDurationSeconds((int)leaderElectionRecord.getLeaseDuration().get(ChronoUnit.SECONDS))
      .withAcquireTime(leaderElectionRecord.getAcquireTime())
      .withRenewTime(leaderElectionRecord.getRenewTime())
      .withLeaseTransitions(leaderElectionRecord.getLeaderTransitions())
      .endSpec()
      .done();
  } catch (Exception e) {
    throw new LockException("Unable to create LeaseLock", e);
  }
}
 
Example #13
Source File: AbstractWatcher.java    From abstract-operator with Apache License 2.0 6 votes vote down vote up
protected AbstractWatcher(boolean isCrd, String namespace, String entityName, KubernetesClient client,
                          CustomResourceDefinition crd, Map<String, String> selector, BiConsumer<T, String> onAdd,
                          BiConsumer<T, String> onDelete, BiConsumer<T, String> onModify, Predicate<ConfigMap> isSupported,
                          Function<ConfigMap, T> convert, Function<InfoClass, T> convertCr) {
    this.isCrd = isCrd;
    this.namespace = namespace;
    this.entityName = entityName;
    this.client = client;
    this.crd = crd;
    this.selector = selector;
    this.onAdd = onAdd;
    this.onDelete = onDelete;
    this.onModify = onModify;
    this.isSupported = isSupported;
    this.convert = convert;
    this.convertCr = convertCr;
}
 
Example #14
Source File: PodDisruptionBudgetTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
  server.expect().withPath("/apis/policy/v1beta1/namespaces/test/poddisruptionbudgets/poddisruptionbudget1").andReturn(200, new PodDisruptionBudgetBuilder()
    .withNewMetadata().withName("poddisruptionbudget1").withNamespace("test").endMetadata()
    .withNewSpec()
    .withMaxUnavailable(new IntOrString("1%"))
    .withNewSelector()
    .withMatchLabels(Collections.singletonMap("app", "zookeeper"))
    .endSelector()
    .endSpec()
    .build()).once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.policy().podDisruptionBudget().withName("poddisruptionbudget1").delete();
  assertNotNull(deleted);
  assertTrue(deleted);
}
 
Example #15
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a ConfigMap with specified PropagationPolicy")
void testDeleteConfigMapWithExplicitPropagationPolicy() throws InterruptedException {
  // Given
  server.expect().delete().withPath("/api/v1/namespaces/ns1/configmaps/myconfigMap")
    .andReturn(HttpURLConnection.HTTP_OK, new ConfigMapBuilder().build())
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.configMaps().inNamespace("ns1").withName("myconfigMap").withPropagationPolicy(DeletionPropagation.FOREGROUND).delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.FOREGROUND.toString(), server.getLastRequest());
}
 
Example #16
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a resource with PropagationPolicy=Background")
void testDeleteResource() throws InterruptedException {
  // Given
  Pod testPod = new PodBuilder().withNewMetadata().withName("testpod").endMetadata().build();
  server.expect().delete().withPath("/api/v1/namespaces/foo/pods/testpod")
    .andReturn(HttpURLConnection.HTTP_OK, testPod)
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.resource(testPod).inNamespace("foo").delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
 
Example #17
Source File: SpringBootWatcher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void watch(List<ImageConfiguration> configs, Set<HasMetadata> resources, PlatformMode mode) throws Exception {
    KubernetesClient kubernetes = getContext().getJKubeServiceHub().getClient();

    PodLogService.PodLogServiceContext logContext = PodLogService.PodLogServiceContext.builder()
            .log(log)
            .newPodLog(getContext().getNewPodLogger())
            .oldPodLog(getContext().getOldPodLogger())
            .build();

    new PodLogService(logContext).tailAppPodsLogs(
        kubernetes,
        getContext().getJKubeServiceHub().getClusterAccess().getNamespace(),
        resources, false, null, true, null, false);

    String url = getServiceExposeUrl(kubernetes, resources);
    if (url == null) {
        url = getPortForwardUrl(resources);
    }

    if (url != null) {
        runRemoteSpringApplication(url);
    } else {
        throw new IllegalStateException("Unable to open a channel to the remote pod.");
    }
}
 
Example #18
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusThrowsWhenHttp422ResponseWithOtherField(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Kafka." + Constants.RESOURCE_GROUP_NAME + " \\\"my-cluster\\\" is invalid: apiVersion: Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"reason\":\"Invalid\",\"details\":{\"name\":\"my-cluster\",\"group\":\"" + Constants.RESOURCE_GROUP_NAME + "\",\"kind\":\"Kafka\",\"causes\":[{\"reason\":\"FieldValueInvalid\",\"message\":\"Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"field\":\"someOtherField\"}]},\"code\":422}");
    Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();
    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(KubernetesClientException.class));
            async.flag();
        })));

}
 
Example #19
Source File: KubernetesConfigurationPropertiesTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testFabric8Namespacing() {
	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();
	kubernetesDeployerProperties.getFabric8().setTrustCerts(true);
	kubernetesDeployerProperties.getFabric8().setMasterUrl("http://localhost:8090");
	// this can be set programatically in properties as well as an environment variable
	// (ie: CI, cmd line, etc) so ensure we have a clean slate here
	kubernetesDeployerProperties.setNamespace(null);
	kubernetesDeployerProperties.getFabric8().setNamespace("testing");

	KubernetesClient kubernetesClient = KubernetesClientFactory
			.getKubernetesClient(kubernetesDeployerProperties);

	assertEquals("http://localhost:8090", kubernetesClient.getMasterUrl().toString());
	assertEquals("testing", kubernetesClient.getNamespace());
	assertEquals("http://localhost:8090", kubernetesClient.getConfiguration().getMasterUrl());
	assertEquals(Boolean.TRUE, kubernetesClient.getConfiguration().isTrustCerts());
}
 
Example #20
Source File: IngressTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteMulti() {
  Ingress ingress1 = new IngressBuilder().withNewMetadata().withName("ingress1").withNamespace("test").and().build();
  Ingress ingress2 = new IngressBuilder().withNewMetadata().withName("ingress2").withNamespace("ns1").and().build();
  Ingress ingress3 = new IngressBuilder().withNewMetadata().withName("ingress3").withNamespace("any").and().build();

 server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/ingresses/ingress1").andReturn(200, ingress1).once();
 server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses/ingress2").andReturn(200, ingress2).once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.extensions().ingress().inAnyNamespace().delete(ingress1, ingress2);
  assertTrue(deleted);

  deleted = client.extensions().ingress().inAnyNamespace().delete(ingress3);
  assertFalse(deleted);
}
 
Example #21
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusWorksAfterUpgradeWithHttp422ResponseAboutApiVersionField(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Kafka." + Constants.RESOURCE_GROUP_NAME + " \\\"my-cluster\\\" is invalid: apiVersion: Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"reason\":\"Invalid\",\"details\":{\"name\":\"my-cluster\",\"group\":\"" + Constants.RESOURCE_GROUP_NAME + "\",\"kind\":\"Kafka\",\"causes\":[{\"reason\":\"FieldValueInvalid\",\"message\":\"Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"field\":\"apiVersion\"}]},\"code\":422}");
    Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();
    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.succeeding(kafka -> async.flag()));

}
 
Example #22
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteMulti() {
  Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
  Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
  Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();

 server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, pod1).once();
 server.expect().withPath("/api/v1/namespaces/ns1/pods/pod2").andReturn(200, pod2).once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.pods().inAnyNamespace().delete(pod1, pod2);
  assertTrue(deleted);

  deleted = client.pods().inAnyNamespace().delete(pod3);
  assertFalse(deleted);
}
 
Example #23
Source File: PodPriorityExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws InterruptedException {
  String master = "https://192.168.99.100:8443/";
  if (args.length == 1) {
    master = args[0];
  }

  log("Using master with url ", master);
  Config config = new ConfigBuilder().withMasterUrl(master).build();
  try (final KubernetesClient client = new DefaultKubernetesClient(config)) {
    PriorityClass priorityClass = new PriorityClassBuilder()
      .withNewMetadata().withName("high-priority").endMetadata()
      .withValue(new Integer(100000))
      .withGlobalDefault(false)
      .withDescription("This priority class should be used for XYZ service pods only.")
      .build();
    client.scheduling().priorityClass().create(priorityClass);

    client.pods().inNamespace("default").create(new PodBuilder()
      .withNewMetadata().withName("nginx").withLabels(Collections.singletonMap("env", "test")).endMetadata()
      .withNewSpec()
      .addToContainers(new ContainerBuilder().withName("nginx").withImage("nginx").withImagePullPolicy("IfNotPresent").build())
      .withPriorityClassName("high-priority")
      .endSpec()
      .build()
    );
  } catch (KubernetesClientException e) {
    e.printStackTrace();
    log("Could not create resource", e.getMessage());
  }
}
 
Example #24
Source File: SecretsPropertySource.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
private static String getSourceName(KubernetesClient client, Environment env, SecretsConfigProperties config) {
    return new StringBuilder()
        .append(PREFIX)
        .append(Constants.PROPERTY_SOURCE_NAME_SEPARATOR)
        .append(getApplicationName(env,config))
        .append(Constants.PROPERTY_SOURCE_NAME_SEPARATOR)
        .append(getApplicationNamespace(client, env, config))
        .toString();
}
 
Example #25
Source File: PodDisruptionBudgetTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testListWithLabels() {
  server.expect().withPath("/apis/policy/v1beta1/namespaces/test/poddisruptionbudgets?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new PodDisruptionBudgetListBuilder().build()).always();
  server.expect().withPath("/apis/policy/v1beta1/namespaces/test/poddisruptionbudgets?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new PodDisruptionBudgetListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  PodDisruptionBudgetList podDisruptionBudgetList = client.policy().podDisruptionBudget()
    .withLabel("key1", "value1")
    .withLabel("key2", "value2")
    .withLabel("key3", "value3")
    .list();


  assertNotNull(podDisruptionBudgetList);
  assertEquals(0, podDisruptionBudgetList.getItems().size());

  podDisruptionBudgetList = client.policy().podDisruptionBudget()
    .withLabel("key1", "value1")
    .withLabel("key2", "value2")
    .list();

  assertNotNull(podDisruptionBudgetList);
  assertEquals(3, podDisruptionBudgetList.getItems().size());
}
 
Example #26
Source File: PodTemplateTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Should be able to delete a PodTemplate")
public void testDelete() {
  // Given
  server.expect().delete().withPath("/api/v1/namespaces/test/podtemplates/pt1")
    .andReturn(200, getPodTemplate())
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.v1().podTemplates().inNamespace("test").withName("pt1").delete();

  // Then
  assertTrue(isDeleted);
}
 
Example #27
Source File: K8sNetworkPolicyWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processConfigUpdating() {
    if (!isRelevantHelper()) {
        return;
    }

    KubernetesClient client = k8sClient(k8sApiConfigService);

    if (client != null) {
        client.network().networkPolicies().inAnyNamespace().watch(
                internalK8sNetworkPolicyWatcher);
    }
}
 
Example #28
Source File: AbstractPodCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    KubernetesClient kubernetes = getKubernetes();

    String podIdText = podId.getValue();
    Pod podInfo = getKubernetes().pods().inNamespace(getNamespace()).withName(podIdText).get();
    if (podInfo == null) {
        System.out.println("No pod for id: " + podIdText);
    } else {
        executePod(podInfo, podIdText);
    }
    return null;
}
 
Example #29
Source File: NetworkingV1beta1IngressTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithNamespaceMismatch() {
  Assertions.assertThrows(KubernetesClientException.class, () -> {
    Ingress ingress1 = new IngressBuilder().withNewMetadata().withName("ingress1").withNamespace("test").and().build();
    Ingress ingress2 = new IngressBuilder().withNewMetadata().withName("ingress2").withNamespace("ns1").and().build();
    KubernetesClient client = server.getClient();

    Boolean deleted = client.network().ingress().inNamespace("test1").delete(ingress1);
    assertTrue(deleted);
  });
}
 
Example #30
Source File: KeyValueV2Test.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public KubernetesClient client() {
    KubernetesClient kubernetesClient = new DefaultKubernetesClient();
    TestHelper.createCrd(kubernetesClient);

    return kubernetesClient;
}