/
k8sapi.go
85 lines (76 loc) · 2.26 KB
/
k8sapi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package k8sapi
import (
"context"
"fmt"
"strings"
"github.com/4armed/kubeshot/internal/config"
"github.com/kubicorn/kubicorn/pkg/logger"
// "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// GetURLs queries the Kubernetes API to get URLs and returns an array
func GetURLs(c *config.Config) ([]string, error) {
var urls []string
var clusterConfig *rest.Config
var err error
if len(c.KubeConfig) > 0 {
clusterConfig, err = clientcmd.BuildConfigFromFlags("", c.KubeConfig)
if err != nil {
return nil, err
}
} else {
// creates the in-cluster config
clusterConfig, err = rest.InClusterConfig()
if err != nil {
return nil, err
}
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(clusterConfig)
if err != nil {
panic(err.Error())
}
if c.GetK8sPods {
logger.Info("Fetching pods from Kubernetes API")
// not implemented yet
}
if c.GetK8sSvcs {
logger.Info("Fetching services from Kubernetes API")
var urls []string
svcs, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, err
}
logger.Info("Counted %d services", len(svcs.Items))
for _, service := range svcs.Items {
logger.Debug("service name: %v", service.Name)
if service.Spec.Type == "ClusterIP" {
if service.Spec.ClusterIP != "None" {
for _, port := range service.Spec.Ports {
if port.Protocol == "TCP" {
// Try and guess the correct protocol, http or https
if strings.HasPrefix(port.Name, "https") || port.Port == 443 {
url := fmt.Sprintf("https://%v:%d", service.Spec.ClusterIP, port.Port)
urls = append(urls, url)
} else if port.Port == 80 {
url := fmt.Sprintf("http://%v:%d", service.Spec.ClusterIP, port.Port)
urls = append(urls, url)
} else {
// Add both
httpUrl := fmt.Sprintf("http://%v:%d", service.Spec.ClusterIP, port.Port)
httpsUrl := fmt.Sprintf("https://%v:%d", service.Spec.ClusterIP, port.Port)
urls = append(urls, httpUrl, httpsUrl)
}
}
}
}
}
}
return urls, err
}
return urls, nil
}