blob: a05d4c1aeb94912d2c2fa3ab1ba3982da04ce8eb [file] [log] [blame]
package mirko
import (
"sync"
"github.com/golang/glog"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
// kubernetesCS is a kubernetes clientset that can connect to the cluster
// that this program is running in, or nil if uninitialized (or not in a
// cluster.
kubernetesCS *kubernetes.Clientset
// kubernetesCSValid is true when kubernetesCS is 'valid', ie. when the
// clientset is either an actual clientset object, or nil if the program is
// not running in production.
kubernetesCSValid bool
// kubernetesCSMu guards kubernetesCS and kubernetesCSValid.
kubernetesCSMu sync.Mutex
)
// KubernetesClient attempts to connect to Kubernetes using in-cluster
// configuration and returns the resulting clientset. If connecting fails, nil
// is returned. Connection will fail if the program is not running in
// production.
// The connection result is cached for the rest of the program lifetime, so
// this function is cheap to call.
func KubernetesClient() *kubernetes.Clientset {
kubernetesCSMu.Lock()
defer kubernetesCSMu.Unlock()
if kubernetesCSValid {
return kubernetesCS
}
kubernetesCSValid = true
config, err := rest.InClusterConfig()
if err != nil {
glog.Errorf("Kubernetes InClusterConfig: %v", err)
glog.Infof("Mirko: no kubernetes config available...")
return nil
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Errorf("Kubernetes NewForConfig: %v", err)
glog.Infof("Mirko: no kubernetes client available...")
return nil
}
kubernetesCS = clientset
return clientset
}