Java Code Examples for io.kubernetes.client.openapi.ApiException#getCode()

The following examples show how to use io.kubernetes.client.openapi.ApiException#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: GenericKubernetesApi.java    From java with Apache License 2.0 6 votes vote down vote up
private <DataType extends KubernetesType> KubernetesApiResponse<DataType> executeCall(
    ApiClient apiClient, Class<DataType> dataClass, CallBuilder callBuilder) {
  try {
    Call call = callBuilder.build();
    call = tweakCallForCoreV1Group(call);
    JsonElement element = apiClient.<JsonElement>execute(call, JsonElement.class).getData();
    return getKubernetesApiResponse(dataClass, element, apiClient.getJSON().getGson());
  } catch (ApiException e) {
    if (e.getCause() instanceof IOException) {
      throw new IllegalStateException(e.getCause()); // make this a checked exception?
    }
    V1Status status = apiClient.getJSON().deserialize(e.getResponseBody(), V1Status.class);
    if (null == status) { // the response body can be something unexpected sometimes..
      throw new RuntimeException(e.getCause());
    }
    return new KubernetesApiResponse<>(status, e.getCode());
  }
}
 
Example 2
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * a test method to see whether kubernetes java client can connect to kubernetes master
 * and get the pod list
 */
public static void testGetPodList(String namespace) {
  if (apiClient == null || coreApi == null) {
    createApiInstances();
  }

  LOG.info("Getting the pod list for the namespace: " + namespace);
  V1PodList list = null;
  try {
    list = coreApi.listNamespacedPod(
        namespace, null, null, null, null, null, null, null, null, null);
  } catch (ApiException e) {
    String logMessage = "Exception when getting the pod list: \n"
        + "exCode: " + e.getCode() + "\n"
        + "responseBody: " + e.getResponseBody();
    LOG.log(Level.SEVERE, logMessage, e);
    throw new RuntimeException(e);
  }

  LOG.info("Number of pods in the received list: " + list.getItems().size());
  for (V1Pod item : list.getItems()) {
    LOG.info(item.getMetadata().getName());
  }
}
 
Example 3
Source File: LegacyEventBroadcaster.java    From java with Apache License 2.0 5 votes vote down vote up
private boolean recordEvent(V1Event event, V1Patch patch, boolean updateExistingEvent) {
  V1Event newEvent = null;
  try {
    if (updateExistingEvent) {
      try {
        newEvent = this.eventSink.patch(event, patch);
      } catch (ApiException patchException) {
        if (patchException.getCode() == HttpURLConnection.HTTP_NOT_FOUND) { // not found
          event = new V1EventBuilder(event).build();
          event.getMetadata().setResourceVersion("");
          updateExistingEvent = false;
        }
      }
    }
    if (!updateExistingEvent) {
      try {
        newEvent = this.eventSink.create(event);
      } catch (ApiException e) {
        if (e.getCode()
            == HttpURLConnection
                .HTTP_CONFLICT) { // "409 Conflict" suggests the requested resource already exists
          logger.error("event already exists", e);
          return true;
        }
        return false;
      }
    }
  } finally {
    if (newEvent != null) {
      this.eventCorrelator.updateState(newEvent);
    }
  }
  return true;
}
 
Example 4
Source File: LeaderElector.java    From java with Apache License 2.0 4 votes vote down vote up
private boolean tryAcquireOrRenew() {
  Date now = new Date();
  Lock lock = config.getLock();
  LeaderElectionRecord leaderElectionRecord =
      new LeaderElectionRecord(
          lock.identity(),
          Long.valueOf(config.getLeaseDuration().getSeconds()).intValue(),
          now,
          now,
          0);

  // 1. obtain or create the ElectionRecord
  LeaderElectionRecord oldLeaderElectionRecord;
  try {
    oldLeaderElectionRecord = lock.get();
  } catch (ApiException e) {
    if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
      log.error("Error retrieving resource lock {} as {}", lock.describe(), e.getMessage());
      return false;
    }

    return createLock(lock, leaderElectionRecord);
  }

  if (oldLeaderElectionRecord == null
      || oldLeaderElectionRecord.getAcquireTime() == null
      || oldLeaderElectionRecord.getRenewTime() == null
      || oldLeaderElectionRecord.getHolderIdentity() == null) {
    return createLock(lock, leaderElectionRecord);
  }

  // 2. Record obtained, check the Identity & Time
  if (!oldLeaderElectionRecord.equals(this.observedRecord)) {
    this.observedRecord = oldLeaderElectionRecord;
    this.observedTimeMilliSeconds = System.currentTimeMillis();
  }
  if (observedTimeMilliSeconds + config.getLeaseDuration().toMillis() > now.getTime()
      && !isLeader()) {
    if (log.isDebugEnabled()) {
      log.debug(
          "Lock is held by {} and has not yet expired",
          oldLeaderElectionRecord.getHolderIdentity());
    }
    return false;
  }

  // 3. We're going to try to update. The leaderElectionRecord is set to it's default
  // here. Let's correct it before updating.
  if (isLeader()) {
    leaderElectionRecord.setAcquireTime(oldLeaderElectionRecord.getAcquireTime());
    leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions());
  } else {
    leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions() + 1);
  }

  // update the lock itself
  if (log.isDebugEnabled()) {
    log.debug("Update lock acquire time to keep lease");
  }
  boolean updateSuccess = config.getLock().update(leaderElectionRecord);
  if (!updateSuccess) {
    return false;
  }
  this.observedRecord = leaderElectionRecord;
  this.observedTimeMilliSeconds = System.currentTimeMillis();
  if (log.isDebugEnabled()) {
    log.debug("TryAcquireOrRenew return success");
  }
  return true;
}
 
Example 5
Source File: KubeOpt.java    From dew with Apache License 2.0 4 votes vote down vote up
/**
 * Read.
 *
 * @param <T>       the type parameter
 * @param name      the name
 * @param namespace the namespace
 * @param res       the res
 * @param clazz     the clazz
 * @return the resource
 * @throws ApiException the api exception
 */
public <T> T read(String name, String namespace, KubeRES res, Class<T> clazz) throws ApiException {
    Object resource;
    try {
        switch (res) {
            case NAME_SPACE:
                resource = coreApi.readNamespace(
                        name, null, false, false);
                break;
            case INGRESS:
                resource = extensionsApi.readNamespacedIngress(
                        name, namespace, null, false, false);
                break;
            case SERVICE:
                resource = coreApi.readNamespacedService(
                        name, namespace, null, false, false);
                break;
            case DEPLOYMENT:
                resource = appsApi.readNamespacedDeployment(
                        name, namespace, null, false, false);
                break;
            case REPLICA_SET:
                resource = appsApi.readNamespacedReplicaSet(
                        name, namespace, null, false, false);
                break;
            case POD:
                resource = coreApi.readNamespacedPod(
                        name, namespace, null, false, false);
                break;
            case SECRET:
                resource = coreApi.readNamespacedSecret(
                        name, namespace, null, false, false);
                break;
            case CONFIG_MAP:
                resource = coreApi.readNamespacedConfigMap(
                        name, namespace, null, false, false);
                break;
            case SERVICE_ACCOUNT:
                resource = coreApi.readNamespacedServiceAccount(
                        name, namespace, null, false, false);
                break;
            case DAEMON_SET:
                resource = appsApi.readNamespacedDaemonSet(
                        name, namespace, null, false, false);
                break;
            case ROLE:
                resource = rbacAuthorizationApi.readNamespacedRole(
                        name, namespace, null);
                break;
            case ROLE_BINDING:
                resource = rbacAuthorizationApi.readNamespacedRoleBinding(
                        name, namespace, null);
                break;
            case CLUSTER_ROLE:
                resource = rbacAuthorizationApi.readClusterRole(
                        name, null);
                break;
            case CLUSTER_ROLE_BINDING:
                resource = rbacAuthorizationApi.readClusterRoleBinding(
                        name, null);
                break;
            case HORIZONTAL_POD_AUTOSCALER:
                resource = autoscalingApi.readNamespacedHorizontalPodAutoscaler(
                        name, namespace, null, false, false);
                break;
            default:
                throw new ApiException("The resource [" + res.getVal() + "] operation NOT implementation");
        }
        if (clazz == String.class) {
            return (T) Yaml.dump(resource);
        } else {
            return (T) resource;
        }
    } catch (ApiException e) {
        // TODO 优雅的判断是否存在
        if (e.getCode() == 404) {
            return null;
        }
        throw e;
    }
}