forked from grafana/loki
/
target.go
242 lines (209 loc) · 5.96 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
package docker
import (
"bufio"
"context"
"fmt"
"io"
"strconv"
"strings"
"sync"
"time"
docker_types "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"go.uber.org/atomic"
"github.com/pao214/loki/v2/clients/pkg/promtail/api"
"github.com/pao214/loki/v2/clients/pkg/promtail/positions"
"github.com/pao214/loki/v2/clients/pkg/promtail/targets/target"
"github.com/pao214/loki/v2/pkg/logproto"
)
type Target struct {
logger log.Logger
handler api.EntryHandler
since int64
positions positions.Positions
containerName string
labels model.LabelSet
relabelConfig []*relabel.Config
metrics *Metrics
cancel context.CancelFunc
client client.APIClient
wg sync.WaitGroup
running *atomic.Bool
err error
}
func NewTarget(
metrics *Metrics,
logger log.Logger,
handler api.EntryHandler,
position positions.Positions,
containerName string,
labels model.LabelSet,
relabelConfig []*relabel.Config,
client client.APIClient,
) (*Target, error) {
pos, err := position.Get(positions.CursorKey(containerName))
if err != nil {
return nil, err
}
var since int64
if pos != 0 {
since = pos
}
t := &Target{
logger: logger,
handler: handler,
since: since,
positions: position,
containerName: containerName,
labels: labels,
relabelConfig: relabelConfig,
metrics: metrics,
client: client,
running: atomic.NewBool(false),
}
t.startIfNotRunning()
return t, nil
}
func (t *Target) processLoop(ctx context.Context) {
t.running.Store(true)
defer t.running.Store(false)
t.wg.Add(1)
defer t.wg.Done()
opts := docker_types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
Timestamps: true,
Since: strconv.FormatInt(t.since, 10),
}
logs, err := t.client.ContainerLogs(ctx, t.containerName, opts)
if err != nil {
level.Error(t.logger).Log("msg", "could not fetch logs for container", "container", t.containerName, "err", err)
t.err = err
return
}
// Start transferring
rstdout, wstdout := io.Pipe()
rstderr, wstderr := io.Pipe()
t.wg.Add(1)
go func() {
defer func() {
t.wg.Done()
wstdout.Close()
wstderr.Close()
t.Stop()
}()
written, err := stdcopy.StdCopy(wstdout, wstderr, logs)
if err != nil {
level.Warn(t.logger).Log("msg", "could not transfer logs", "written", written, "container", t.containerName, "err", err)
} else {
level.Info(t.logger).Log("msg", "finished transferring logs", "written", written, "container", t.containerName)
}
}()
// Start processing
t.wg.Add(2)
go t.process(rstdout, "stdout")
go t.process(rstderr, "stderr")
// Wait until done
<-ctx.Done()
logs.Close()
level.Debug(t.logger).Log("msg", "done processing Docker logs", "container", t.containerName)
}
// extractTs tries for read the timestamp from the beginning of the log line.
// It's expected to follow the format 2006-01-02T15:04:05.999999999Z07:00.
func extractTs(line string) (time.Time, string, error) {
pair := strings.SplitN(line, " ", 2)
if len(pair) != 2 {
return time.Now(), line, fmt.Errorf("Could not find timestamp in '%s'", line)
}
ts, err := time.Parse("2006-01-02T15:04:05.999999999Z07:00", pair[0])
if err != nil {
return time.Now(), line, fmt.Errorf("Could not parse timestamp from '%s': %w", pair[0], err)
}
return ts, pair[1], nil
}
func (t *Target) process(r io.Reader, logStream string) {
defer func() {
t.wg.Done()
}()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
ts, line, err := extractTs(line)
if err != nil {
level.Error(t.logger).Log("msg", "could not extract timestamp, skipping line", "err", err)
t.metrics.dockerErrors.Inc()
continue
}
// Add all labels from the config, relabel and filter them.
lb := labels.NewBuilder(nil)
for k, v := range t.labels {
lb.Set(string(k), string(v))
}
lb.Set(dockerLabelLogStream, logStream)
processed := relabel.Process(lb.Labels(), t.relabelConfig...)
filtered := make(model.LabelSet)
for _, lbl := range processed {
if strings.HasPrefix(lbl.Name, "__") {
continue
}
filtered[model.LabelName(lbl.Name)] = model.LabelValue(lbl.Value)
}
t.handler.Chan() <- api.Entry{
Labels: filtered,
Entry: logproto.Entry{
Timestamp: ts,
Line: line,
},
}
t.metrics.dockerEntries.Inc()
t.positions.Put(positions.CursorKey(t.containerName), ts.Unix())
}
err := scanner.Err()
if err != nil {
level.Warn(t.logger).Log("msg", "finished scanning logs lines with an error", "err", err)
}
}
// startIfNotRunning starts processing container logs. The operation is idempotent , i.e. the processing cannot be started twice.
func (t *Target) startIfNotRunning() {
if t.running.CAS(false, true) {
level.Debug(t.logger).Log("msg", "starting process loop", "container", t.containerName)
ctx, cancel := context.WithCancel(context.Background())
t.cancel = cancel
go t.processLoop(ctx)
} else {
level.Debug(t.logger).Log("msg", "attempted to start process loop but it's already running", "container", t.containerName)
}
}
func (t *Target) Stop() {
t.cancel()
t.wg.Wait()
level.Debug(t.logger).Log("msg", "stopped Docker target", "container", t.containerName)
}
func (t *Target) Type() target.TargetType {
return target.DockerTargetType
}
func (t *Target) Ready() bool {
return t.running.Load()
}
func (t *Target) DiscoveredLabels() model.LabelSet {
return t.labels
}
func (t *Target) Labels() model.LabelSet {
return t.labels
}
// Details returns target-specific details.
func (t *Target) Details() interface{} {
return map[string]string{
"id": t.containerName,
"error": t.err.Error(),
"position": t.positions.GetString(positions.CursorKey(t.containerName)),
"running": strconv.FormatBool(t.running.Load()),
}
}