io.fabric8.kubernetes.client.KubernetesClientException Java Examples

The following examples show how to use io.fabric8.kubernetes.client.KubernetesClientException. 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: DeleteExamples.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  String master = "https://localhost:8443/";
  if (args.length == 1) {
    master = args[0];
  }

  Config config = new ConfigBuilder().withMasterUrl(master).build();
  KubernetesClient client = new DefaultKubernetesClient(config);
  try {
    log("Create namespace:", client.namespaces().create(new NamespaceBuilder().withNewMetadata().withName("thisisatest").endMetadata().build()));
    log("Deleted namespace:", client.namespaces().withName("test").delete());
    log("Deleted testPod:", client.pods().inNamespace("thisisatest").withName("testpod").delete());
    log("Deleted pod by label:", client.pods().withLabel("this", "works").delete());
  } catch (KubernetesClientException e) {
    logger.error(e.getMessage(), e);
  } finally {
    client.namespaces().withName("thisisatest").delete();
    client.close();
  }
}
 
Example #2
Source File: AddressUtils.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public static void waitForAddressDeleted(Address address, TimeoutBudget timeoutBudget) throws Exception {
    Kubernetes kubernetes = Kubernetes.getInstance();

    TestUtils.waitUntilCondition(address + " match", phase -> {
        try {
            AddressList addressList = kubernetes.getAddressClient().inNamespace(address.getMetadata().getNamespace()).list();
            List<Address> addressesInSameAddrSpace = addressList.getItems().stream()
                    .filter(address1 -> Address.extractAddressSpace(address1)
                            .equals(Address.extractAddressSpace(address))).collect(Collectors.toList());
            return !addressesInSameAddrSpace.contains(address);
        } catch (KubernetesClientException e) {
            log.warn("Client can't read address resources");
            return false;
        }
    }, timeoutBudget);
}
 
Example #3
Source File: OpenShiftProjectFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = InfrastructureException.class,
    expectedExceptionsMessageRegExp =
        "Error while trying to fetch the project 'che-default'. Cause: connection refused")
public void shouldThrowExceptionWhenFailedToGetInfoAboutDefaultNamespace() throws Exception {
  throwOnTryToGetProjectByName(
      "che-default", new KubernetesClientException("connection refused"));

  projectFactory =
      new OpenShiftProjectFactory(
          "predefined",
          "",
          "",
          "che-default",
          false,
          clientFactory,
          configFactory,
          stopWorkspaceRoleProvisioner,
          userManager,
          pool,
          NO_OAUTH_IDENTITY_PROVIDER);

  projectFactory.list();
}
 
Example #4
Source File: ListBuildConfigs.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  try {
    OpenShiftClient client = new DefaultOpenShiftClient();
    if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.BUILD)) {
      System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.BUILD);
      return;
    }
    BuildConfigList list = client.buildConfigs().list();
    if (list == null) {
      System.out.println("ERROR no list returned!");
      return;
    }
    List<BuildConfig> items = list.getItems();
    for (BuildConfig item : items) {
      System.out.println("BuildConfig " + item.getMetadata().getName() + " has version: " + item.getApiVersion());
    }
  } catch (KubernetesClientException e) {
    System.out.println("Failed: " + e);
    e.printStackTrace();
  }
}
 
Example #5
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 #6
Source File: WatchConnectionManager.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
  logger.debug("Force closing the watch {}", this);
  closeEvent(null);
  closeWebSocket(webSocketRef.getAndSet(null));
  if (!executor.isShutdown()) {
    try {
      executor.shutdown();
      if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
        logger.warn("Executor didn't terminate in time after shutdown in close(), killing it in: {}", this);
        executor.shutdownNow();
      }
    } catch (Throwable t) {
      throw KubernetesClientException.launderThrowable(t);
    }
  }
}
 
Example #7
Source File: ClusterOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public VersionInfo fetchVersion() {
  try {
    Response response = handleVersionGet(versionEndpoint);
    // Handle Openshift 4 version case
    if (HttpURLConnection.HTTP_NOT_FOUND == response.code() && versionEndpoint.equals(OPENSHIFT_VERSION_ENDPOINT)) {
      response.close();
      return fetchOpenshift4Version();
    }

    Map<String, String> myMap = objectMapper.readValue(response.body().string(), HashMap.class);
    return fetchVersionInfoFromResponse(myMap);
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return null;
}
 
Example #8
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExceptionMessageForNonExistentField() {
	StatusCause statusCause = new StatusCause("spec.schedule", null, null);
	StatusDetails statusDetails = new StatusDetails();
	statusDetails.setCauses(Collections.singletonList(statusCause));

	Status status = new Status();
	status.setCode(0);
	status.setMessage("invalid cron expression");
	status.setDetails(statusDetails);

	KubernetesClientException kubernetesClientException = new KubernetesClientException(status);
	String message = ((KubernetesScheduler) scheduler).getExceptionMessageForField(kubernetesClientException,
			"spec.restartpolicy");

	assertNull("Field message should be null", message);
}
 
Example #9
Source File: OpenShiftProjectTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testOpenShiftProjectPreparingWhenProjectDoesNotExist() throws Exception {
  // given
  MetadataNested projectMetadata = prepareProjectRequest();

  Resource resource = prepareProjectResource(PROJECT_NAME);
  doThrow(new KubernetesClientException("error", 403, null)).when(resource).get();
  OpenShiftProject project =
      new OpenShiftProject(clientFactory, executor, PROJECT_NAME, WORKSPACE_ID);

  // when
  openShiftProject.prepare(true);

  // then
  verify(projectMetadata).withName(PROJECT_NAME);
}
 
Example #10
Source File: KubernetesNamespaceTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testKubernetesNamespacePreparingCreationWhenNamespaceDoesNotExist() throws Exception {
  // given
  MetadataNested namespaceMeta = prepareCreateNamespaceRequest();

  Resource resource = prepareNamespaceResource(NAMESPACE);
  doThrow(new KubernetesClientException("error", 403, null)).when(resource).get();
  KubernetesNamespace namespace =
      new KubernetesNamespace(clientFactory, executor, NAMESPACE, WORKSPACE_ID);

  // when
  namespace.prepare(true);

  // then
  verify(namespaceMeta).withName(NAMESPACE);
}
 
Example #11
Source File: Serialization.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Unmarshals an {@link InputStream} optionally performing placeholder substitution to the stream.
 *
 * @param is            The {@link InputStream}.
 * @param type          The {@link TypeReference}.
 * @param parameters    A {@link Map} with parameters for placeholder substitution.
 * @param <T>           Template argument denoting type
 *
 * @return returns de-serialized object
 * @throws KubernetesClientException KubernetesClientException
 */
public static <T> T unmarshal(InputStream is, TypeReference<T> type, Map<String, String> parameters) {
  try (
    InputStream wrapped = parameters != null && !parameters.isEmpty() ? ReplaceValueStream.replaceValues(is, parameters) : is;
    BufferedInputStream bis = new BufferedInputStream(wrapped)
  ) {
    bis.mark(-1);
    int intch;
    do {
      intch = bis.read();
    } while (intch > -1 && Character.isWhitespace(intch));
    bis.reset();

    ObjectMapper mapper = JSON_MAPPER;
    if (intch != '{') {
      mapper = YAML_MAPPER;
    }
    return mapper.readValue(bis, type);
  } catch (IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #12
Source File: WatchHTTPManager.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
  logger.debug("Force closing the watch {}", this);
  forceClosed.set(true);
  if (!executor.isShutdown()) {
    try {
      executor.shutdown();
      if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
        logger.warn("Executor didn't terminate in time after shutdown in close(), killing it in: {}", this);
        executor.shutdownNow();
      }
    } catch (Throwable t) {
      throw KubernetesClientException.launderThrowable(t);
    }
  }
}
 
Example #13
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
protected void applyJob(Job job, String sourceName) {
    String namespace = getNamespace();
    String id = getName(job);
    Objects.requireNonNull(id, "No name for " + job + " " + sourceName);
    if (isServicesOnlyMode()) {
        log.debug("Only processing Services right now so ignoring Job: " + namespace + ":" + id);
        return;
    }
    // Not using createOrReplace() here (https://github.com/fabric8io/kubernetes-client/issues/1586)
    try {
        doCreateJob(job, namespace, sourceName);
    } catch (KubernetesClientException exception) {
        if(exception.getStatus().getCode().equals(HttpURLConnection.HTTP_CONFLICT)) {
            Job old = kubernetesClient.batch().jobs().inNamespace(namespace).withName(id).get();
            Job updatedJob = patchService.compareAndPatchEntity(namespace, job, old);
            log.info("Updated Job: " + old.getMetadata().getName());
            return;
        }
        onApplyError("Failed to apply Job from " + job.getMetadata().getName(), exception);
    }
}
 
Example #14
Source File: KafkaRebalanceResource.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private static DoneableKafkaRebalance deployKafkaRebalance(KafkaRebalance kafkaRebalance) {
    return new DoneableKafkaRebalance(kafkaRebalance, kB -> {
        TestUtils.waitFor("KafkaRebalance creation", Constants.POLL_INTERVAL_FOR_RESOURCE_CREATION, Constants.TIMEOUT_FOR_CR_CREATION,
            () -> {
                try {
                    kafkaRebalanceClient().inNamespace(ResourceManager.kubeClient().getNamespace()).createOrReplace(kB);
                    return true;
                } catch (KubernetesClientException e) {
                    if (e.getMessage().contains("object is being deleted")) {
                        return false;
                    } else {
                        throw e;
                    }
                }
            }
        );
        return waitFor(deleteLater(kB));
    });
}
 
Example #15
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 #16
Source File: KubernetesResource.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public static DoneableDeployment deployNewDeployment(Deployment deployment) {
    return new DoneableDeployment(deployment, co -> {
        TestUtils.waitFor("Deployment creation", Constants.POLL_INTERVAL_FOR_RESOURCE_CREATION, Constants.TIMEOUT_FOR_CR_CREATION,
            () -> {
                try {
                    ResourceManager.kubeClient().createOrReplaceDeployment(co);
                    return true;
                } catch (KubernetesClientException e) {
                    if (e.getMessage().contains("object is being deleted")) {
                        return false;
                    } else {
                        throw e;
                    }
                }
            }
        );
        return waitFor(deleteLater(co));
    });
}
 
Example #17
Source File: KubernetesPodsWatcher.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void onClose(KubernetesClientException cause) {
	// null means the watcher is closed by expected.
	if (cause == null) {
		LOG.info("The pods watcher is closing.");
	} else {
		podsCallbackHandler.handleFatalError(cause);
	}
}
 
Example #18
Source File: KubernetesIngresses.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public List<Ingress> get() throws InfrastructureException {
  try {
    return clientFactory
        .create(workspaceId)
        .extensions()
        .ingresses()
        .inNamespace(namespace)
        .withLabel(CHE_WORKSPACE_ID_LABEL, workspaceId)
        .list()
        .getItems();
  } catch (KubernetesClientException e) {
    throw new KubernetesInfrastructureException(e);
  }
}
 
Example #19
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 #20
Source File: KubernetesDeployments.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Starts watching the pods inside Kubernetes namespace and registers a specified handler for such
 * events. Note that watcher can be started only once so two times invocation of this method will
 * not produce new watcher and just register the event handlers.
 *
 * @param handler pod action events handler
 * @throws InfrastructureException if any error occurs while watcher starting
 */
public void watch(PodActionHandler handler) throws InfrastructureException {
  if (podWatch == null) {
    final Watcher<Pod> watcher =
        new Watcher<Pod>() {
          @Override
          public void eventReceived(Action action, Pod pod) {
            podActionHandlers.forEach(h -> h.handle(action, pod));
          }

          @Override
          public void onClose(KubernetesClientException ignored) {}
        };
    try {
      podWatch =
          clientFactory
              .create(workspaceId)
              .pods()
              .inNamespace(namespace)
              .withLabel(CHE_WORKSPACE_ID_LABEL, workspaceId)
              .watch(watcher);
    } catch (KubernetesClientException ex) {
      throw new KubernetesInfrastructureException(ex);
    }
  }
  podActionHandlers.add(handler);
}
 
Example #21
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected ResponseBody doGetLog(){
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters()));
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    ResponseBody body = response.body();
    assertResponseCode(request, response);
    return body;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t);
  }
}
 
Example #22
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
void deleteThis() {
  try {
    if (item != null) {
      updateApiVersionResource(item);
      handleDelete(item, gracePeriodSeconds, propagationPolicy, cascading);
    } else {
      handleDelete(getResourceUrl(), gracePeriodSeconds, propagationPolicy, cascading);
    }
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(forOperationType("delete"), e);
  }
}
 
Example #23
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public L list(ListOptions listOptions) {
  try {
    return listRequestHelper(fetchListUrl(getNamespacedUrl(), listOptions));
  } catch (MalformedURLException e) {
    throw KubernetesClientException.launderThrowable(forOperationType("list"), e);
  }
}
 
Example #24
Source File: KubernetesIngresses.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public Ingress create(Ingress ingress) throws InfrastructureException {
  putLabel(ingress, CHE_WORKSPACE_ID_LABEL, workspaceId);
  try {
    return clientFactory
        .create(workspaceId)
        .extensions()
        .ingresses()
        .inNamespace(namespace)
        .withName(ingress.getMetadata().getName())
        .create(ingress);
  } catch (KubernetesClientException e) {
    throw new KubernetesInfrastructureException(e);
  }
}
 
Example #25
Source File: KubernetesTaskLauncher.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private List<String> getIdsForTasks(Optional<String> taskName, boolean isCreateJob) {
	List<String> ids = new ArrayList<>();
	try {
		KubernetesResourceList<?> resourceList = getTaskResources(taskName, isCreateJob);

		for (HasMetadata hasMetadata : resourceList.getItems()) {
			ids.add(hasMetadata.getMetadata().getName());
		}
	}
	catch (KubernetesClientException kce) {
		logger.warn(String.format("Failed to retrieve pods for task: %s", taskName), kce);
	}

	return ids;
}
 
Example #26
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void dynamicPVC() throws Exception {
    try {
        cloud.connect().persistentVolumeClaims().list();
    } catch (KubernetesClientException x) {
        // Error from server (Forbidden): persistentvolumeclaims is forbidden: User "system:serviceaccount:kubernetes-plugin-test:default" cannot list resource "persistentvolumeclaims" in API group "" in the namespace "kubernetes-plugin-test"
        assumeNoException("was not permitted to list pvcs, so presumably cannot run test either", x);
    }
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
 
Example #27
Source File: NodeMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NodeMetricsList metrics() {
	try {
		String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL);
		return handleMetric(resourceUrl, NodeMetricsList.class);
	} catch(Exception e) {
		throw KubernetesClientException.launderThrowable(e);
	}
}
 
Example #28
Source File: BuildOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected ResponseBody doGetLog(){
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters()));
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    ResponseBody body = response.body();
    assertResponseCode(request, response);
    return body;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t);
  }
}
 
Example #29
Source File: KubernetesScheduler.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
protected String getExceptionMessageForField(KubernetesClientException clientException,
		String fieldName) {
	List<StatusCause> statusCauses = clientException.getStatus().getDetails().getCauses();

	if (!CollectionUtils.isEmpty(statusCauses)) {
		for (StatusCause statusCause : statusCauses) {
			if (fieldName.equals(statusCause.getField())) {
				return clientException.getStatus().getMessage();
			}
		}
	}

	return null;
}
 
Example #30
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isProjectManaged(OpenShiftClient client) throws InfrastructureException {
  try {
    Project namespace = client.projects().withName(getName()).get();
    return namespace.getMetadata().getLabels() != null
        && "true".equals(namespace.getMetadata().getLabels().get(MANAGED_NAMESPACE_LABEL));
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      throw new InfrastructureException(
          format(
              "Could not access the project %s when trying to determine if it is managed "
                  + "for workspace %s",
              getName(), getWorkspaceId()),
          e);
    } else if (e.getCode() == 404) {
      // we don't want to block whatever work the caller is doing on the namespace. The caller
      // will fail anyway if the project doesn't exist.
      return true;
    }

    throw new InternalInfrastructureException(
        format(
            "Failed to determine whether the project"
                + " %s is managed. OpenShift client said: %s",
            getName(), e.getMessage()),
        e);
  }
}