blob: 7226423613f17d86d6aa36b02f9df44c1d1c280f [file] [log] [blame]
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"time"
"github.com/golang/glog"
pb "code.hackerspace.pl/hscloud/cluster/prodvider/proto"
)
func kubernetesPaths() (string, string, string) {
localRoot := os.Getenv("hscloud_root")
if localRoot == "" {
glog.Exitf("Please source env.sh")
}
localKey := path.Join(localRoot, ".kubectl", fmt.Sprintf("%s.key", flagUsername))
localCert := path.Join(localRoot, ".kubectl", fmt.Sprintf("%s.crt", flagUsername))
localCA := path.Join(localRoot, ".kubectl", fmt.Sprintf("ca.crt"))
return localKey, localCert, localCA
}
func needKubernetesCreds() bool {
localKey, localCert, _ := kubernetesPaths()
// Check for existence of cert/key.
if _, err := os.Stat(localKey); os.IsNotExist(err) {
return true
}
if _, err := os.Stat(localCert); os.IsNotExist(err) {
return true
}
// Cert/key exist, try to load and parse.
creds, err := tls.LoadX509KeyPair(localCert, localKey)
if err != nil {
return true
}
if len(creds.Certificate) != 1 {
return true
}
cert, err := x509.ParseCertificate(creds.Certificate[0])
if err != nil {
return true
}
creds.Leaf = cert
// Check if certificate will still be valid in 2 hours.
target := time.Now().Add(2 * time.Hour)
if creds.Leaf.NotAfter.Before(target) {
return true
}
return false
}
func useKubernetesKeys(keys *pb.KubernetesKeys) {
localKey, localCert, localCA := kubernetesPaths()
parent := filepath.Dir(localKey)
if _, err := os.Stat(parent); os.IsNotExist(err) {
os.MkdirAll(parent, 0700)
}
if err := ioutil.WriteFile(localKey, keys.Key, 0600); err != nil {
glog.Exitf("WriteFile(%q): %v", localKey, err)
}
if err := ioutil.WriteFile(localCert, keys.Cert, 0600); err != nil {
glog.Exitf("WriteFile(%q): %v", localCert, err)
}
if err := ioutil.WriteFile(localCA, keys.Ca, 0600); err != nil {
glog.Exitf("WriteFile(%q): %v", localCA, err)
}
kubectl := func(args ...string) {
cmd := exec.Command("kubectl", args...)
out, err := cmd.CombinedOutput()
if err != nil {
glog.Exitf("kubectl %v: %v: %v", args, err, string(out))
}
}
kubectl("config",
"set-cluster", keys.Cluster,
"--certificate-authority="+localCA,
"--embed-certs=true",
"--server=https://"+keys.Cluster+":4001")
kubectl("config",
"set-credentials", flagUsername,
"--client-certificate="+localCert,
"--client-key="+localKey,
"--embed-certs=true")
kubectl("config",
"set-context", keys.Cluster,
"--cluster="+keys.Cluster,
"--user="+flagUsername)
kubectl("config", "use-context", keys.Cluster)
}