io.fabric8.kubernetes.api.model.Status Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.Status. 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: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void logBuildFailure(OpenShiftClient client, String buildName) throws JKubeServiceException {
    try {
        List<Build> builds = client.builds().inNamespace(client.getNamespace()).list().getItems();
        for(Build build : builds) {
            if(build.getMetadata().getName().contains(buildName)) {
                log.error(build.getMetadata().getName() + "\t" + "\t" + build.getStatus().getReason() + "\t" + build.getStatus().getMessage());
                throw new JKubeServiceException("Unable to build the image using the OpenShift build service", new KubernetesClientException(build.getStatus().getReason() + " " + build.getStatus().getMessage()));
            }
        }

        log.error("Also, check cluster events via `oc get events` to see what could have possibly gone wrong");
    } catch (KubernetesClientException clientException) {
        Status status = clientException.getStatus();
        if (status != null)
            log.error("OpenShift Error: [%d] %s", status.getCode(), status.getMessage());
    }
}
 
Example #2
Source File: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private Build startBuild(OpenShiftClient client, File dockerTar, String buildName) {
    log.info("Starting Build %s", buildName);
    try {
        return client.buildConfigs().withName(buildName)
                .instantiateBinary()
                .fromFile(dockerTar);
    } catch (KubernetesClientException exp) {
        Status status = exp.getStatus();
        if (status != null) {
            log.error("OpenShift Error: [%d %s] [%s] %s", status.getCode(), status.getStatus(), status.getReason(), status.getMessage());
        }
        if (exp.getCause() instanceof IOException && exp.getCause().getMessage().contains("Stream Closed")) {
            log.error("Build for %s failed: %s", buildName, exp.getCause().getMessage());
            logBuildFailedDetails(client, buildName);
        }
        throw exp;
    }
}
 
Example #3
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteGCPKeysIfSecretAlreadyExists() throws IOException {
  when(serviceAccountKeyManager.serviceAccountExists(SERVICE_ACCOUNT)).thenReturn(true);

  ServiceAccountKey jsonKey = new ServiceAccountKey();
  jsonKey.setName("key.json");
  jsonKey.setPrivateKeyData("json-private-key-data");
  ServiceAccountKey p12Key = new ServiceAccountKey();
  p12Key.setName("key.p12");
  p12Key.setPrivateKeyData("p12-private-key-data");
  when(serviceAccountKeyManager.createJsonKey(any(String.class))).thenReturn(jsonKey);
  when(serviceAccountKeyManager.createP12Key(any(String.class))).thenReturn(p12Key);
  when(k8sClient.createSecret(any())).thenThrow(new KubernetesClientException(
      "Already exists", 409, new Status()));

  sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);

  verify(serviceAccountKeyManager).createJsonKey(SERVICE_ACCOUNT);
  verify(serviceAccountKeyManager).createP12Key(SERVICE_ACCOUNT);
  verify(serviceAccountKeyManager).tryDeleteKey(jsonKey.getName());
  verify(serviceAccountKeyManager).tryDeleteKey(p12Key.getName());
}
 
Example #4
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExceptionMessageForExistingField() {
	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.schedule");

	assertNotNull("Field message should not be null", message);
	assertEquals("Invalid message for field", "invalid cron expression", message);
}
 
Example #5
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 #6
Source File: DeploymentTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testRollback() {
  DeploymentRollback deploymentRollback = new DeploymentRollbackBuilder()
    .withName("deployment1")
    .withNewRollbackTo().withRevision(1L).endRollbackTo()
    .withUpdatedAnnotations(Collections.singletonMap("foo", "bar"))
    .build();

  Status status = new StatusBuilder().build();
  KubernetesClient client = server.getClient();
  server.expect()
    .post()
    .withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1/rollback")
    .andReturn(201, status).once();

  client.extensions().deployments().inNamespace("test").withName("deployment1").rollback(deploymentRollback);
}
 
Example #7
Source File: ProjectRequestsOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Status list(ListOptions listOptions) {
  try {
    HttpUrl.Builder urlBuilder = HttpUrl.get(getNamespacedUrl().toString()).newBuilder();
    if(listOptions.getLimit() != null) {
      urlBuilder.addQueryParameter("limit", listOptions.getLimit().toString());
    }
    if(listOptions.getContinue() != null) {
      urlBuilder.addQueryParameter("continue", listOptions.getContinue());
    }

    if (listOptions.getResourceVersion() != null) {
      urlBuilder.addQueryParameter("resourceVersion", listOptions.getResourceVersion());
    }

    if (listOptions.getFieldSelector() != null) {
      urlBuilder.addQueryParameter("fieldSelector", listOptions.getFieldSelector());
    }

    if (listOptions.getLabelSelector() != null) {
      urlBuilder.addQueryParameter("labelSelector", listOptions.getLabelSelector());
    }

    if (listOptions.getTimeoutSeconds() != null) {
      urlBuilder.addQueryParameter("timeoutSeconds", listOptions.getTimeoutSeconds().toString());
    }

    if (listOptions.getAllowWatchBookmarks() != null) {
      urlBuilder.addQueryParameter("allowWatchBookmarks", listOptions.getAllowWatchBookmarks().toString());
    }
    Request.Builder requestBuilder = new Request.Builder().get().url(urlBuilder.build());
    return handleResponse(requestBuilder, Status.class);
  } catch (InterruptedException | ExecutionException | IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #8
Source File: ProjectRequestsOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Status list() {
  try {
    URL requestUrl = getNamespacedUrl();
    Request.Builder requestBuilder = new Request.Builder().get().url(requestUrl);
    return handleResponse(requestBuilder, Status.class);
  } catch (InterruptedException | ExecutionException | IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #9
Source File: KubernetesClientException.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static RuntimeException launderThrowable(OperationInfo spec, Status status, Throwable cause) {
  StringBuilder sb = new StringBuilder();
  sb.append(describeOperation(spec)+ " failed.");
  if (status != null && Utils.isNotNullOrEmpty(status.getMessage())) {
    sb.append("Reason: ").append(status.getMessage());
  }
  return launderThrowable(sb.toString(), cause);
}
 
Example #10
Source File: ExecWebSocketListener.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {

    //If we already called onClosed() or onFailed() before, we need to abort.
    if (explicitlyClosed.get() || closed.get() || !failed.compareAndSet(false, true) ) {
      //We are not going to notify the listener, sicne we've already called onClose(), so let's log a debug/warning.
      if (LOGGER.isDebugEnabled()) {
        LOGGER.warn("Received [" + t.getClass().getCanonicalName() + "], with message:[" + t.getMessage() + "] after ExecWebSocketListener is closed, Ignoring.");
      }
      return;
    }

    try {
      Status status = OperationSupport.createStatus(response);
      LOGGER.error("Exec Failure: HTTP:" + status.getCode() + ". Message:" + status.getMessage(), t);
      //We only need to queue startup failures.
      if (!started.get()) {
        queue.add(new KubernetesClientException(status));
      }

      cleanUpOnce();
    } finally {
      if (listener != null) {
        listener.onFailure(t, response);
      }
    }
  }
 
Example #11
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static KubernetesClientException requestFailure(Request request, Status status) {
  StringBuilder sb = new StringBuilder();
  sb.append("Failure executing: ").append(request.method())
    .append(" at: ").append(request.url().toString()).append(".");

  if (status.getMessage() != null && !status.getMessage().isEmpty()) {
    sb.append(" Message: ").append(status.getMessage()).append(".");
  }

  if (status != null && !status.getAdditionalProperties().containsKey(CLIENT_STATUS_FLAG)) {
    sb.append(" Received status: ").append(status).append(".");
  }

  return new KubernetesClientException(sb.toString(), status.getCode(), status);
}
 
Example #12
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static Status createStatus(int statusCode, String message) {
  Status status = new StatusBuilder()
          .withCode(statusCode)
          .withMessage(message)
          .build();
  status.getAdditionalProperties().put(CLIENT_STATUS_FLAG, "true");
  return status;
}
 
Example #13
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private String combineMessages(String customMessage, Status defaultStatus) {
  if (defaultStatus != null) {
    String message = defaultStatus.getMessage();
    if (message != null && message.length() > 0) {
      return customMessage + " " + message;
    }
  }
  return customMessage;
}
 
Example #14
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected Status handleDeploymentRollback(DeploymentRollback deploymentRollback) {
  try {
    return handleDeploymentRollback(getCompleteResourceUrl().toString(), deploymentRollback);
  } catch (InterruptedException | ExecutionException | IOException e) {
    throw KubernetesClientException.launderThrowable(forOperationType("rollback"), e);
  }
}
 
Example #15
Source File: Watcher.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private void run() {
    customResource.inAnyNamespace().watch(new io.fabric8.kubernetes.client.Watcher<Vault>() {
        @Override
        public void eventReceived(Action action, Vault resource) {
            log.info("Received action: {} for {} in namespace {}", action.name(), resource.getMetadata().getName(), resource.getMetadata().getNamespace());

            switch (action) {
                case ADDED:
                    eventHandler.addHandler(resource);
                    break;
                case MODIFIED:
                    eventHandler.modifyHandler(resource);
                    break;
                case DELETED:
                    eventHandler.deleteHandler(resource);
                    break;
                default:
                    log.error("Handling of action failed, not implemented action");
            }
        }

        @Override
        public void onClose(KubernetesClientException cause) {
            Optional<Integer> statusCode = Optional.ofNullable(cause)
                    .map(KubernetesClientException::getStatus)
                    .map(Status::getCode);

            int status = statusCode.orElse(-1);
            if (status == HttpURLConnection.HTTP_GONE) {
                log.warn("Http Gone exception ignored!");
                run();
            } else {
                log.error("Watch for custom resource failed with status: " + status, cause);
                System.exit(1);
            }
        }
    });
}
 
Example #16
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testDontRetryWatchOnHttpGone() throws InterruptedException {
  Pod noReady = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_GONE)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  try {
    client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
    fail("should have thrown KubernetesClientException");
  } catch (KubernetesClientException e) {
    assertTrue(e.getCause() instanceof WaitForConditionWatcher.WatchException);
  }
}
 
Example #17
Source File: AdmissionReviewService.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private AdmissionResponse invalidRequest(String uid, String message) {
    Status status = new StatusBuilder()
            .withCode(400)
            .withMessage(message)
            .build();
    return new AdmissionResponseBuilder()
            .withAllowed(false)
            .withUid(uid)
            .withStatus(status)
            .build();
}
 
Example #18
Source File: ProjectRequestTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testList() {
 server.expect().withPath("/apis/project.openshift.io/v1/projectrequests").andReturn(200, new StatusBuilder().withMessage("success").build()).once();
  OpenShiftClient client = server.getOpenshiftClient();

  Status status = client.projectrequests().list();
  assertNotNull(status);
  assertEquals("success", status.getMessage());
}
 
Example #19
Source File: MeteredFabric8KubernetesClientProxyTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void reportKubernetesClientException() {
  doThrow(new KubernetesClientException("enhance your calm", 429, new Status()))
      .when(fabric8KubernetesClient).listPods();

  try {
    proxy.listPods();
    fail("Expected exception");
  } catch (Exception ignored) {
  }

  verify(stats).recordKubernetesOperationError("listPods", "kubernetes-client", 429);
}
 
Example #20
Source File: ReflectorWatcher.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onClose(KubernetesClientException exception) {
  log.error("Watch closing");
  Optional.ofNullable(exception)
    .map(e -> {
      log.debug("Exception received during watch", e);
      return exception;
    })
    .map(KubernetesClientException::getStatus)
    .map(Status::getCode)
    .filter(c -> c.equals(HttpURLConnection.HTTP_GONE))
    .ifPresent(c -> onHttpGone.run());
  onClose.run();
}
 
Example #21
Source File: ReplicationControllerOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Status rollback(DeploymentRollback deploymentRollback) {
  throw new KubernetesClientException("rollback not supported in case of ReplicationControllers");
}
 
Example #22
Source File: ProjectRequestsOperationImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Status list(Integer limitVal, String continueVal) {
  return list(new ListOptionsBuilder().withLimit(Long.parseLong(limitVal.toString())).withContinue(continueVal).build());
}
 
Example #23
Source File: KubernetesClientException.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public Status getStatus() {
  return status;
}
 
Example #24
Source File: KubernetesClientException.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public KubernetesClientException(String message, int code, Status status) {
  super(message);
  this.code = code;
  this.status = status;
}
 
Example #25
Source File: KubernetesClientException.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public KubernetesClientException(Status status) {
  this(status.getMessage(), status.getCode(), status);
}
 
Example #26
Source File: StatefulSetOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Status rollback(DeploymentRollback deploymentRollback) {
  throw new KubernetesClientException("rollback not supported in case of StatefulSets");
}
 
Example #27
Source File: ReplicaSetOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Status rollback(DeploymentRollback deploymentRollback) {
  throw new KubernetesClientException("rollback not supported in case of ReplicaSets");
}
 
Example #28
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testRetryOnErrorEventDuringWaitReturnFromAPIIfMatch() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_FORBIDDEN)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).once();
  // once ready, after watch fails
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, ready).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #29
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testRetryOnErrorEventDuringWait() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();

  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_FORBIDDEN)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).times(2);

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(ready, "MODIFIED"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #30
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 2 votes vote down vote up
/**
 * Create rollback of a Deployment
 *
 * @param resourceUrl resource url
 * @param deploymentRollback DeploymentRollback resource
 * @return Status
 * @throws ExecutionException in case of any execution exception
 * @throws InterruptedException in case thread is interrupted
 * @throws KubernetesClientException in case error from Kubernetes API
 * @throws MalformedURLException in case URL formed in invalid
 * @throws JsonProcessingException in case Json processing fails
 * @throws IOException in some other I/O problem
 */
protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws ExecutionException, InterruptedException, KubernetesClientException, MalformedURLException, JsonProcessingException, IOException {
  RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback));
  Request.Builder requestBuilder = new Request.Builder().post(body).url(resourceUrl + "/rollback");
  return handleResponse(requestBuilder, Status.class);
}