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

io.kubernetes.client.util.KubeConfig Maven / Gradle / Ivy

The newest version!
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.util;

import io.kubernetes.client.util.authenticators.Authenticator;
import org.apache.log4j.Logger;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * KubeConfig represents a kubernetes client configuration
 */
public class KubeConfig {
    // Defaults for where to find a kubeconfig file
    public static final String ENV_HOME = "HOME";
    public static final String KUBEDIR = ".kube";
    public static final String KUBECONFIG = "config";
    private static Map authenticators = new HashMap<>();

    // Note to the reader: I considered creating a Config object
    // and parsing into that instead of using Maps, but honestly
    // this seemed cleaner than a bunch of boilerplate classes

    private ArrayList clusters;
    private ArrayList contexts;
    private ArrayList users;
    Map currentContext;
    Map currentCluster;
    Map currentUser;

    private static final Logger log = Logger.getLogger(KubeConfig.class);

    public static void registerAuthenticator(Authenticator auth) {
        synchronized (authenticators) {
            authenticators.put(auth.getName(), auth);
        }
    }

    /**
     * Load a Kubernetes config from the default location
     */
    public static KubeConfig loadDefaultKubeConfig() throws FileNotFoundException {
        File config = new File(new File(System.getenv(ENV_HOME), KUBEDIR), KUBECONFIG);
        if (!config.exists()) {
            return null;
        }
        return loadKubeConfig(new FileReader(config));
    }

    /**
     * Load a Kubernetes config from a Reader
     */
    public static KubeConfig loadKubeConfig(Reader input) {
        Yaml yaml = new Yaml(new SafeConstructor());
        Object config = yaml.load(input);
        Map configMap = (Map)config;

        String currentContext = (String)configMap.get("current-context");
        ArrayList contexts = (ArrayList)configMap.get("contexts");
        ArrayList clusters = (ArrayList)configMap.get("clusters");
        ArrayList users = (ArrayList)configMap.get("users");

        KubeConfig kubeConfig = new KubeConfig(contexts, clusters, users);
        kubeConfig.setContext(currentContext);

        return kubeConfig;
    }

    public KubeConfig(ArrayList contexts,
        ArrayList clusters,
        ArrayList users) {
        this.contexts = contexts;
        this.clusters = clusters;
        this.users = users;
    }

    public boolean setContext(String context) {
        currentCluster = null;
        currentUser = null;
        Map ctx = findObject(contexts, context);
        if (ctx == null) {
            return false;
        }
        currentContext = (Map) ctx.get("context");
        if (currentContext == null) {
            return false;
        }
        String cluster = (String) currentContext.get("cluster");
        String user = (String) currentContext.get("user");

        if (cluster != null) {
            Map obj = findObject(clusters, cluster);
            if (obj != null) {
                currentCluster = (Map) obj.get("cluster");
            }
        }
        if (user != null) {
            Map obj = findObject(users, user);
            if (obj != null) {
                currentUser = (Map) obj.get("user");
            }
        }
        return true;
    }

    public String getServer() {
        return getData(currentCluster, "server");
    }

    public String getCertificateAuthorityData() {
        return getData(currentCluster, "certificate-authority-data");
    }

    public String getCertificateAuthorityFile() {
        return getData(currentCluster, "certificate-authority");
    }

    public String getClientCertificateFile() {
        return getData(currentUser, "client-certificate");
    }

    public String getClientCertificateData() {
        return getData(currentUser, "client-certificate-data");
    }

    public String getClientKeyFile() {
        return getData(currentUser, "client-key");
    }

    public String getClientKeyData() {
        return getData(currentUser, "client-key-data");
    }

    public String getUsername() {
        return getData(currentUser, "username");
    }

    public String getPassword() {
        return getData(currentUser, "password");
    }

    public String getAccessToken() {
        if (currentUser == null) {
            return null;
        } 
        
        Object authProvider = currentUser.get("auth-provider");
        if (authProvider != null) {            Map authProviderMap = (Map) authProvider;
            Map authConfig = (Map) authProviderMap.get("config");
            if (authConfig != null) {
                String name = (String) authProviderMap.get("name");
                Authenticator auth = authenticators.get(name);
                System.out.println(auth + " for " + name);                
                if (auth != null) {
                    if (auth.isExpired(authConfig)) {
                        authConfig = auth.refresh(authConfig);
                        // TODO persist things here.
                    }
                    return auth.getToken(authConfig);
                }
            }
        }
        if (currentUser.containsKey("token")) {
            return (String) currentUser.get("token");
        }
        if (currentUser.containsKey("tokenFile")) {
            String tokenFile = (String) currentUser.get("tokenFile");
            try {
                byte[] data = Files.readAllBytes(FileSystems.getDefault().getPath(tokenFile));
                return new String(data, "UTF-8");
            } catch (IOException ex) {
                log.error("Failed to read token file", ex);
            }
        }
        return null;
    }

    public boolean verifySSL() {
        if (currentCluster.containsKey("insecure-skip-tls-verify")) {
            return ! ((Boolean) currentCluster.get("insecure-skip-tls-verify")).booleanValue();
        }
        return true;
    }

    private static String getData(Map obj, String key) {
        if (obj == null) {
            return null;
        }
        return (String) obj.get(key);
    }
    
    private static Map findObject(ArrayList list, String name) {
        if (list == null) {
            return null;
        }
        for (Object obj : list) {
            Map map = (Map)obj;
            if (name.equals((String)map.get("name"))) {
                return map;
            }
        }
        return null;
    }
}