All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodic.kubernetes.base.support.StandardPodOperations Maven / Gradle / Ivy

package org.zodic.kubernetes.base.support;

import java.nio.file.Paths;
import java.util.function.Supplier;

import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zodiac.sdk.toolkit.function.LazilyInstantiate;
import org.zodiac.sdk.toolkit.util.ExceptionUtil;

public class StandardPodOperations implements PodOperations {

    /**
     * Hostname environment variable name.
     */
    public static final String HOSTNAME = "HOSTNAME";

    private static final Logger LOG = LoggerFactory.getLogger(StandardPodOperations.class);

    private final KubernetesClient client;

    private final String hostName;

    private Supplier current;

    public StandardPodOperations(KubernetesClient client) {
        if (client == null) {
            throw new IllegalArgumentException("Must provide an instance of KubernetesClient");
        }

        this.client = client;
        this.hostName = System.getenv(HOSTNAME);
        this.current = LazilyInstantiate.using(() -> internalGetPod());
    }

    @Override
    public Supplier currentPod() {
        return this.current;
    }

    @Override
    public Boolean isInsideKubernetes() {
        return currentPod().get() != null;
    }

    private synchronized Pod internalGetPod() {
        try {
            if (isServiceAccountFound() && isHostNameEnvVarPresent()) {
                return this.client.pods().withName(this.hostName).get();
            } else {
                return null;
            }
        } catch (Throwable t) {
            LOG.warn("Failed to get pod with name:[{}]. You should look into this if things aren't working as you expect. Are you missing serviceaccount permissions? Caused by {} .",
                this.hostName, ExceptionUtil.stackTrace(t));
            return null;
        }
    }

    private boolean isHostNameEnvVarPresent() {
        return this.hostName != null && !this.hostName.isEmpty();
    }

    private boolean isServiceAccountFound() {
        return Paths.get(Config.KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH).toFile().exists()
            && Paths.get(Config.KUBERNETES_SERVICE_ACCOUNT_CA_CRT_PATH).toFile().exists();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy