-
Notifications
You must be signed in to change notification settings - Fork 7
/
kubeclient.go
221 lines (196 loc) · 6.75 KB
/
kubeclient.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Copyright 2024 Edgeless Systems GmbH
// SPDX-License-Identifier: AGPL-3.0-only
/*
The kubeclient package provides a simple wrapper around Kubernetes interactions
commonly used in the e2e tests.
*/
package kubeclient
import (
"bytes"
"context"
"fmt"
"log/slog"
"net/http"
"os"
"testing"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
)
// A Kubeclient offers a communication interface to a Kubernetes cluster.
type Kubeclient struct {
log *slog.Logger
// client is the underlying Kubernetes client.
client *kubernetes.Clientset
// restMapper allows to look up schema information for dynamic resources
restMapper meta.RESTMapper
// config is the "Kubeconfig" for the client
config *rest.Config
}
// New creates a new Kubeclient from a given Kubeconfig.
func New(config *rest.Config, log *slog.Logger) (*Kubeclient, error) {
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("creating kubernetes client: %w", err)
}
resources, err := restmapper.GetAPIGroupResources(client.Discovery())
if err != nil {
return nil, fmt.Errorf("getting resource groups: %w", err)
}
return &Kubeclient{
log: log,
client: client,
config: config,
restMapper: restmapper.NewDiscoveryRESTMapper(resources),
}, nil
}
// NewFromConfigFile creates a new Kubeclient for a given Kubeconfig file.
func NewFromConfigFile(configPath string, log *slog.Logger) (*Kubeclient, error) {
config, err := clientcmd.BuildConfigFromFlags("", configPath)
if err != nil {
return nil, fmt.Errorf("creating config from file: %w", err)
}
return New(config, log)
}
// NewForTest creates a Kubeclient with parameters suitable for e2e testing.
func NewForTest(t *testing.T) *Kubeclient {
t.Helper()
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
configFile := os.Getenv("KUBECONFIG")
if configFile == "" {
configFile = clientcmd.RecommendedHomeFile
}
c, err := NewFromConfigFile(configFile, log)
if err != nil {
t.Fatalf("Could not create Kubeclient: %v", err)
}
return c
}
// PodsFromDeployment returns the pods from a deployment in a namespace.
//
// A pod is considered to belong to a deployment if it is owned by a ReplicaSet which is in turn
// owned by the Deployment in question.
func (c *Kubeclient) PodsFromDeployment(ctx context.Context, namespace, deployment string) ([]v1.Pod, error) {
replicasets, err := c.client.AppsV1().ReplicaSets(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("listing replicasets: %w", err)
}
pods, err := c.client.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("listing pods: %w", err)
}
var out []v1.Pod
for _, replicaset := range replicasets.Items {
for _, ref := range replicaset.OwnerReferences {
if ref.Kind != "Deployment" || ref.Name != deployment {
continue
}
for _, pod := range pods.Items {
for _, ref := range pod.OwnerReferences {
if ref.Kind == "ReplicaSet" && ref.UID == replicaset.UID {
out = append(out, pod)
}
}
}
}
}
return out, nil
}
// PodsFromOwner returns the pods owned by an object in the namespace of the given kind.
func (c *Kubeclient) PodsFromOwner(ctx context.Context, namespace, kind, name string) ([]v1.Pod, error) {
pods, err := c.client.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("listing pods: %w", err)
}
var out []v1.Pod
for _, pod := range pods.Items {
for _, ref := range pod.OwnerReferences {
if ref.Kind == kind && ref.Name == name {
out = append(out, pod)
}
}
}
return out, nil
}
// Exec executes a process in a pod and returns the stdout and stderr.
func (c *Kubeclient) Exec(ctx context.Context, namespace, pod string, argv []string) (
stdout string, stderr string, err error,
) {
buf := &bytes.Buffer{}
errBuf := &bytes.Buffer{}
request := c.client.CoreV1().RESTClient().
Post().
Namespace(namespace).
Resource("pods").
Name(pod).
SubResource("exec").
VersionedParams(&v1.PodExecOptions{
Command: argv,
Stdin: false,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(c.config, http.MethodPost, request.URL())
if err != nil {
return "", "", fmt.Errorf("creating executor: %w", err)
}
err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{
Stdout: buf,
Stderr: errBuf,
Tty: false,
})
return buf.String(), errBuf.String(), err
}
// ExecDeployment executes a process in one of the deployment's pods.
func (c *Kubeclient) ExecDeployment(ctx context.Context, namespace, deployment string, argv []string) (stdout string, stderr string, err error) {
if err := c.WaitFor(ctx, Deployment{}, namespace, deployment); err != nil {
return "", "", fmt.Errorf("deployment not ready: %w", err)
}
pods, err := c.PodsFromDeployment(ctx, namespace, deployment)
if err != nil {
return "", "", fmt.Errorf("could not get pods for deployment %s/%s: %w", namespace, deployment, err)
}
if len(pods) == 0 {
return "", "", fmt.Errorf("no pods found for deployment %s/%s", namespace, deployment)
}
return c.Exec(ctx, namespace, pods[0].Name, argv)
}
// LogDebugInfo collects pod information from the cluster and writes it to the logger.
func (c *Kubeclient) LogDebugInfo(ctx context.Context) {
namespaces, err := c.client.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
if err != nil {
c.log.Error("Could not get namespaces", "error", err)
return
}
for _, namespace := range namespaces.Items {
c.log.Debug("Collecting debug info for pods", "namespace", namespace.Name)
pods, err := c.client.CoreV1().Pods(namespace.Name).List(ctx, metav1.ListOptions{})
if err != nil {
c.log.Error("Could not get pods", "namespace", namespace.Name, "error", err)
continue
}
for _, pod := range pods.Items {
c.logContainerStatus(pod)
}
}
}
func (c *Kubeclient) logContainerStatus(pod v1.Pod) {
c.log.Debug("pod status", "name", pod.Name, "phase", pod.Status.Phase, "reason", pod.Status.Reason, "message", pod.Status.Message)
for containerType, containers := range map[string][]v1.ContainerStatus{
"init": pod.Status.InitContainerStatuses,
"main": pod.Status.ContainerStatuses,
"ephemeral": pod.Status.EphemeralContainerStatuses,
} {
log := c.log.With("pod", pod.Name, "type", containerType)
for _, container := range containers {
log.Debug("container status", "name", container.Name, "started", container.Started, "ready", container.Ready, "state", container.State)
}
}
}