-
Notifications
You must be signed in to change notification settings - Fork 9
/
logging.go
283 lines (231 loc) · 7.27 KB
/
logging.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
// 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 buildkit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"time"
"github.com/moby/buildkit/client"
"github.com/moby/buildkit/util/progress/progressui"
"github.com/opencontainers/go-digest"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/common"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/std/tasks"
)
var TaskOutputBuildkitJsonLog = tasks.Output("buildkit.json", "application/json+fn.buildkit")
var UsePlaintextLogging = false
type jsonEvent struct {
SessionID string `json:"s"`
Started *time.Time `json:"started,omitempty"`
Completed *time.Time `json:"completed,omitempty"`
Event *client.SolveStatus `json:"e,omitempty"`
}
func setupOutput(ctx context.Context, logid, sid string, eg executor.ExecutorLike, parentCh chan *client.SolveStatus) {
attachments := tasks.Attachments(ctx)
outText := attachments.Output(tasks.TaskOutputTextLog, common.CatOutputTool)
outJSON := attachments.Output(TaskOutputBuildkitJsonLog, common.CatOutputTool)
console.GetErrContext(ctx).AddLog(tasks.TaskOutputTextLog)
writers := []io.Writer{outText}
jsonWriters := []io.Writer{outJSON}
channelCount := len(writers) + len(jsonWriters)
if UsePlaintextLogging {
writers = append(writers, console.Output(ctx, console.MakeConsoleName(logid, sid, "")))
channelCount++
} else {
channelCount++
}
chs := make([]chan *client.SolveStatus, channelCount)
for k := range chs {
chs[k] = make(chan *client.SolveStatus)
}
eg.Go(func(_ context.Context) error {
// Copy output to N consoles.
for v := range parentCh {
for _, child := range chs {
child <- v
}
}
for _, child := range chs {
close(child)
}
return nil
})
for k := range writers {
k := k // Capture k
eg.Go(func(ctx context.Context) error {
// Don't propagate context cancelation, rather let the channel management above
// decide when we should bail out. Without this, DisplaySolveStatus may decide to
// return because it observed a cancellation. But it's channel is not closed. Which
// leads to writes above blocking, as there's no consumer. If those writes block,
// then buildkit's Solve can't return, as it's waiting to push a status update. And
// that will lead to it never returning from a cancelation (8h+ were spent on this issue).
_, err := progressui.DisplaySolveStatus(context.Background(), "", nil,
×tampPrefixWriter{writers[k], time.Now, true}, chs[k])
if err != nil {
return fnerrors.InternalError("buildkit progress ui failed: %w", err)
}
return nil
})
}
for k := range jsonWriters {
k := k // Capture k
eg.Go(func(ctx context.Context) error {
ch := chs[k+len(writers)]
now := time.Now()
if err := pushJsonEvent(jsonWriters[k], jsonEvent{SessionID: sid, Started: &now}); err != nil {
return err
}
for event := range ch {
if err := pushJsonEvent(jsonWriters[k], jsonEvent{SessionID: sid, Event: event}); err != nil {
return err
}
}
end := time.Now()
if err := pushJsonEvent(jsonWriters[k], jsonEvent{SessionID: sid, Completed: &end}); err != nil {
return err
}
return nil
})
}
if UsePlaintextLogging {
return // Skip the next block.
}
eg.Go(func(ctx context.Context) error {
ch := chs[len(chs)-1]
running := map[string]*vertexState{}
streams := map[string]io.Writer{}
for event := range ch {
for _, vertex := range event.Vertexes {
vid := vertex.Digest.Encoded()
name := vertex.Name
if vertex.Cached {
tasks.Action(name).Category("buildkit").Arg("cached", true).Log(ctx)
continue
}
existing := running[vid]
if vertex.Started != nil && vertex.Completed == nil {
if existing == nil {
existing = &vertexState{
action: tasks.Action(name).Category("buildkit").StartTimestamp(*vertex.Started).Start(ctx),
statuses: map[string]*tasks.RunningAction{},
}
running[vid] = existing
}
}
if vertex.Completed != nil && existing != nil {
var err error
if vertex.Error != "" {
err = fnerrors.New(vertex.Error)
// TODO mark a buffer storing the error message.
}
existing.customDone(*vertex.Completed, err)
delete(running, vid)
}
}
for _, status := range event.Statuses {
vid := status.Vertex.Encoded()
parent := running[vid]
if parent == nil {
// Should never happen.
continue
}
sid := status.ID
existing := parent.statuses[sid]
if status.Started != nil {
if existing == nil {
existing = tasks.Action(sid).Category("buildkit").Parent(parent.action.ID()).StartTimestamp(*status.Started).Start(ctx)
parent.statuses[sid] = existing
// XXX implement progress tracking, buildkit will send updated `Current` counts.
}
}
if status.Completed != nil && existing != nil {
existing.CustomDone(*status.Completed, nil)
delete(running, sid)
}
}
for _, log := range event.Logs {
key := fmt.Sprintf("%s/%d", log.Vertex, log.Stream)
if streams[key] == nil {
name := consoleName(logid, log.Vertex, log.Stream)
outputName := tasks.Output(name, "text/plain")
output := tasks.Attachments(ctx).Output(outputName, common.CatOutputTool)
streams[key] = io.MultiWriter(output, console.Output(ctx, name))
console.GetErrContext(ctx).AddLog(outputName)
}
_, _ = streams[key].Write(log.Data)
}
}
for _, ra := range running {
ra.customDone(time.Now(), fnerrors.New("never finished"))
}
return nil
})
}
func consoleName(logid string, d digest.Digest, streamNum int) string {
if logid == "" {
logid = "buildkit"
}
return console.MakeConsoleName(logid, d.Hex(), streamName(streamNum))
}
func streamName(streamNum int) string {
// https://github.com/moby/buildkit/blob/08497dafaff7b99f4e1780f17475e327c940b3f6/util/progress/logs/logs.go#L25-L26
switch streamNum {
case 1, 2:
return ""
default:
return fmt.Sprintf(":%d", streamNum)
}
}
type vertexState struct {
action *tasks.RunningAction
statuses map[string]*tasks.RunningAction
}
func (vs *vertexState) customDone(t time.Time, err error) {
for _, st := range vs.statuses {
st.CustomDone(t, err)
}
vs.action.CustomDone(t, err)
}
func pushJsonEvent(w io.Writer, ev jsonEvent) error {
p, err := json.Marshal(ev)
if err != nil {
return err
}
// Make a space for a newline, easier to parse.
pline := make([]byte, len(p)+1)
copy(pline, p)
pline[len(p)] = '\n'
if _, err := w.Write(pline); err != nil {
return err
}
return nil
}
type timestampPrefixWriter struct {
w io.Writer
clock func() time.Time
pendingTimestamp bool
}
func (tsw *timestampPrefixWriter) Write(p []byte) (int, error) {
for len(p) > 0 {
if tsw.pendingTimestamp {
fmt.Fprintf(tsw.w, "%s ", tsw.clock().Format(time.RFC3339Nano))
tsw.pendingTimestamp = false
}
k := bytes.Index(p, []byte("\n"))
if k < 0 {
_, _ = tsw.w.Write(p)
break
} else {
_, _ = tsw.w.Write(p[:(k + 1)])
p = p[k+1:]
tsw.pendingTimestamp = true
}
}
return len(p), nil
}