-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
watcher.go
178 lines (154 loc) · 5.21 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
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
/*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"errors"
"fmt"
"sync"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log"
)
type PodWatcher interface {
Register(receiver chan<- PodEvent)
Deregister(receiver chan<- PodEvent)
Start(ctx context.Context, kubeContext string, ns []string) (func(), error)
}
// podWatcher is a pod watcher for multiple namespaces.
type podWatcher struct {
podSelector PodSelector
receivers map[chan<- PodEvent]bool
receiverLock sync.RWMutex
}
type PodEvent struct {
Type watch.EventType
Pod *v1.Pod
}
func NewPodWatcher(podSelector PodSelector) PodWatcher {
return &podWatcher{
podSelector: podSelector,
receivers: make(map[chan<- PodEvent]bool),
}
}
func (w *podWatcher) Register(receiver chan<- PodEvent) {
w.receiverLock.Lock()
w.receivers[receiver] = true
w.receiverLock.Unlock()
}
func (w *podWatcher) Deregister(receiver chan<- PodEvent) {
w.receiverLock.Lock()
w.receivers[receiver] = false
w.receiverLock.Unlock()
}
func (w *podWatcher) Start(ctx context.Context, kubeContext string, namespaces []string) (func(), error) {
if len(w.receivers) == 0 {
return func() {}, errors.New("no receiver was registered")
}
var watchers []watch.Interface
stopWatchers := func() {
for _, w := range watchers {
w.Stop()
}
}
kubeclient, err := client.Client(kubeContext)
if err != nil {
return func() {}, fmt.Errorf("getting k8s client: %w", err)
}
var forever int64 = 3600 * 24 * 365 * 100
for _, ns := range namespaces {
watcher, err := kubeclient.CoreV1().Pods(ns).Watch(context.Background(), metav1.ListOptions{
TimeoutSeconds: &forever,
})
if err != nil {
stopWatchers()
return func() {}, fmt.Errorf("initializing pod watcher for %q: %w", ns, err)
}
watchers = append(watchers, watcher)
go func() {
l := log.Entry(ctx)
defer l.Tracef("podWatcher: cease waiting")
l.Tracef("podWatcher: waiting")
for {
select {
case <-ctx.Done():
l.Tracef("podWatcher: context canceled, returning")
return
case evt, ok := <-watcher.ResultChan():
if !ok {
l.Tracef("podWatcher: channel closed, returning")
return
}
// If the event's type is "ERROR", log and continue.
if evt.Type == watch.Error {
// These errors sem to arise from the watch stream being closed from a ^C.
// evt.Object seems likely to be a https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Status
// Status{
// Status:Failure,
// Code:500,
// Reason:InternalError,
// Message:an error on the server ("unable to decode an event from the watch stream: http2: response body closed") has prevented the request from succeeding,
// Details:&StatusDetails{
// Causes:[]StatusCause{
// {Type:UnexpectedServerResponse,Message:unable to decode an event from the watch stream: http2: response body closed},
// {Type:ClientWatchDecoding,Message:unable to decode an event from the watch stream: http2: response body closed}},
// RetryAfterSeconds:0}}
l.Debugf("podWatcher: got unexpected event of type %s: %v", evt.Type, evt.Object)
continue
}
// Grab the pod from the event.
pod, ok := evt.Object.(*v1.Pod)
if !ok {
continue
}
if !w.podSelector.Select(pod) {
continue
}
if log.IsTraceLevelEnabled() {
st := fmt.Sprintf("podWatcher[%s/%s:%v] phase:%v ", pod.Namespace, pod.Name, evt.Type, pod.Status.Phase)
if len(pod.Status.Reason) > 0 {
st += fmt.Sprintf("reason:%s ", pod.Status.Reason)
}
for _, c := range append(pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses...) {
switch {
case c.State.Waiting != nil:
st += fmt.Sprintf("%s<waiting> ", c.Name)
case c.State.Running != nil:
st += fmt.Sprintf("%s<running> ", c.Name)
case c.State.Terminated != nil:
st += fmt.Sprintf("%s<terminated> ", c.Name)
}
}
l.Trace(st)
}
l.Tracef("podWatcher: sending to all receivers")
w.receiverLock.RLock()
for receiver, open := range w.receivers {
if open {
l.Tracef("podWatcher: sending event type %v pod name %v namespace %v", evt.Type, pod.GetName(), pod.GetNamespace())
receiver <- PodEvent{
Type: evt.Type,
Pod: pod,
}
}
}
w.receiverLock.RUnlock()
l.Tracef("podWatcher: done sending to all receivers")
}
}
}()
}
return stopWatchers, nil
}