-
Notifications
You must be signed in to change notification settings - Fork 9
/
clusternamespace.go
337 lines (275 loc) · 11.3 KB
/
clusternamespace.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package kubernetes
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"sort"
"time"
"google.golang.org/protobuf/types/known/anypb"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"namespacelabs.dev/foundation/framework/kubernetes/kubedef"
"namespacelabs.dev/foundation/internal/artifacts/oci"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/runtime"
"namespacelabs.dev/foundation/internal/runtime/kubernetes/kubeobserver"
runtimepb "namespacelabs.dev/foundation/schema/runtime"
"namespacelabs.dev/foundation/schema/storage"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/std/tasks"
fnschema "namespacelabs.dev/foundation/schema"
)
type ClusterNamespace struct {
cluster *Cluster
target clusterTarget
}
type clusterTarget struct {
env *fnschema.Environment
namespace string
}
var _ runtime.ClusterNamespace = &ClusterNamespace{}
var _ kubedef.KubeClusterNamespace = &ClusterNamespace{}
func ConnectToNamespace(ctx context.Context, env cfg.Context) (*ClusterNamespace, error) {
cluster, err := ConnectToCluster(ctx, env.Configuration())
if err != nil {
return nil, err
}
bound, err := cluster.Bind(env)
if err != nil {
return nil, err
}
return bound.(*ClusterNamespace), nil
}
func (r *ClusterNamespace) KubeConfig() kubedef.KubeConfig {
return kubedef.KubeConfig{
Context: r.cluster.computedClient.HostEnv.GetContext(),
Environment: r.target.env,
Namespace: r.target.namespace,
}
}
func (cn *ClusterNamespace) Cluster() runtime.Cluster {
return cn.cluster
}
func (cn *ClusterNamespace) Planner() runtime.Planner {
return Planner{fetchSystemInfo: cn.cluster.SystemInfo, target: cn.target}
}
func (r *ClusterNamespace) FetchEnvironmentDiagnostics(ctx context.Context) (*storage.EnvironmentDiagnostics, error) {
systemInfo, err := r.cluster.SystemInfo(ctx)
if err != nil {
return nil, err
}
events, err := r.cluster.cli.CoreV1().Events(r.target.namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fnerrors.New("kubernetes: failed to obtain event list: %w", err)
}
// Ignore failures, this is best effort.
eventsBytes, _ := json.Marshal(events)
kube := &kubedef.KubernetesEnvDiagnostics{
SystemInfo: systemInfo,
SerializedEventList: string(eventsBytes),
}
diag := &storage.EnvironmentDiagnostics{Runtime: "kubernetes"}
serializedKube, err := anypb.New(kube)
if err != nil {
return nil, fnerrors.New("kubernetes: failed to serialize KubernetesEnvDiagnostics")
}
diag.RuntimeSpecific = append(diag.RuntimeSpecific, serializedKube)
return diag, nil
}
func (r *ClusterNamespace) startTerminal(ctx context.Context, cli *kubernetes.Clientset, server runtime.Deployable, rio runtime.TerminalIO, cmd []string) error {
pod, err := r.resolvePod(ctx, cli, rio.Stderr, server)
if err != nil {
return err
}
return r.cluster.lowLevelAttachTerm(ctx, cli, pod.Namespace, pod.Name, rio, "exec", &corev1.PodExecOptions{
Command: cmd,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: rio.TTY,
})
}
func (r *ClusterNamespace) Observe(ctx context.Context, srv runtime.Deployable, opts runtime.ObserveOpts, onInstance func(runtime.ObserveEvent) error) error {
// XXX use a watch
announced := map[string]*runtimepb.ContainerReference{}
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
// No cancelation, moving along.
}
pods, err := r.cluster.cli.CoreV1().Pods(r.target.namespace).List(ctx, metav1.ListOptions{
LabelSelector: kubedef.SerializeSelector(kubedef.SelectById(srv)),
})
if err != nil {
return fnerrors.Wrapf(nil, err, "unable to list pods")
}
type Key struct {
Instance *runtimepb.ContainerReference
CreatedAt time.Time // used for sorting
}
keys := []Key{}
newM := map[string]struct{}{}
labels := map[string]string{}
for _, pod := range pods.Items {
if pod.Status.Phase == corev1.PodRunning {
instance := kubedef.MakePodRef(r.target.namespace, pod.Name, kubedef.ServerCtrName(srv), srv)
keys = append(keys, Key{
Instance: instance,
CreatedAt: pod.CreationTimestamp.Time,
})
newM[instance.UniqueId] = struct{}{}
labels[instance.UniqueId] = fmt.Sprintf("%s (%s)", srv.GetName(), pod.ResourceVersion)
if ObserveInitContainerLogs {
for _, container := range pod.Spec.InitContainers {
instance := kubedef.MakePodRef(r.target.namespace, pod.Name, container.Name, srv)
keys = append(keys, Key{Instance: instance, CreatedAt: pod.CreationTimestamp.Time})
newM[instance.UniqueId] = struct{}{}
labels[instance.UniqueId] = fmt.Sprintf("%s:%s (%s)", srv.GetName(), container.Name, pod.ResourceVersion)
}
}
}
}
sort.SliceStable(keys, func(i int, j int) bool {
return keys[i].CreatedAt.Before(keys[j].CreatedAt)
})
for k, ref := range announced {
if _, ok := newM[k]; ok {
delete(newM, k)
} else {
if err := onInstance(runtime.ObserveEvent{ContainerReference: ref, Removed: true}); err != nil {
return err
}
// The previously announced pod is not present in the current list and is already announced as `Removed`.
delete(announced, k)
}
}
for _, key := range keys {
instance := key.Instance
if _, ok := newM[instance.UniqueId]; !ok {
continue
}
human := labels[instance.UniqueId]
if human == "" {
human = instance.HumanReference
}
if err := onInstance(runtime.ObserveEvent{ContainerReference: instance, HumanReadableID: human, Added: true}); err != nil {
return err
}
announced[instance.UniqueId] = instance
}
if opts.OneShot {
return nil
}
time.Sleep(1 * time.Second)
}
}
func (r *ClusterNamespace) WaitForTermination(ctx context.Context, object runtime.Deployable) ([]runtime.ContainerStatus, error) {
if object.GetDeployableClass() != string(fnschema.DeployableClass_ONESHOT) && object.GetDeployableClass() != string(fnschema.DeployableClass_MANUAL) {
return nil, fnerrors.InternalError("WaitForTermination: only support one-shot deployments")
}
cli := r.cluster.cli
namespace := r.target.namespace
podName := kubedef.MakeDeploymentId(object)
return kubeobserver.WatchDeployable(ctx, "deployable.wait-until-done", cli, namespace, object, func(pod corev1.Pod) ([]runtime.ContainerStatus, bool) {
if pod.Status.Phase != corev1.PodFailed && pod.Status.Phase != corev1.PodSucceeded {
return nil, false
}
var all []corev1.ContainerStatus
all = append(all, pod.Status.ContainerStatuses...)
all = append(all, pod.Status.InitContainerStatuses...)
var status []runtime.ContainerStatus
for _, container := range all {
st := runtime.ContainerStatus{
Reference: kubedef.MakePodRef(namespace, podName, container.Name, object),
}
if container.State.Terminated != nil {
if container.State.Terminated.ExitCode != 0 {
st.TerminationError = runtime.ErrContainerExitStatus{ExitCode: container.State.Terminated.ExitCode}
}
}
status = append(status, st)
}
return status, true
})
}
func (r *ClusterNamespace) ForwardPort(ctx context.Context, server runtime.Deployable, containerPort int32, localAddrs []string, callback runtime.SinglePortForwardedFunc) (io.Closer, error) {
if containerPort <= 0 {
return nil, fnerrors.BadInputError("invalid port number: %d", containerPort)
}
return r.cluster.RawForwardPort(ctx, server.GetPackageName(), r.target.namespace, kubedef.SelectById(server), int(containerPort), localAddrs, callback)
}
func (r *ClusterNamespace) DialServer(ctx context.Context, server runtime.Deployable, containerPort int32) (net.Conn, error) {
if containerPort <= 0 {
return nil, fnerrors.BadInputError("invalid port number: %d", containerPort)
}
return r.cluster.RawDialServer(ctx, r.target.namespace, kubedef.SelectById(server), int(containerPort))
}
func (r *ClusterNamespace) ResolveContainers(ctx context.Context, object runtime.Deployable) ([]*runtimepb.ContainerReference, error) {
return kubeobserver.WatchDeployable(ctx, "deployable.resolve-containers", r.cluster.cli, r.target.namespace, object,
func(pod corev1.Pod) ([]*runtimepb.ContainerReference, bool) {
if pod.Status.Phase != corev1.PodRunning && pod.Status.Phase != corev1.PodFailed && pod.Status.Phase != corev1.PodSucceeded {
return nil, false
}
var refs []*runtimepb.ContainerReference
for _, init := range pod.Status.InitContainerStatuses {
refs = append(refs, kubedef.MakePodRef(pod.Namespace, pod.Name, init.Name, object))
}
for _, container := range pod.Status.ContainerStatuses {
refs = append(refs, kubedef.MakePodRef(pod.Namespace, pod.Name, container.Name, object))
}
return refs, true
})
}
func (r *ClusterNamespace) resolvePod(ctx context.Context, cli *kubernetes.Clientset, w io.Writer, obj runtime.Deployable) (corev1.Pod, error) {
return resolvePodByLabels(ctx, cli, w, r.target.namespace, kubedef.SelectById(obj))
}
func (r *ClusterNamespace) DeployedConfigImageID(ctx context.Context, server runtime.Deployable) (oci.ImageID, error) {
return tasks.Return(ctx, tasks.Action("kubernetes.resolve-config-image-id").Scope(fnschema.PackageName(server.GetPackageName())),
func(ctx context.Context) (oci.ImageID, error) {
// XXX need a StatefulSet variant.
d, err := r.cluster.cli.AppsV1().Deployments(r.target.namespace).Get(ctx, kubedef.MakeDeploymentId(server), metav1.GetOptions{})
if err != nil {
// XXX better error messages.
return oci.ImageID{}, err
}
cfgimage, ok := d.Annotations[kubedef.K8sConfigImage]
if !ok {
return oci.ImageID{}, fnerrors.BadInputError("%s: %q is missing as an annotation in %q",
server.GetPackageName(), kubedef.K8sConfigImage, kubedef.MakeDeploymentId(server))
}
imgid, err := oci.ParseImageID(cfgimage)
if err != nil {
return imgid, err
}
tasks.Attachments(ctx).AddResult("ref", imgid.ImageRef())
return imgid, nil
})
}
func (r *ClusterNamespace) StartTerminal(ctx context.Context, server runtime.Deployable, rio runtime.TerminalIO, command string, rest ...string) error {
cmd := append([]string{command}, rest...)
return r.startTerminal(ctx, r.cluster.cli, server, rio, cmd)
}
func (r *ClusterNamespace) DeleteRecursively(ctx context.Context, wait bool) (bool, error) {
return DeleteAllRecursively(ctx, r.cluster.cli, wait, nil, r.target.namespace)
}
func (r *ClusterNamespace) DeleteDeployable(ctx context.Context, deployable runtime.Deployable) error {
listOpts := metav1.ListOptions{LabelSelector: kubedef.SerializeSelector(kubedef.SelectById(deployable))}
switch deployable.GetDeployableClass() {
case string(fnschema.DeployableClass_ONESHOT), string(fnschema.DeployableClass_MANUAL):
return r.cluster.cli.CoreV1().Pods(r.target.namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, listOpts)
case string(fnschema.DeployableClass_STATEFUL):
return r.cluster.cli.AppsV1().StatefulSets(r.target.namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, listOpts)
case string(fnschema.DeployableClass_STATELESS):
return r.cluster.cli.AppsV1().Deployments(r.target.namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, listOpts)
default:
return fnerrors.InternalError("%s: unsupported deployable class", deployable.GetDeployableClass())
}
}