forked from cloudfoundry/go-log-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwalk.go
318 lines (267 loc) · 7.49 KB
/
walk.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package client
import (
"context"
"io"
"log"
"time"
"code.cloudfoundry.org/go-log-cache/v3/rpc/logcache_v1"
"code.cloudfoundry.org/go-loggregator/v10/rpc/loggregator_v2"
)
// Reader reads envelopes from LogCache. It will be invoked by Walker several
// time to traverse the length of the cache.
type Reader func(
ctx context.Context,
sourceID string,
start time.Time,
opts ...ReadOption,
) ([]*loggregator_v2.Envelope, error)
// Visitor is invoked for each envelope batch. If the function returns false,
// it doesn't make any more requests. Otherwise it reaches out for the next
// batch of envelopes.
type Visitor func([]*loggregator_v2.Envelope) bool
// Walk reads from the LogCache until the Visitor returns false.
func Walk(ctx context.Context, sourceID string, v Visitor, r Reader, opts ...WalkOption) {
c := &WalkConfig{
Log: log.New(io.Discard, "", 0),
Backoff: AlwaysDoneBackoff{},
}
walkOptionDelay := WithWalkDelay(2)
walkOptionDelay(c)
for _, o := range opts {
o(c)
}
var readOpts []ReadOption
if !c.End.IsZero() {
readOpts = append(readOpts, WithEndTime(c.End))
}
if c.Limit != nil {
readOpts = append(readOpts, WithLimit(*c.Limit))
}
if c.EnvelopeTypes != nil {
readOpts = append(readOpts, WithEnvelopeTypes(c.EnvelopeTypes...))
}
if c.NameFilter != "" {
readOpts = append(readOpts, WithNameFilter(c.NameFilter))
}
var receivedEmpty bool
for {
es, err := r(ctx, sourceID, time.Unix(0, c.Start), readOpts...)
if err != nil && ctx.Err() != nil {
// Context cancelled
return
}
if err != nil {
c.Log.Print(err)
if !c.Backoff.OnErr(err) {
return
}
continue
}
if c.End.IsZero() || !receivedEmpty {
// Prune envelopes for any that are too new or from the future.
es = c.DelayFunc(es)
}
if !c.End.IsZero() {
for i := len(es) - 1; i >= 0; i-- {
if es[i].GetTimestamp() < c.End.UnixNano() {
break
}
es = es[:i]
}
}
if len(es) == 0 {
receivedEmpty = true
if !c.Backoff.OnEmpty() {
return
}
continue
}
c.Backoff.Reset()
receivedEmpty = false
// If visitor is done or the next timestamp would be outside of our
// window (only when End is set), then be done.
if !v(es) || (!c.End.IsZero() && es[len(es)-1].Timestamp+1 >= c.End.UnixNano()) {
return
}
c.Start = es[len(es)-1].Timestamp + 1
}
}
// WalkOption overrides defaults for Walk.
type WalkOption func(config *WalkConfig)
// WithWalkLogger is used to set the logger for the Walk. It defaults to
// not logging.
func WithWalkLogger(l *log.Logger) WalkOption {
return func(c *WalkConfig) {
c.Log = l
}
}
// WithWalkStartTime sets the Start time of the query.
func WithWalkStartTime(t time.Time) WalkOption {
return func(c *WalkConfig) {
c.Start = t.UnixNano()
}
}
// WithWalkEndTime sets the End time of the query. Once reached, Walk will
// exit.
func WithWalkEndTime(t time.Time) WalkOption {
return func(c *WalkConfig) {
c.End = t
}
}
// WithWalkLimit sets the Limit of the query.
func WithWalkLimit(limit int) WalkOption {
return func(c *WalkConfig) {
c.Limit = &limit
}
}
// WithWalkEnvelopeType sets the envelope_types of the query.
func WithWalkEnvelopeTypes(t ...logcache_v1.EnvelopeType) WalkOption {
return func(c *WalkConfig) {
c.EnvelopeTypes = t
}
}
func WithWalkNameFilter(nameFilter string) WalkOption {
return func(c *WalkConfig) {
c.NameFilter = nameFilter
}
}
// WithWalkBackoff sets the Backoff strategy for an empty batch or error. It
// defaults to stopping on an error or empty batch via AlwaysDoneBackoff.
func WithWalkBackoff(b Backoff) WalkOption {
return func(c *WalkConfig) {
c.Backoff = b
}
}
// WithWalkDelay sets the value that the walk algorithm will consider "old"
// enough. If an envelope has a timestamp that has a value that is greater
// than time.Now().Add(-Delay), it will be considered too "new", and not
// included. This protects from distributed clocks causing data to be skipped.
// Defaults to 1 second.
func WithWalkDelay(delay time.Duration) WalkOption {
return func(c *WalkConfig) {
c.DelayFunc = func(es []*loggregator_v2.Envelope) []*loggregator_v2.Envelope {
withDelay := time.Now().Add(-delay).UnixNano()
for i := len(es) - 1; i >= 0; i-- {
if es[i].GetTimestamp() <= withDelay {
// The rest of the envelopes aren't too new.
break
}
// Envelope is too new. Throw it away.
es = es[:i]
}
return es
}
}
}
// WithWalkDelayFunc allows custom logic to determine which envelopes are too new.
// Walk will continue to walk from the last envelope not discarded by this
// function. By default it uses WithWalkDelay(1)
func WithWalkDelayFunc(delayFunc func([]*loggregator_v2.Envelope) []*loggregator_v2.Envelope) WalkOption {
return func(c *WalkConfig) {
c.DelayFunc = delayFunc
}
}
// Backoff is used to determine what to do if there is an empty batch or
// error. If there is an error, it will be passed to the method OnErr. If there is
// not an error and just an empty batch, the method OnEmpty will be invoked. If
// the either method returns false, then Walk exits. On a successful read that
// has envelopes, Reset will be invoked.
type Backoff interface {
OnErr(error) bool
OnEmpty() bool
Reset()
}
// AlwaysDoneBackoff returns false for both OnErr and OnEmpty.
type AlwaysDoneBackoff struct{}
// OnErr implements Backoff.
func (b AlwaysDoneBackoff) OnErr(error) bool {
return false
}
// OnEmpty implements Backoff.
func (b AlwaysDoneBackoff) OnEmpty() bool {
return false
}
// Reset implements Backoff.
func (b AlwaysDoneBackoff) Reset() {}
// AlwaysRetryBackoff returns true for both OnErr and OnEmpty after sleeping
// the given interval.
type AlwaysRetryBackoff struct {
interval time.Duration
}
// NewAlwaysRetryBackoff returns a new AlwaysRetryBackoff.
func NewAlwaysRetryBackoff(interval time.Duration) AlwaysRetryBackoff {
return AlwaysRetryBackoff{
interval: interval,
}
}
// OnErr implements Backoff.
func (b AlwaysRetryBackoff) OnErr(error) bool {
time.Sleep(b.interval)
return true
}
// OnEmpty implements Backoff.
func (b AlwaysRetryBackoff) OnEmpty() bool {
time.Sleep(b.interval)
return true
}
// Reset implements Backoff.
func (b AlwaysRetryBackoff) Reset() {}
// RetryBackoff returns true for both OnErr and OnEmpty after sleeping
// the given interval for a limited number of times.
type RetryBackoff struct {
interval time.Duration
maxCount int
count int
onlyErr bool
}
// NewRetryBackoff returns a new RetryBackoff.
func NewRetryBackoff(interval time.Duration, maxCount int) *RetryBackoff {
return &RetryBackoff{
interval: interval,
maxCount: maxCount,
}
}
// NewRetryBackoffOnErr returns a new RetryBackoff that only backs off no
// errors.
func NewRetryBackoffOnErr(interval time.Duration, maxCount int) *RetryBackoff {
return &RetryBackoff{
interval: interval,
maxCount: maxCount,
onlyErr: true,
}
}
// OnErr implements Backoff.
func (b *RetryBackoff) OnErr(error) bool {
b.count++
if b.count >= b.maxCount {
return false
}
time.Sleep(b.interval)
return true
}
// OnEmpty implements Backoff.
func (b *RetryBackoff) OnEmpty() bool {
if b.onlyErr {
return false
}
b.count++
if b.count >= b.maxCount {
return false
}
time.Sleep(b.interval)
return true
}
// Reset implements Backoff.
func (b *RetryBackoff) Reset() {
b.count = 0
}
type WalkConfig struct {
Log *log.Logger
Backoff Backoff
Start int64
End time.Time
Limit *int
EnvelopeTypes []logcache_v1.EnvelopeType
DelayFunc func([]*loggregator_v2.Envelope) []*loggregator_v2.Envelope
NameFilter string
}