-
Notifications
You must be signed in to change notification settings - Fork 485
/
target.go
260 lines (238 loc) · 7.08 KB
/
target.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
package cloudflaretarget
// This code is copied from Promtail (a1c1152b79547a133cc7be520a0b2e6db8b84868).
// The cloudflaretarget package is used to configure and run a target that can
// read from the Cloudflare Logpull API and forward entries to other loki
// components.
import (
"context"
"regexp"
"strings"
"sync"
"time"
"github.com/buger/jsonparser"
"github.com/go-kit/log"
"github.com/grafana/agent/component/common/loki"
"github.com/grafana/agent/component/common/loki/positions"
"github.com/grafana/agent/pkg/flow/logging/level"
"github.com/grafana/cloudflare-go"
"github.com/grafana/dskit/backoff"
"github.com/grafana/dskit/concurrency"
"github.com/grafana/dskit/multierror"
"github.com/grafana/loki/pkg/logproto"
"github.com/prometheus/common/model"
"go.uber.org/atomic"
)
// The minimum window size is 1 minute.
const minDelay = time.Minute
var cloudflareTooEarlyError = regexp.MustCompile(`too early: logs older than \S+ are not available`)
var defaultBackoff = backoff.Config{
MinBackoff: 1 * time.Second,
MaxBackoff: 10 * time.Second,
MaxRetries: 5,
}
// Config defines how to connect to Cloudflare's Logpull API.
type Config struct {
APIToken string
ZoneID string
Labels model.LabelSet
Workers int
PullRange model.Duration
FieldsType string
AdditionalFields []string
}
// Target enables pulling HTTP log messages from Cloudflare using the Logpull
// API.
type Target struct {
logger log.Logger
handler loki.EntryHandler
positions positions.Positions
config *Config
metrics *Metrics
client Client
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
to time.Time // the end of the next pull interval
running *atomic.Bool
err error
}
// NewTarget creates and runs a Cloudflare target.
func NewTarget(metrics *Metrics, logger log.Logger, handler loki.EntryHandler, position positions.Positions, config *Config) (*Target, error) {
fields, err := Fields(FieldsType(config.FieldsType), config.AdditionalFields)
if err != nil {
return nil, err
}
client, err := getClient(config.APIToken, config.ZoneID, fields)
if err != nil {
return nil, err
}
pos, err := position.Get(positions.CursorKey(config.ZoneID), config.Labels.String())
if err != nil {
return nil, err
}
to := time.Now()
if pos != 0 {
to = time.Unix(0, pos)
}
ctx, cancel := context.WithCancel(context.Background())
t := &Target{
logger: logger,
handler: handler,
positions: position,
config: config,
metrics: metrics,
ctx: ctx,
cancel: cancel,
client: client,
to: to,
running: atomic.NewBool(false),
}
t.start()
return t, nil
}
func (t *Target) start() {
t.wg.Add(1)
t.running.Store(true)
go func() {
defer func() {
t.wg.Done()
t.running.Store(false)
}()
for t.ctx.Err() == nil {
end := t.to
maxEnd := time.Now().Add(-minDelay)
if end.After(maxEnd) {
end = maxEnd
}
start := end.Add(-time.Duration(t.config.PullRange))
requests := splitRequests(start, end, t.config.Workers)
// Use background context for workers as we don't want to cancel halfway through.
// In case of errors we stop the target, each worker has its own retry logic.
if err := concurrency.ForEachJob(context.Background(), len(requests), t.config.Workers, func(ctx context.Context, idx int) error {
request := requests[idx]
return t.pull(ctx, request.start, request.end)
}); err != nil {
level.Error(t.logger).Log("msg", "failed to pull logs", "err", err, "start", start, "end", end)
t.err = err
return
}
// Sets current timestamp metrics, move to the next interval and saves the position.
t.metrics.LastEnd.Set(float64(end.UnixNano()) / 1e9)
t.to = end.Add(time.Duration(t.config.PullRange))
t.positions.Put(positions.CursorKey(t.config.ZoneID), t.Labels().String(), t.to.UnixNano())
// If the next window can be fetched do it, if not sleep for a while.
// This is because Cloudflare logs should never be pulled between now-1m and now.
diff := t.to.Sub(time.Now().Add(-minDelay))
if diff > 0 {
select {
case <-time.After(diff):
case <-t.ctx.Done():
}
}
}
}()
}
// pull pulls logs from cloudflare for a given time range.
// It will retry on errors.
func (t *Target) pull(ctx context.Context, start, end time.Time) error {
var (
backoff = backoff.New(ctx, defaultBackoff)
errs = multierror.New()
it cloudflare.LogpullReceivedIterator
err error
)
for backoff.Ongoing() {
it, err = t.client.LogpullReceived(ctx, start, end)
if err != nil && cloudflareTooEarlyError.MatchString(err.Error()) {
level.Warn(t.logger).Log("msg", "failed iterating over logs, out of cloudflare range, not retrying", "err", err, "start", start, "end", end, "retries", backoff.NumRetries())
return nil
} else if err != nil {
if it != nil {
it.Close()
}
errs.Add(err)
backoff.Wait()
continue
}
if err := func() error {
defer it.Close()
var lineRead int64
for it.Next() {
line := it.Line()
ts, err := jsonparser.GetInt(line, "EdgeStartTimestamp")
if err != nil {
ts = time.Now().UnixNano()
}
t.handler.Chan() <- loki.Entry{
Labels: t.config.Labels.Clone(),
Entry: logproto.Entry{
Timestamp: time.Unix(0, ts),
Line: string(line),
},
}
lineRead++
t.metrics.Entries.Inc()
}
if it.Err() != nil {
level.Warn(t.logger).Log("msg", "failed iterating over logs", "err", it.Err(), "start", start, "end", end, "retries", backoff.NumRetries(), "lineRead", lineRead)
return it.Err()
}
return nil
}(); err != nil {
errs.Add(err)
backoff.Wait()
continue
}
return nil
}
return errs.Err()
}
// Stop shuts down the target.
func (t *Target) Stop() {
t.cancel()
t.wg.Wait()
t.handler.Stop()
}
// Labels returns the custom labels attached to log entries.
func (t *Target) Labels() model.LabelSet {
return t.config.Labels
}
// Ready reports whether the target is ready.
func (t *Target) Ready() bool {
return t.running.Load()
}
// Details returns debug details about the Cloudflare target.
func (t *Target) Details() map[string]string {
fields, _ := Fields(FieldsType(t.config.FieldsType), t.config.AdditionalFields)
var errMsg string
if t.err != nil {
errMsg = t.err.Error()
}
return map[string]string{
"zone_id": t.config.ZoneID,
"error": errMsg,
"position": t.positions.GetString(positions.CursorKey(t.config.ZoneID), t.config.Labels.String()),
"last_timestamp": t.to.String(),
"fields": strings.Join(fields, ","),
}
}
type pullRequest struct {
start time.Time
end time.Time
}
func splitRequests(start, end time.Time, workers int) []pullRequest {
perWorker := end.Sub(start) / time.Duration(workers)
var requests []pullRequest
for i := 0; i < workers; i++ {
r := pullRequest{
start: start.Add(time.Duration(i) * perWorker),
end: start.Add(time.Duration(i+1) * perWorker),
}
// If the last worker is smaller than the others, we need to make sure it gets the last chunk.
if i == workers-1 && r.end != end {
r.end = end
}
requests = append(requests, r)
}
return requests
}