2022-09-05 04:01:14 +00:00
|
|
|
package kubernetes
|
|
|
|
|
|
|
|
import (
|
2023-03-21 19:00:45 +00:00
|
|
|
"errors"
|
2022-09-05 04:01:14 +00:00
|
|
|
"os"
|
2023-03-21 19:00:45 +00:00
|
|
|
"regexp"
|
2022-09-05 04:01:14 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
v1 "k8s.io/api/core/v1"
|
|
|
|
"k8s.io/client-go/kubernetes"
|
|
|
|
"k8s.io/client-go/rest"
|
|
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
|
|
)
|
|
|
|
|
2023-03-21 19:00:45 +00:00
|
|
|
var (
|
|
|
|
dnsPattern = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`)
|
|
|
|
ErrDNSPatternInvalid = errors.New("name is not a valid kubernetes DNS name")
|
|
|
|
)
|
|
|
|
|
|
|
|
func dnsName(i string) (string, error) {
|
|
|
|
res := strings.Replace(i, "_", "-", -1)
|
|
|
|
|
|
|
|
if found := dnsPattern.FindStringIndex(res); found == nil {
|
|
|
|
return "", ErrDNSPatternInvalid
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
2022-09-05 04:01:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func isImagePullBackOffState(pod *v1.Pod) bool {
|
|
|
|
for _, containerState := range pod.Status.ContainerStatuses {
|
|
|
|
if containerState.State.Waiting != nil {
|
|
|
|
if containerState.State.Waiting.Reason == "ImagePullBackOff" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// getClientOutOfCluster returns a k8s clientset to the request from outside of cluster
|
|
|
|
func getClientOutOfCluster() (kubernetes.Interface, error) {
|
|
|
|
kubeconfigPath := os.Getenv("KUBECONFIG")
|
|
|
|
if kubeconfigPath == "" {
|
|
|
|
kubeconfigPath = os.Getenv("HOME") + "/.kube/config"
|
|
|
|
}
|
|
|
|
|
|
|
|
// use the current context in kubeconfig
|
|
|
|
config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
|
|
|
|
if err != nil {
|
2023-03-20 23:48:15 +00:00
|
|
|
return nil, err
|
2022-09-05 04:01:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return kubernetes.NewForConfig(config)
|
|
|
|
}
|
|
|
|
|
|
|
|
// getClient returns a k8s clientset to the request from inside of cluster
|
|
|
|
func getClientInsideOfCluster() (kubernetes.Interface, error) {
|
|
|
|
config, err := rest.InClusterConfig()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return kubernetes.NewForConfig(config)
|
|
|
|
}
|