This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
/
kubelet.go
95 lines (80 loc) · 2.64 KB
/
kubelet.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
86
87
88
89
90
91
92
93
94
95
package k8s
import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"github.com/containernetworking/cni/pkg/types"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
)
func PodKey(pod *corev1.Pod) string {
return pod.Name
}
func ToPodList(body []byte) (*corev1.PodList, error) {
deserializer := serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer()
podListObject, _, err := deserializer.Decode(body, nil, &corev1.PodList{})
if err != nil {
err = errors.Wrap(err, "Cannot deserialize podlist from kubelet")
return nil, err
}
podList, ok := podListObject.(*corev1.PodList)
if !ok {
return nil, fmt.Errorf("Could not cast podlistobject, as it's type is: %s", podListObject.GetObjectKind().GroupVersionKind().String())
}
return podList, nil
}
func GetPod(ctx context.Context, url string, args Args) (*corev1.Pod, error) {
body, err := Get(ctx, url)
if err != nil {
return nil, errors.Wrap(err, "Unable to fetch from Kubernetes URL")
}
podList, err := ToPodList(body)
if err != nil {
return nil, errors.Wrap(err, "Unable deserialize pods body from kubelet")
}
namespace := string(args.K8S_POD_NAMESPACE)
name := string(args.K8S_POD_NAME)
for idx := range podList.Items {
pod := podList.Items[idx]
if pod.Namespace == namespace && pod.Name == name {
return &pod, nil
}
}
err = fmt.Errorf("Could not find pod %s, in namespace %s", name, namespace)
return nil, err
}
func Get(ctx context.Context, url string) ([]byte, error) {
customTransport := &http.Transport{
MaxIdleConns: 0,
// The certificate that the VK loads isn't reloaded periodically, so it can go stale. Therefore,
// the easiest option is to skip verify, especially because it's on localhost.
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // nolint: gosec
}
client := &http.Client{
Transport: customTransport,
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
req.Header.Add("Accept", "application/json")
if err != nil {
return nil, errors.Wrap(err, "Unable to create new request")
}
resp, err := client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "Unable to do request")
}
defer func() {
_ = resp.Body.Close()
}()
return ioutil.ReadAll(resp.Body)
}
// Refer https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/dockershim/network/cni/cni.go#L392
type Args struct {
types.CommonArgs
K8S_POD_NAME types.UnmarshallableString // nolint:golint
K8S_POD_NAMESPACE types.UnmarshallableString // nolint:golint
K8S_POD_INFRA_CONTAINER_ID types.UnmarshallableString // nolint:golint
}