forked from openconfig/kne
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus.go
More file actions
253 lines (233 loc) · 6.28 KB
/
status.go
File metadata and controls
253 lines (233 loc) · 6.28 KB
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
package pods
import (
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
log "k8s.io/klog/v2"
)
// MaxPullTime is how long we will give a pod to start after seeing
// ErrImagePull.
var MaxPullTime = time.Minute * 15
// A Watcher watches pod and container updates.
type Watcher struct {
ctx context.Context
errCh chan error
wstop func()
cancel func()
podStates map[types.UID]string
podStart map[types.UID]time.Time
cStates map[string]string
ch chan *PodStatus
stdout io.Writer
warningf func(string, ...any)
mu sync.Mutex
progress bool
currentNamespace string
currentPod types.UID
allowedNS map[string]struct{}
}
// NewWatcher returns a Watcher on the provided client or an error. The cancel
// function is called when the Watcher determines a container has permanently
// failed. The Watcher will exit if the context provided is canceled, an error
// is encountered, or Cleanup is called.
func NewWatcher(ctx context.Context, client kubernetes.Interface, cancel func()) (*Watcher, error) {
ch, stop, err := WatchPodStatus(ctx, client, "")
if err != nil {
return nil, err
}
w := newWatcher(ctx, cancel, ch, stop)
go w.watch()
return w, nil
}
func newWatcher(ctx context.Context, cancel func(), ch chan *PodStatus, stop func()) *Watcher {
w := &Watcher{
ctx: ctx,
ch: ch,
wstop: stop,
cancel: cancel,
stdout: os.Stdout,
podStates: map[types.UID]string{},
podStart: map[types.UID]time.Time{},
cStates: map[string]string{},
warningf: log.Warningf,
}
// A channel is used to record errors from the watcher to prevent any
// possible race conditions if Cleanup is called while an update is
// happening. At most one error will be written to the channel.
w.errCh = make(chan error, 1)
w.display("Displaying state changes for pods and containers")
return w
}
// SetProgress determins if progress output should be displayed while watching.
func (w *Watcher) SetProgress(value bool) {
w.mu.Lock()
w.progress = value
w.mu.Unlock()
}
// AllowNamespaces restricts the watcher to only consider pods in the provided namespaces.
// If no namespaces are provided, all namespaces are considered.
func (w *Watcher) AllowNamespaces(namespaces ...string) {
w.mu.Lock()
defer w.mu.Unlock()
if len(namespaces) == 0 {
w.allowedNS = nil
return
}
w.allowedNS = make(map[string]struct{}, len(namespaces))
for _, ns := range namespaces {
if ns == "" {
continue
}
w.allowedNS[ns] = struct{}{}
}
}
func (w *Watcher) stop() {
w.mu.Lock()
stop := w.wstop
w.wstop = nil
w.mu.Unlock()
if stop != nil {
stop()
}
}
// Cleanup should be called when the Watcher is no longer needed. If the
// Watcher encountered an error the provided err is logged and the Watcher error
// is returned, otherwise err is returned.
func (w *Watcher) Cleanup(err error) error {
w.stop()
select {
case werr := <-w.errCh:
if err != nil {
w.warningf("Deploy() failed: %v", err)
}
w.warningf("Deployment failed: %v", werr)
return werr
default:
}
return err
}
func (w *Watcher) watch() {
defer w.stop()
for {
select {
case s, ok := <-w.ch:
if !ok || !w.updatePod(s) {
return
}
case <-w.ctx.Done():
return
}
}
}
var timeNow = func() string { return time.Now().Format("15:04:05 ") }
func (w *Watcher) display(format string, v ...any) {
if w.progress {
fmt.Fprintf(w.stdout, timeNow()+format+"\n", v...)
}
}
func (w *Watcher) updatePod(s *PodStatus) bool {
// If allowed namespaces are configured, ignore pods outside them.
w.mu.Lock()
allowed := w.allowedNS
w.mu.Unlock()
if allowed != nil {
if _, ok := allowed[s.Namespace]; !ok {
return true
}
}
newNamespace := s.Namespace != w.currentNamespace
var newState string
if s.Ready {
newState = "READY"
} else {
switch s.Phase {
case PodPending:
newState = "pending"
case PodRunning:
newState = "running"
case PodSucceeded:
newState = "success"
case PodFailed:
newState = "failed"
}
}
showPodState := func(s *PodStatus, oldState, newState string) {
if w.currentPod == s.UID && oldState == newState {
return
}
w.currentPod = s.UID
if newNamespace {
w.currentNamespace = s.Namespace
w.display("NS: %s", s.Namespace)
newNamespace = false
}
if newState == "" {
w.display(" POD: %s", s.Name)
} else {
w.display(" POD: %s is now %s", s.Name, newState)
}
}
showContainer := func(s *PodStatus, c *ContainerStatus, state string) {
id := s.Namespace + ":" + s.Name + ":" + c.Name
if oldState := w.cStates[id]; oldState != state {
showPodState(s, "", "")
w.cStates[id] = state
w.display(" CONTAINER: %s is now %s", c.Name, state)
}
}
if oldState := w.podStates[s.UID]; oldState != newState {
showPodState(s, oldState, newState)
w.podStates[s.UID] = newState
}
if newState == "failed" {
w.errCh <- fmt.Errorf("Pod %s failed to deploy", s.Name)
w.cancel()
return false
}
for _, c := range append(s.Containers, s.InitContainers...) {
c := c // because of lint
fullName := fmt.Sprintf("NS:%s POD:%s CONTAINER:%s", s.Namespace, s.Name, c.Name)
// We could keep track of all container
// states and issue a message each time
// the state changes
if c.Ready {
showContainer(s, &c, "READY")
continue
}
s.Ready = false // This should never happen
switch {
case c.Reason == "ErrImagePull" && strings.Contains(c.Message, "code = NotFound"):
showContainer(s, &c, "FAILED")
w.warningf("%s: %s", fullName, c.Message)
w.errCh <- fmt.Errorf("%s IMAGE:%s not found", fullName, c.Image)
w.cancel()
return false
case c.Reason == "ErrImagePull":
if t, ok := w.podStart[s.UID]; ok {
if t.Add(MaxPullTime).Before(time.Now()) {
showContainer(s, &c, "PULL TIMED OUT")
w.warningf("%s: pull timed out after %v", fullName, MaxPullTime)
w.errCh <- fmt.Errorf("%s IMAGE:%s pull timed out after %v", fullName, c.Image, MaxPullTime)
w.cancel()
return false
}
} else {
w.podStart[s.UID] = time.Now()
}
showContainer(s, &c, c.Reason)
log.Infof("%s in ErrImagePull", fullName)
case c.Reason == "ImagePullBackOff":
showContainer(s, &c, c.Reason)
log.Infof("%s in PullBackoff", fullName)
default:
showContainer(s, &c, c.Reason)
}
}
return true
}