-
Notifications
You must be signed in to change notification settings - Fork 9
/
wait.go
247 lines (202 loc) · 7.25 KB
/
wait.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
// 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 deploy
import (
"bytes"
"context"
"fmt"
"io"
"time"
"github.com/kr/text"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/renderwait"
"namespacelabs.dev/foundation/internal/runtime"
"namespacelabs.dev/foundation/schema/orchestration"
runtimepb "namespacelabs.dev/foundation/schema/runtime"
"namespacelabs.dev/foundation/schema/storage"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/std/execution"
"namespacelabs.dev/foundation/std/tasks"
)
const (
maxDeployWait = 5 * time.Second
diagnosisInterval = 3 * time.Second
tailLinesOnFailure = 10
)
func MaybeRenderClusterBlock(env cfg.Context, cluster runtime.Cluster, fetchDiagnostics func(context.Context) (*storage.EnvironmentDiagnostics, error), render bool) execution.WaitHandler {
return func(ctx context.Context) (chan *orchestration.Event, func(context.Context) error) {
if !render {
return observeContainers(ctx, env, cluster, fetchDiagnostics, nil), func(ctx context.Context) error { return nil }
}
rwb := renderwait.NewBlock(ctx, "deploy")
return observeContainers(ctx, env, cluster, fetchDiagnostics, rwb.Ch()), rwb.Wait
}
}
func MaybeRenderBlock(env cfg.Context, cluster runtime.ClusterNamespace, render bool) execution.WaitHandler {
return MaybeRenderClusterBlock(env, cluster.Cluster(), cluster.FetchEnvironmentDiagnostics, render)
}
func shouldCheckDiagnostics(commited, last time.Time, hasCrash bool, now time.Time) bool {
if last.IsZero() {
if hasCrash {
return true
}
return now.Sub(commited) >= maxDeployWait
}
return now.Sub(last) >= diagnosisInterval
}
// observeContainers observes the deploy events (received from the returned channel) and updates the
// console through the `parent` channel.
func observeContainers(ctx context.Context, env cfg.Context, cluster runtime.Cluster, fetchDiagnostics func(context.Context) (*storage.EnvironmentDiagnostics, error), parent chan *orchestration.Event) chan *orchestration.Event {
ch := make(chan *orchestration.Event)
t := time.NewTicker(time.Second)
type committedState struct {
Committed time.Time
LastDiagnosis time.Time
Help string
Waiting []*runtimepb.ContainerWaitStatus
}
go func() {
if parent != nil {
defer close(parent)
}
defer t.Stop()
committed := map[string]*committedState{} // Key is resource ID.
checkRunDiagnosis := func() {
for resourceID, state := range committed {
all := []*runtimepb.ContainerUnitWaitStatus{}
for _, w := range state.Waiting {
all = append(all, w.Containers...)
all = append(all, w.Initializers...)
}
if len(all) == 0 {
// No containers are present yet, should still produce pod diagnostics.
continue
}
hasCrash := false
for _, ws := range all {
if ws.Status.Crashed || ws.Status.Failed() {
hasCrash = true
break
}
}
now := time.Now()
if !shouldCheckDiagnostics(state.Committed, state.LastDiagnosis, hasCrash, now) {
continue
}
state.LastDiagnosis = now
buf := bytes.NewBuffer(nil)
out := io.MultiWriter(buf, console.Debug(ctx))
if state.Help != "" && !env.Environment().GetEphemeral() {
fmt.Fprintf(out, "For more information, run:\n %s\n", state.Help)
}
fmt.Fprintf(out, "Diagnostics retrieved at %s:\n", time.Now().Format("2006-01-02 15:04:05.000"))
// XXX fetching diagnostics should not block forwarding events (above).
for _, ws := range all {
diagnostics, err := cluster.FetchDiagnostics(ctx, ws.Reference)
if err != nil {
fmt.Fprintf(out, "Failed to retrieve diagnostics for %s: %v\n", ws.Reference.HumanReference, err)
continue
}
fmt.Fprintf(out, "%s", ws.Reference.HumanReference)
if diagnostics.RestartCount > 0 {
fmt.Fprintf(out, " (restarted %d times)", diagnostics.RestartCount)
}
fmt.Fprintln(out, ":")
w := runtime.WriteToWriter(text.NewIndentWriter(out, []byte(" ")))
switch diagnostics.State {
case runtimepb.Diagnostics_RUNNING:
fmt.Fprintf(out, " Running, logs (last %d lines):\n", tailLinesOnFailure)
if err := cluster.FetchLogsTo(ctx, ws.Reference, runtime.FetchLogsOpts{TailLines: tailLinesOnFailure}, w); err != nil {
fmt.Fprintf(out, "Failed to retrieve logs for %s: %v\n", ws.Reference.HumanReference, err)
}
case runtimepb.Diagnostics_WAITING:
fmt.Fprintf(out, " Waiting: %s\n", diagnostics.WaitingReason)
if diagnostics.Crashed {
fmt.Fprintf(out, " Crashed, logs (last %d lines):\n", tailLinesOnFailure)
if err := cluster.FetchLogsTo(ctx, ws.Reference, runtime.FetchLogsOpts{TailLines: tailLinesOnFailure, FetchLastFailure: true}, w); err != nil {
fmt.Fprintf(out, "Failed to retrieve logs for %s: %v\n", ws.Reference.HumanReference, err)
}
}
case runtimepb.Diagnostics_TERMINATED:
if diagnostics.ExitCode > 0 {
fmt.Fprintf(out, " Failed: %s (exit code %d), logs (last %d lines):\n", diagnostics.TerminatedReason, diagnostics.ExitCode, tailLinesOnFailure)
if err := cluster.FetchLogsTo(ctx, ws.Reference, runtime.FetchLogsOpts{TailLines: tailLinesOnFailure, FetchLastFailure: true}, w); err != nil {
fmt.Fprintf(out, "Failed to retrieve logs for %s: %v\n", ws.Reference.HumanReference, err)
}
}
}
}
if parent != nil {
parent <- &orchestration.Event{
ResourceId: resourceID,
WaitDetails: buf.String(),
}
} else if fetchDiagnostics != nil {
diagnostics, err := fetchDiagnostics(ctx)
if err != nil {
fmt.Fprintf(out, "Failed to retrieve environment diagnostics: %v\n", err)
} else {
_ = tasks.Attachments(ctx).AttachSerializable("diagnostics.json", "", diagnostics)
}
}
}
}
for {
select {
case <-ctx.Done():
return
case ev, ok := <-ch:
if !ok {
return
}
if parent != nil {
parent <- ev
}
if ev.Stage >= orchestration.Event_COMMITTED {
state, ok := committed[ev.ResourceId]
if !ok {
state = &committedState{
Committed: ev.Timestamp.AsTime(),
}
if state.Committed.IsZero() {
state.Committed = time.Now()
}
committed[ev.ResourceId] = state
}
if ev.Ready != orchestration.Event_READY {
state.Waiting = nil
state.Help = ev.RuntimeSpecificHelp
failed := false
for _, w := range ev.WaitStatus {
if w.Opaque == nil {
continue
}
cws := &runtimepb.ContainerWaitStatus{}
if err := w.Opaque.UnmarshalTo(cws); err != nil {
continue
}
state.Waiting = append(state.Waiting, cws)
var ctrs []*runtimepb.ContainerUnitWaitStatus
ctrs = append(ctrs, cws.Containers...)
ctrs = append(ctrs, cws.Initializers...)
for _, ctr := range ctrs {
if ctr.Status.Crashed || ctr.Status.Failed() {
failed = true
}
}
}
if failed {
checkRunDiagnosis()
}
} else {
delete(committed, ev.ResourceId)
}
}
case <-t.C:
checkRunDiagnosis()
}
}
}()
return ch
}