Repository navigation
Expand file tree
/
Copy pathrunlog.go
More file actions
102 lines (92 loc) · 2.26 KB
/
Copy pathrunlog.go
File metadata and controls
102 lines (92 loc) · 2.26 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
package main
import (
"context"
"fmt"
"net/http"
"sync"
"time"
)
// maxRunLogSize caps the output kept per run, so a runaway job can't exhaust memory.
const maxRunLogSize = 4 << 20
// runLog collects a sign job's output while it runs, for /status to stream.
type runLog struct {
mu sync.Mutex
started time.Time
finished time.Time
err error
output []byte
truncated bool
}
func newRunLog() *runLog {
return &runLog{started: time.Now()}
}
func (r *runLog) Write(p []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
if room := maxRunLogSize - len(r.output); len(p) > room {
r.output = append(r.output, p[:max(room, 0)]...)
r.truncated = true
} else {
r.output = append(r.output, p...)
}
return len(p), nil
}
func (r *runLog) String() string {
r.mu.Lock()
defer r.mu.Unlock()
return string(r.output)
}
func (r *runLog) finish(err error) {
r.mu.Lock()
defer r.mu.Unlock()
r.finished = time.Now()
r.err = err
}
// snapshot returns the output from offset on, and whether the run has finished.
func (r *runLog) snapshot(offset int) ([]byte, bool) {
r.mu.Lock()
defer r.mu.Unlock()
return r.output[offset:len(r.output):len(r.output)], !r.finished.IsZero()
}
// follow writes the run's output to w, and keeps writing new output until the run finishes or
// the client goes away.
func (r *runLog) follow(ctx context.Context, w http.ResponseWriter) error {
fmt.Fprintf(w, "Last job started %s\n\n", r.started.UTC().Format(time.RFC1123))
flusher, _ := w.(http.Flusher)
offset := 0
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
chunk, done := r.snapshot(offset)
if len(chunk) > 0 {
if _, err := w.Write(chunk); err != nil {
return nil
}
offset += len(chunk)
}
if done {
fmt.Fprintf(w, "\n%s\n", r.summary())
return nil
}
if flusher != nil {
flusher.Flush()
}
select {
case <-ctx.Done():
return nil
case <-ticker.C:
}
}
}
func (r *runLog) summary() string {
r.mu.Lock()
defer r.mu.Unlock()
result := "Succeeded"
if r.err != nil {
result = "Failed: " + r.err.Error()
}
if r.truncated {
result += fmt.Sprintf(" (output after the first %d MB not shown)", maxRunLogSize>>20)
}
return fmt.Sprintf("%s after %s.", result, r.finished.Sub(r.started).Round(time.Second))
}