-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.go
147 lines (115 loc) · 2.47 KB
/
monitor.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
package kail
import (
"context"
"fmt"
"io"
"k8s.io/api/core/v1"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
lifecycle "github.com/boz/go-lifecycle"
logutil "github.com/boz/go-logutil"
)
const (
logBufsiz = 1024
)
type monitor interface {
Shutdown()
Done() <-chan struct{}
}
func newMonitor(c *controller, source EventSource) monitor {
lc := lifecycle.New()
go lc.WatchContext(c.ctx)
log := c.log.WithComponent(
fmt.Sprintf("monitor [%v]", source))
m := &_monitor{
core: c.cs.CoreV1(),
source: source,
eventch: c.eventch,
log: log,
lc: lc,
ctx: c.ctx,
}
go m.run()
return m
}
type _monitor struct {
core corev1.CoreV1Interface
source EventSource
eventch chan<- Event
log logutil.Log
lc lifecycle.Lifecycle
ctx context.Context
}
func (m *_monitor) Shutdown() {
m.lc.ShutdownAsync()
}
func (m *_monitor) Done() <-chan struct{} {
return m.lc.Done()
}
func (m *_monitor) run() {
defer m.log.Un(m.log.Trace("run"))
defer m.lc.ShutdownCompleted()
ctx, cancel := context.WithCancel(m.ctx)
donech := make(chan struct{})
go m.mainloop(ctx, donech)
<-m.lc.ShutdownRequest()
m.lc.ShutdownInitiated()
cancel()
<-donech
}
func (m *_monitor) mainloop(ctx context.Context, donech chan struct{}) {
defer m.log.Un(m.log.Trace("mainloop"))
defer close(donech)
defer m.lc.ShutdownAsync()
// todo: backoff handled by k8 client?
for ctx.Err() == nil {
err := m.readloop(ctx)
switch {
case err == io.EOF:
case err == nil:
case ctx.Err() != nil:
return
default:
m.log.ErrWarn(err, "error readloop")
return
}
}
}
func (m *_monitor) readloop(ctx context.Context) error {
defer m.log.Un(m.log.Trace("readloop"))
since := int64(1)
opts := &v1.PodLogOptions{
Container: m.source.Container(),
Follow: true,
SinceSeconds: &since,
}
req := m.core.
Pods(m.source.Namespace()).
GetLogs(m.source.Name(), opts)
req = req.Context(ctx)
stream, err := req.Stream()
if err != nil {
return err
}
defer stream.Close()
logbuf := make([]byte, logBufsiz)
for ctx.Err() == nil {
nread, err := stream.Read(logbuf)
switch {
case err == io.EOF:
return err
case ctx.Err() != nil:
return ctx.Err()
case err != nil:
return m.log.Err(err, "error while reading logs")
case nread == 0:
return io.EOF
}
event := newEvent(m.source, logbuf[0:nread])
select {
case m.eventch <- event:
default:
m.log.Warnf("event buffer full. dropping logs %v", nread)
}
}
return nil
}