Java Code Examples for io.fabric8.kubernetes.client.KubernetesClientException#getCode()

The following examples show how to use io.fabric8.kubernetes.client.KubernetesClientException#getCode() . 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: BaseOperation.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public T require() throws ResourceNotFoundException {
  try {
    T answer = getMandatory();
    if (answer == null) {
      throw new ResourceNotFoundException("The resource you request doesn't exist or couldn't be fetched.");
    }
    if (answer instanceof HasMetadata) {
      HasMetadata hasMetadata = (HasMetadata) answer;
      updateApiVersion(hasMetadata);
    } else if (answer instanceof KubernetesResourceList) {
      KubernetesResourceList list = (KubernetesResourceList) answer;
      updateApiVersion(list);
    }
    return answer;
  } catch (KubernetesClientException e) {
    if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
      throw e;
    }
    throw new ResourceNotFoundException("Resource not found : " + e.getMessage());
  }
}
 
Example 2
Source File: OpenShiftProjectFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Optional<Project> fetchNamespaceObject(String name) throws InfrastructureException {
  try {
    Project project = clientFactory.createOC().projects().withName(name).get();
    return Optional.ofNullable(project);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      // 403 means that the project does not exist
      // or a user really is not permitted to access it which is Che Server misconfiguration
      return Optional.empty();
    } else {
      throw new InfrastructureException(
          format("Error while trying to fetch the project '%s'. Cause: %s", name, e.getMessage()),
          e);
    }
  }
}
 
Example 3
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Deletes the project. Deleting a non-existent projects is not an error as is not an attempt to
 * delete a project that is already being deleted.
 *
 * @throws InfrastructureException if any unexpected exception occurs during project deletion
 */
void delete() throws InfrastructureException {
  String workspaceId = getWorkspaceId();
  String projectName = getName();

  OpenShiftClient osClient = clientFactory.createOC(workspaceId);

  try {
    delete(projectName, osClient);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      throw new InfrastructureException(
          format(
              "Could not access the project %s when deleting it for workspace %s",
              projectName, workspaceId),
          e);
    }

    throw new KubernetesInfrastructureException(e);
  }
}
 
Example 4
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void create(String projectName, OpenShiftClient osClient) throws InfrastructureException {
  try {
    osClient
        .projectrequests()
        .createNew()
        .withNewMetadata()
        .withName(projectName)
        .endMetadata()
        .done();
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      LOG.error(
          "Unable to create new OpenShift project due to lack of permissions."
              + "HINT: When using workspace project name placeholders, os-oauth or service account with more lenient permissions (cluster-admin) must be used.");
    }
    throw new KubernetesInfrastructureException(e);
  }
}
 
Example 5
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void delete(String projectName, OpenShiftClient osClient) throws InfrastructureException {
  try {
    osClient.projects().withName(projectName).delete();
  } catch (KubernetesClientException e) {
    if (e.getCode() == 404) {
      LOG.warn(
          format(
              "Tried to delete project '%s' but it doesn't exist in the cluster.", projectName),
          e);
    } else if (e.getCode() == 409) {
      LOG.info(format("The project '%s' is currently being deleted.", projectName), e);
    } else {
      throw new KubernetesInfrastructureException(e);
    }
  }
}
 
Example 6
Source File: URLFromOpenshiftRouteImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public String getURL(Service service, String portName, String namespace, KubernetesClient client) {
  String serviceName = service.getMetadata().getName();
  ServicePort port = URLFromServiceUtil.getServicePortByName(service, portName);
  if(port != null && port.getName() != null && isOpenShift(client)) {
    try {
      String serviceProtocol = port.getProtocol();
      OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
      Route route = openShiftClient.routes().inNamespace(namespace).withName(service.getMetadata().getName()).get();
      if (route != null) {
        return (serviceProtocol + "://" + route.getSpec().getHost()).toLowerCase(Locale.ROOT);
      }
    } catch (KubernetesClientException e) {
      if(e.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
        logger.warn("Could not lookup route:" + serviceName + " in namespace:"+ namespace +", due to: " + e.getMessage());
      }
    }
  }
  return null;
}
 
Example 7
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 8
Source File: KubernetesNamespace.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Deletes the namespace. Deleting a non-existent namespace is not an error as is not an attempt
 * to delete a namespace that is already being deleted.
 *
 * @throws InfrastructureException if any unexpected exception occurs during namespace deletion
 */
void delete() throws InfrastructureException {
  KubernetesClient client = clientFactory.create(workspaceId);

  try {
    delete(name, client);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      throw new InfrastructureException(
          format(
              "Could not access the namespace %s when deleting it for workspace %s",
              name, workspaceId),
          e);
    }

    throw new KubernetesInfrastructureException(e);
  }
}
 
Example 9
Source File: KubernetesNamespace.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void create(String namespaceName, KubernetesClient client)
    throws InfrastructureException {
  try {
    client
        .namespaces()
        .createNew()
        .withNewMetadata()
        .withName(namespaceName)
        .endMetadata()
        .done();
    waitDefaultServiceAccount(namespaceName, client);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      LOG.error(
          "Unable to create new Kubernetes project due to lack of permissions."
              + "When using workspace namespace placeholders, service account with lenient permissions (cluster-admin) must be used.");
    }
    throw new KubernetesInfrastructureException(e);
  }
}
 
Example 10
Source File: KubernetesHandler.java    From apollo with Apache License 2.0 5 votes vote down vote up
public void restartPod(String podName) throws ApolloKubernetesException {
    // Deleting a pod, which created with a deployment is basically restarting since the replica set will create a new one immediately
    try {
        kubernetesClient
                .pods()
                .inNamespace(environment.getKubernetesNamespace())
                .withName(podName)
                .delete();
    } catch (KubernetesClientException e) {
        // Async deletion throws KubernetesClientException with code 202, but it's working and actually deleting the pod
        if (e.getCode() != HttpStatus.ACCEPTED) {
            throw new ApolloKubernetesException();
        }
    }
}
 
Example 11
Source File: KubernetesClusterService.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@Override
public void onClose(KubernetesClientException cause) {
    // try to re-add it if it's an abnormal close
    if (cause != null) {
        if (cause.getCode() == HTTP_GONE) {
            logger.info(
                    "Watcher on StatefulSet {} was closed. Reason: {} ",
                    name,
                    cause.getMessage());
        } else {
            logger.error("Watcher on StatefulSet {} was closed", name, cause);
        }
        watchStatefulSet();
    }
}
 
Example 12
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean evict() {
  try {
    evictThis();
    return true;
  } catch (KubernetesClientException e) {
    if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND && e.getCode() != HTTP_TOO_MANY_REQUESTS) {
      throw e;
    }
    return false;
  }
}
 
Example 13
Source File: RawCustomResourceOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> createOrReplaceObject(String namespace, Map<String, Object> objectAsMap) throws IOException {
  Map<String, Object> metadata = (Map<String, Object>) objectAsMap.get(METADATA);
  if (metadata == null) {
    throw KubernetesClientException.launderThrowable(new IllegalStateException("Invalid object provided -- metadata is required."));
  }

  Map<String, Object> ret;

  // can't include resourceVersion in create calls
  String originalResourceVersion = (String) metadata.get(RESOURCE_VERSION);
  metadata.remove(RESOURCE_VERSION);

  try {
    if(namespace != null) {
      ret = create(namespace, objectAsMap);
    } else {
      ret = create(objectAsMap);
    }
  } catch (KubernetesClientException exception) {
    if (exception.getCode() != HttpURLConnection.HTTP_CONFLICT) {
      throw exception;
    }

    try {
      // re-add for edit call
      if (originalResourceVersion != null) {
        metadata.put(RESOURCE_VERSION, originalResourceVersion);
      }
      String name = (String) metadata.get("name");
      ret = namespace != null ?
        edit(namespace, name, objectAsMap) : edit(name, objectAsMap);
    } catch (NullPointerException nullPointerException) {
      throw KubernetesClientException.launderThrowable(new IllegalStateException("Invalid object provided -- metadata.name is required."));
    }
  }
  return ret;
}
 
Example 14
Source File: KubernetesInfrastructureException.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private static String extractMessage(KubernetesClientException e) {
  int code = e.getCode();
  if (code == 401 || code == 403) {
    return e.getMessage()
        + " The error may be caused by an expired token or changed password. "
        + "Update Che server deployment with a new token or password.";
  } else {
    return e.getMessage();
  }
}
 
Example 15
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);
  }
}
 
Example 16
Source File: KubernetesLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Secret createSecret(final String namespace, final String secretName, String auth) {
    try (KubernetesClient client = getClient()) {
        Secret secret = client.secrets().inNamespace(namespace).withName(secretName).get();
        if (secret != null) return secret;

        String json = String.format("{\"https://index.docker.io/v1/\":{\"auth\":\"%s\"}}", auth);
        String base64encoded = BaseEncoding.base64().encode(json.getBytes(Charset.defaultCharset()));
        secret = new SecretBuilder()
                .withNewMetadata()
                .withName(secretName)
                .endMetadata()
                .withType(KUBERNETES_DOCKERCFG)
                .withData(ImmutableMap.of(".dockercfg", base64encoded))
                .build();
        try {
            client.secrets().inNamespace(namespace).create(secret);
        } catch (KubernetesClientException e) {
            if (e.getCode() == 500 && e.getMessage().contains("Message: resourceVersion may not be set on objects to be created")) {
                // ignore exception as per https://github.com/fabric8io/kubernetes-client/issues/451
            } else {
                throw Throwables.propagate(e);
            }
        }
        ExitCondition exitCondition = new ExitCondition() {
            @Override
            public Boolean call() {
                return client.secrets().inNamespace(namespace).withName(secretName).get() != null;
            }

            @Override
            public String getFailureMessage() {
                return "Absent namespace=" + namespace + ", secretName=" + secretName;
            }
        };
        waitForExitCondition(exitCondition);
        return client.secrets().inNamespace(namespace).withName(secretName).get();
    }
}
 
Example 17
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void update(Project project, OpenShiftClient client) throws InfrastructureException {
  try {
    client.projects().createOrReplace(project);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      LOG.error(
          "Unable to update new Kubernetes project due to lack of permissions."
              + "When using workspace namespace placeholders, service account with lenient permissions (cluster-admin) must be used.");
    }
    throw new KubernetesInfrastructureException(e);
  }
}
 
Example 18
Source File: KubernetesDockerRunner.java    From styx with Apache License 2.0 5 votes vote down vote up
@Override
public String start(RunState runState, RunSpec runSpec) throws IOException {
  var workflowInstance = runState.workflowInstance();

  // First make cheap check for if pod already exists
  var existingPod = client.getPod(runSpec.executionId());
  if (existingPod.isPresent()) {
    LOG.info("Pod already exists, not creating: {}: {}", workflowInstance, existingPod);
    return id;
  }

  // Set up secrets
  final KubernetesSecretSpec secretSpec = ensureSecrets(workflowInstance, runSpec);

  // Create pod. This might fail with 409 Conflict if the pod already exists as despite the existence
  // check above it might have been concurrently created. That is fine.
  try {
    var pod = createPod(workflowInstance, runSpec, secretSpec, styxEnvironment);
    LOG.info("Creating pod: {}: {}", workflowInstance, pod);
    var createdPod = client.createPod(pod);
    stats.recordSubmission(runSpec.executionId());
    LOG.info("Created pod: {}: {}", workflowInstance, createdPod);
  } catch (KubernetesClientException kce) {
    if (kce.getCode() == 409 && kce.getStatus().getReason().equals("AlreadyExists")) {
      LOG.info("Pod already existed when creating: {}: {}", workflowInstance, runSpec.executionId());
      // Already launched, success!
    } else {
      throw new IOException("Failed to create Kubernetes pod", kce);
    }
  }

  return id;
}
 
Example 19
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public OpenShiftProject createProject(final String name) throws
        DuplicateProjectException,
        IllegalArgumentException {

    // Create
    final ProjectRequest projectRequest;
    try {
        projectRequest = client.projectrequests().createNew().
                withNewMetadata().
                withName(name).
                endMetadata().
                done();
    } catch (final KubernetesClientException kce) {
        // Detect if duplicate project
        if (kce.getCode() == CODE_DUPLICATE_PROJECT &&
                STATUS_REASON_DUPLICATE_PROJECT.equals(kce.getStatus().getReason())) {
            throw new DuplicateProjectException(name);
        }

        // Some other error, rethrow it
        throw kce;
    }

    // Block until exists
    int counter = 0;
    while (true) {
        counter++;
        if (projectExists(name)) {
            // We good
            break;
        }
        if (counter == 20) {
            throw new IllegalStateException("Newly-created project "
                                                    + name + " could not be found ");
        }
        log.finest("Couldn't find project " + name +
                           " after creating; waiting and trying again...");
        try {
            Thread.sleep(3000);
        } catch (final InterruptedException ie) {
            Thread.interrupted();
            throw new RuntimeException("Someone interrupted thread while finding newly-created project", ie);
        }
    }
    // Populate value object and return it
    final String roundtripDisplayName = projectRequest.getMetadata().getName();
    final OpenShiftProject project = new OpenShiftProjectImpl(roundtripDisplayName, consoleUrl.toString());

    return project;
}
 
Example 20
Source File: WaitForConditionWatcher.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private boolean isHttpGone() {
  KubernetesClientException cause = ((KubernetesClientException) getCause());
  return cause.getCode() == HttpURLConnection.HTTP_GONE
    || (cause.getStatus() != null && cause.getStatus().getCode() == HttpURLConnection.HTTP_GONE);
}