-
Notifications
You must be signed in to change notification settings - Fork 9
/
watcher.go
63 lines (51 loc) · 1.83 KB
/
watcher.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
// 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 kubeobserver
import (
"context"
"fmt"
"reflect"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8s "k8s.io/client-go/kubernetes"
"namespacelabs.dev/foundation/framework/kubernetes/kubedef"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/runtime"
"namespacelabs.dev/foundation/std/tasks"
)
func WatchDeployable[V any](ctx context.Context, actionName string, cli *k8s.Clientset, namespace string, object runtime.Deployable, callback func(corev1.Pod) (V, bool, error)) (V, error) {
return tasks.Return(ctx, tasks.Action(actionName).Arg("id", object.GetId()).Arg("name", object.GetName()),
func(ctx context.Context) (V, error) {
return WatchPods(ctx, cli, namespace, kubedef.SelectById(object), callback)
})
}
func WatchPods[V any](ctx context.Context, cli *k8s.Clientset, namespace string, labels map[string]string, callback func(corev1.Pod) (V, bool, error)) (V, error) {
var empty V
for {
w, err := cli.CoreV1().Pods(namespace).Watch(ctx, metav1.ListOptions{LabelSelector: kubedef.SerializeSelector(labels)})
if err != nil {
return empty, fnerrors.InvocationError("kubernetes", "failed while waiting for pod: %w", err)
}
defer w.Stop()
debug := console.Debug(ctx)
for ev := range w.ResultChan() {
if ev.Object == nil {
continue
}
pod, ok := ev.Object.(*corev1.Pod)
if !ok {
fmt.Fprintf(debug, "received non-pod event: %v\n", reflect.TypeOf(ev.Object))
continue
}
v, done, err := callback(*pod)
if err != nil {
return v, err
}
if done {
return v, nil
}
}
}
}