/
logs.go
188 lines (160 loc) · 3.79 KB
/
logs.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
package k8s
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"sort"
"strings"
"sync"
"time"
"gitlab.com/tslocum/cview"
cv1 "k8s.io/api/core/v1"
)
type ErrMultipleContainers struct {
error
Containers []string
}
type logData struct {
color []byte
from []byte
line []byte
time time.Time
}
const previousPrefix = "previous:"
func (c *Client) Logs(ctx context.Context, object ObjectMetaGetter, container string, colors []string) (<-chan []byte, error) {
var pods []*cv1.Pod
switch v := object.(type) {
case *cv1.Pod:
pods = append(pods, v)
case PodManager:
pods = v.Pods()
}
if len(pods) == 0 {
return nil, nil
}
var previous bool
if strings.HasPrefix(container, previousPrefix) {
previous = true
container = container[len(previousPrefix):]
}
names := make([]string, 0, len(pods[0].Status.ContainerStatuses))
for _, c := range pods[0].Status.ContainerStatuses {
if c.Name == container {
names = nil
break
}
names = append(names, c.Name)
if c.LastTerminationState.Terminated != nil {
names = append(names, previousPrefix+c.Name)
}
}
if len(names) > 1 {
return nil, ErrMultipleContainers{
errors.New("multiple containers"),
names,
}
}
writer := make(chan []byte)
reader := make(chan logData)
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
go demuxLogs(ctx, writer, reader, len(pods) > 1)
var wg sync.WaitGroup
for i, pod := range pods {
name := pod.ObjectMeta.GetName()
req := c.CoreV1().Pods(pod.ObjectMeta.GetNamespace()).GetLogs(
name, &cv1.PodLogOptions{Previous: previous, Follow: true, Container: container, Timestamps: true})
rc, err := req.Stream(ctx)
if err != nil {
cancel()
return nil, fmt.Errorf("getting logs for pod %s: %w", name, NormalizeError(err))
}
prefix := name
idx := strings.LastIndex(name, "-")
if idx > 0 {
prefix = name[idx+1:]
}
wg.Add(1)
go func(i int) {
readLogData(ctx, rc, reader, []byte(prefix), []byte(colors[i%len(colors)]))
wg.Done()
}(i)
}
go func() {
wg.Wait()
close(reader)
cancel()
}()
return writer, nil
}
func demuxLogs(ctx context.Context, writer chan<- []byte, reader <-chan logData, showPrefixes bool) {
var logData []logData
var buf bytes.Buffer
canTrigger := true
trig := make(chan struct{})
defer close(writer)
for {
select {
case <-ctx.Done():
return
case <-trig:
sort.Slice(logData, func(i, j int) bool {
return logData[i].time.Before(logData[j].time)
})
for _, d := range logData {
if showPrefixes {
buf.Write([]byte("["))
buf.Write(d.color)
buf.Write([]byte("]"))
buf.Write(d.from)
buf.Write([]byte(" → "))
buf.Write([]byte("[white]"))
}
buf.Write([]byte(cview.Escape(string(d.line))))
}
logData = nil
writer <- buf.Bytes()
buf.Reset()
canTrigger = true
case data, open := <-reader:
if !open {
reader = nil
continue
}
logData = append(logData, data)
// Buffer the writes in a timed window to avoid having to print out
// line by line when there is a lot of initial content
if canTrigger {
time.AfterFunc(500*time.Millisecond, func() { trig <- struct{}{} })
canTrigger = false
}
}
}
}
func readLogData(ctx context.Context, rc io.ReadCloser, data chan<- logData, prefix []byte, color []byte) {
defer rc.Close()
r := bufio.NewReader(rc)
for {
if ctx.Err() != nil {
return
}
b, err := r.ReadBytes('\n')
if err != nil {
if err != io.EOF {
log.Printf("Error reading stream: %v", err)
return
}
return
}
parts := bytes.SplitN(b, []byte(" "), 2)
t, err := time.Parse(time.RFC3339Nano, string(parts[0]))
if err != nil {
log.Printf("Error parsing time %s from log line: %v", string(parts[0]), err)
}
data <- logData{from: prefix, color: color, line: parts[1], time: t}
}
}