-
Notifications
You must be signed in to change notification settings - Fork 487
/
logs.go
219 lines (183 loc) · 5.66 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
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
// Package logs implements logs support for the Grafana Agent.
package logs
import (
"fmt"
"os"
"path/filepath"
"sync"
"time"
_ "time/tzdata" // embed timezone data
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/grafana/agent/pkg/util"
"github.com/grafana/loki/clients/pkg/promtail"
"github.com/grafana/loki/clients/pkg/promtail/api"
"github.com/grafana/loki/clients/pkg/promtail/client"
"github.com/grafana/loki/clients/pkg/promtail/config"
"github.com/grafana/loki/clients/pkg/promtail/server"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/version"
)
func init() {
client.UserAgent = fmt.Sprintf("GrafanaAgent/%s", version.Version)
}
// Logs is a Logs log collection. It uses multiple distinct sets of Logs
// Promtail agents to collect logs and send them to a Logs server.
type Logs struct {
mut sync.Mutex
reg prometheus.Registerer
l log.Logger
instances map[string]*Instance
}
// New creates and starts Loki log collection.
func New(reg prometheus.Registerer, c *Config, l log.Logger, dryRun bool) (*Logs, error) {
logs := &Logs{
instances: make(map[string]*Instance),
reg: reg,
l: log.With(l, "component", "logs"),
}
if err := logs.ApplyConfig(c, dryRun); err != nil {
return nil, err
}
return logs, nil
}
// ApplyConfig updates Logs with a new Config.
func (l *Logs) ApplyConfig(c *Config, dryRun bool) error {
l.mut.Lock()
defer l.mut.Unlock()
if c == nil {
c = &Config{}
}
newInstances := make(map[string]*Instance, len(c.Configs))
for _, ic := range c.Configs {
// If an old instance existed, update it and move it to the new map.
if old, ok := l.instances[ic.Name]; ok {
err := old.ApplyConfig(ic, dryRun)
if err != nil {
return err
}
newInstances[ic.Name] = old
continue
}
inst, err := NewInstance(l.reg, ic, l.l, dryRun)
if err != nil {
return fmt.Errorf("unable to apply config for %s: %w", ic.Name, err)
}
newInstances[ic.Name] = inst
}
// Any promtail in l.instances that isn't in newInstances has been removed
// from the config. Stop them before replacing the map.
for key, i := range l.instances {
if _, exist := newInstances[key]; exist {
continue
}
i.Stop()
}
l.instances = newInstances
return nil
}
// Stop stops the log collector.
func (l *Logs) Stop() {
l.mut.Lock()
defer l.mut.Unlock()
for _, i := range l.instances {
i.Stop()
}
}
// Instance is used to retrieve a named Logs instance
func (l *Logs) Instance(name string) *Instance {
l.mut.Lock()
defer l.mut.Unlock()
return l.instances[name]
}
// Instance is an individual Logs instance.
type Instance struct {
mut sync.Mutex
cfg *InstanceConfig
log log.Logger
reg *util.Unregisterer
promtail *promtail.Promtail
}
// NewInstance creates and starts a Logs instance.
func NewInstance(reg prometheus.Registerer, c *InstanceConfig, l log.Logger, dryRun bool) (*Instance, error) {
instReg := prometheus.WrapRegistererWith(prometheus.Labels{"logs_config": c.Name}, reg)
inst := Instance{
reg: util.WrapWithUnregisterer(instReg),
log: log.With(l, "logs_config", c.Name),
}
if err := inst.ApplyConfig(c, dryRun); err != nil {
return nil, err
}
return &inst, nil
}
// ApplyConfig will apply a new InstanceConfig. If the config hasn't changed,
// then nothing will happen, otherwise the old Promtail will be stopped and
// then replaced with a new one.
func (i *Instance) ApplyConfig(c *InstanceConfig, dryRun bool) error {
i.mut.Lock()
defer i.mut.Unlock()
// No-op if the configs haven't changed.
if util.CompareYAML(c, i.cfg) {
level.Debug(i.log).Log("msg", "instance config hasn't changed, not recreating Promtail")
return nil
}
i.cfg = c
positionsDir := filepath.Dir(c.PositionsConfig.PositionsFile)
err := os.MkdirAll(positionsDir, 0775)
if err != nil {
level.Warn(i.log).Log("msg", "failed to create the positions directory. logs may be unable to save their position", "path", positionsDir, "err", err)
}
if i.promtail != nil {
i.promtail.Shutdown()
i.promtail = nil
}
// Unregister all existing metrics before trying to create a new instance.
if !i.reg.UnregisterAll() {
// If UnregisterAll fails, we need to abort, otherwise the new promtail
// would try to re-register an existing metric and might panic.
return fmt.Errorf("failed to unregister all metrics from previous promtail. THIS IS A BUG")
}
if len(c.ClientConfigs) == 0 {
level.Debug(i.log).Log("msg", "skipping creation of a promtail because no client_configs are present")
return nil
}
clientMetrics := client.NewMetrics(i.reg, nil)
p, err := promtail.New(config.Config{
ServerConfig: server.Config{Disable: true},
ClientConfigs: c.ClientConfigs,
PositionsConfig: c.PositionsConfig,
ScrapeConfig: c.ScrapeConfig,
TargetConfig: c.TargetConfig,
}, nil, clientMetrics, dryRun, promtail.WithLogger(i.log), promtail.WithRegisterer(i.reg))
if err != nil {
return fmt.Errorf("unable to create logs instance: %w", err)
}
i.promtail = p
return nil
}
// SendEntry passes an entry to the internal promtail client and returns true if successfully sent. It is
// best effort and not guaranteed to succeed.
func (i *Instance) SendEntry(entry api.Entry, dur time.Duration) bool {
i.mut.Lock()
defer i.mut.Unlock()
// promtail is nil it has been stopped
if i.promtail != nil {
// send non blocking so we don't block the mutex. this is best effort
select {
case i.promtail.Client().Chan() <- entry:
return true
case <-time.After(dur):
}
}
return false
}
// Stop stops the Promtail instance.
func (i *Instance) Stop() {
i.mut.Lock()
defer i.mut.Unlock()
if i.promtail != nil {
i.promtail.Shutdown()
i.promtail = nil
}
i.reg.UnregisterAll()
}