Search in sources :

Example 16 with ApiException

use of io.kubernetes.client.openapi.ApiException in project java by kubernetes-client.

the class LeaderElector method tryAcquireOrRenew.

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, config.getOwnerReference());
    // 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 {}", lock.describe(), e);
            return false;
        }
        if (log.isDebugEnabled()) {
            log.debug("Lock not found, try to create it");
        }
        // No Lock resource exists, try to get leadership by creating it
        return createLock(lock, leaderElectionRecord);
    }
    if (oldLeaderElectionRecord == null || oldLeaderElectionRecord.getAcquireTime() == null || oldLeaderElectionRecord.getRenewTime() == null || oldLeaderElectionRecord.getHolderIdentity() == null) {
        // updating it
        if (log.isDebugEnabled()) {
            log.debug("Update lock to get lease");
        }
        if (oldLeaderElectionRecord != null) {
            // maintain the leaderTransitions
            leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions() + 1);
        }
        return updateLock(lock, leaderElectionRecord);
    }
    // 2. Record obtained with LeaderElectionRecord, check the Identity & Time
    if (!oldLeaderElectionRecord.equals(this.observedRecord)) {
        this.observedRecord = oldLeaderElectionRecord;
        this.observedTimeMilliSeconds = System.currentTimeMillis();
    }
    if (observedTimeMilliSeconds + config.getLeaseDuration().toMillis() > now.getTime() && !isLeader()) {
        log.debug("Lock is held by {} and has not yet expired", oldLeaderElectionRecord.getHolderIdentity());
        return false;
    }
    // here. Let's correct it before updating.
    if (isLeader()) {
        leaderElectionRecord.setAcquireTime(oldLeaderElectionRecord.getAcquireTime());
        leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions());
    } else {
        leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions() + 1);
    }
    if (log.isDebugEnabled()) {
        log.debug("Update lock to renew lease");
    }
    boolean renewalStatus = updateLock(lock, leaderElectionRecord);
    if (renewalStatus && log.isDebugEnabled()) {
        log.debug("TryAcquireOrRenew return success");
    }
    return renewalStatus;
}
Also used : Date(java.util.Date) ApiException(io.kubernetes.client.openapi.ApiException)

Example 17 with ApiException

use of io.kubernetes.client.openapi.ApiException in project java by kubernetes-client.

the class ConfigMapLock method create.

@Override
public boolean create(LeaderElectionRecord record) {
    try {
        V1ConfigMap configMap = new V1ConfigMap();
        V1ObjectMeta objectMeta = new V1ObjectMeta();
        objectMeta.setName(name);
        objectMeta.setNamespace(namespace);
        Map<String, String> annotations = new HashMap<>();
        annotations.put(LeaderElectionRecordAnnotationKey, coreV1Client.getApiClient().getJSON().serialize(record));
        objectMeta.setAnnotations(annotations);
        if (record.getOwnerReference() != null) {
            objectMeta.setOwnerReferences(Collections.singletonList(record.getOwnerReference()));
        }
        configMap.setMetadata(objectMeta);
        V1ConfigMap createdConfigMap = coreV1Client.createNamespacedConfigMap(namespace, configMap, null, null, null, null);
        configMapRefer.set(createdConfigMap);
        return true;
    } catch (ApiException e) {
        if (e.getCode() == HttpURLConnection.HTTP_CONFLICT) {
            log.debug("received {} when creating configmap lock", e.getCode(), e);
        } else {
            log.error("received {} when creating configmap lock", e.getCode(), e);
        }
        return false;
    }
}
Also used : HashMap(java.util.HashMap) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) ApiException(io.kubernetes.client.openapi.ApiException)

Example 18 with ApiException

use of io.kubernetes.client.openapi.ApiException in project java by kubernetes-client.

the class ConfigMapLock method update.

@Override
public boolean update(LeaderElectionRecord record) {
    try {
        V1ConfigMap configMap = configMapRefer.get();
        configMap.getMetadata().putAnnotationsItem(LeaderElectionRecordAnnotationKey, coreV1Client.getApiClient().getJSON().serialize(record));
        // TODO consider to retry if receiving a 409 code
        V1ConfigMap replacedConfigMap = coreV1Client.replaceNamespacedConfigMap(name, namespace, configMap, null, null, null, null);
        configMapRefer.set(replacedConfigMap);
        return true;
    } catch (ApiException e) {
        if (e.getCode() == HttpURLConnection.HTTP_CONFLICT) {
            log.debug("received {} when updating configmap lock", e.getCode(), e);
        } else {
            log.error("received {} when updating configmap lock", e.getCode(), e);
        }
        return false;
    }
}
Also used : V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) ApiException(io.kubernetes.client.openapi.ApiException)

Example 19 with ApiException

use of io.kubernetes.client.openapi.ApiException in project java by kubernetes-client.

the class DeploymentHelper method listReplicaSets.

/**
 * listReplicaSets returns a list of RSes the given deployment targets. Note that this does NOT
 * attempt to reconcile ControllerRef (adopt/orphan), because only the controller itself should do
 * that. However, it does filter out anything whose ControllerRef doesn't match.
 */
private static List<V1ReplicaSet> listReplicaSets(V1Deployment deployment, AppsV1Api api) throws ApiException {
    String namespace = deployment.getMetadata().getNamespace();
    LabelSelector selector = LabelSelector.parse(deployment.getSpec().getSelector());
    List<V1ReplicaSet> all = rsListFromClient(namespace, selector.toString(), api);
    List<V1ReplicaSet> owned = new ArrayList<>(all.size());
    for (V1ReplicaSet rs : all) {
        List<V1OwnerReference> refs = rs.getMetadata().getOwnerReferences();
        Optional<V1OwnerReference> ref = refs.stream().filter(o -> o.getController() != null && o.getController()).findAny();
        // Only include those whose ControllerRef matches the Deployment.
        if (ref.isPresent() && ref.get().getUid().equals(deployment.getMetadata().getUid())) {
            owned.add(rs);
        }
    }
    return owned;
}
Also used : V1ReplicaSet(io.kubernetes.client.openapi.models.V1ReplicaSet) V1PodTemplateSpec(io.kubernetes.client.openapi.models.V1PodTemplateSpec) Yaml(io.kubernetes.client.util.Yaml) LabelSelector(io.kubernetes.client.util.labels.LabelSelector) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) ArrayList(java.util.ArrayList) Objects(java.util.Objects) ApiException(io.kubernetes.client.openapi.ApiException) List(java.util.List) V1ReplicaSetList(io.kubernetes.client.openapi.models.V1ReplicaSetList) V1OwnerReference(io.kubernetes.client.openapi.models.V1OwnerReference) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) Optional(java.util.Optional) V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) ArrayList(java.util.ArrayList) LabelSelector(io.kubernetes.client.util.labels.LabelSelector) V1OwnerReference(io.kubernetes.client.openapi.models.V1OwnerReference) V1ReplicaSet(io.kubernetes.client.openapi.models.V1ReplicaSet)

Example 20 with ApiException

use of io.kubernetes.client.openapi.ApiException in project java by kubernetes-client.

the class EndpointsLock method update.

@Override
public boolean update(LeaderElectionRecord record) {
    try {
        V1Endpoints endpoints = endpointsRefer.get();
        endpoints.getMetadata().putAnnotationsItem(LeaderElectionRecordAnnotationKey, coreV1Client.getApiClient().getJSON().serialize(record));
        // TODO consider to retry if receiving a 409 code
        V1Endpoints replacedEndpoints = coreV1Client.replaceNamespacedEndpoints(name, namespace, endpoints, null, null, null, null);
        endpointsRefer.set(replacedEndpoints);
        return true;
    } catch (ApiException e) {
        if (e.getCode() == HttpURLConnection.HTTP_CONFLICT) {
            log.debug("received {} when updating endpoints lock", e.getCode(), e);
        } else {
            log.error("received {} when updating endpoints lock", e.getCode(), e);
        }
        return false;
    }
}
Also used : V1Endpoints(io.kubernetes.client.openapi.models.V1Endpoints) ApiException(io.kubernetes.client.openapi.ApiException)

Aggregations

ApiException (io.kubernetes.client.openapi.ApiException)82 V1Pod (io.kubernetes.client.openapi.models.V1Pod)21 IOException (java.io.IOException)21 V1PodList (io.kubernetes.client.openapi.models.V1PodList)18 Test (org.junit.Test)18 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)17 KubectlException (io.kubernetes.client.extended.kubectl.exception.KubectlException)14 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)13 ApiClient (io.kubernetes.client.openapi.ApiClient)10 AppsV1Api (io.kubernetes.client.openapi.apis.AppsV1Api)10 V1ConfigMap (io.kubernetes.client.openapi.models.V1ConfigMap)8 V1Deployment (io.kubernetes.client.openapi.models.V1Deployment)8 V1ListMeta (io.kubernetes.client.openapi.models.V1ListMeta)8 V1Status (io.kubernetes.client.openapi.models.V1Status)8 CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)8 Watch (io.kubernetes.client.util.Watch)8 List (java.util.List)8 Configuration (io.kubernetes.client.openapi.Configuration)6 HashMap (java.util.HashMap)6 V1Patch (io.kubernetes.client.custom.V1Patch)5