/
store.go
338 lines (299 loc) · 8.32 KB
/
store.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package services
import (
"bufio"
"context"
"fmt"
"os"
"sync"
"time"
"github.com/awnumar/memguard"
"github.com/gogo/protobuf/proto"
"github.com/inconshreveable/log15"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
circuit "github.com/rubyist/circuitbreaker"
"github.com/stephane-martin/skewer/conf"
"github.com/stephane-martin/skewer/model"
"github.com/stephane-martin/skewer/services/base"
"github.com/stephane-martin/skewer/store"
"github.com/stephane-martin/skewer/store/dests"
"github.com/stephane-martin/skewer/sys/binder"
"github.com/stephane-martin/skewer/sys/kring"
"github.com/stephane-martin/skewer/utils"
"github.com/stephane-martin/skewer/utils/eerrors"
"github.com/stephane-martin/skewer/utils/httpserver"
"github.com/stephane-martin/skewer/utils/reservoir"
"github.com/stephane-martin/skewer/utils/waiter"
)
type storeServiceImpl struct {
store *store.MessageStore
config conf.BaseConfig
logger log15.Logger
binder binder.Client
shutdownStore context.CancelFunc
shutdownCtx context.Context
pipeCtx context.Context
cancelForwarders context.CancelFunc
cancelPipe context.CancelFunc
fwdersWg sync.WaitGroup
mu sync.Mutex
ingestwg sync.WaitGroup
pipe *os.File
status bool
secret *memguard.LockedBuffer
ring kring.Ring
confined bool
}
// NewStoreService creates a StoreService.
// The StoreService is responsible to manage the lifecycle of the Store and the
// Kafka Forwarder that is fed by the Store.
func NewStoreService(env *base.ProviderEnv) (base.Provider, error) {
if env.Pipe == nil {
return nil, fmt.Errorf("The Store was not given a message pipe")
}
store.InitRegistry()
dests.InitRegistry()
impl := storeServiceImpl{
status: false,
pipe: env.Pipe,
logger: env.Logger,
binder: env.Binder,
ring: env.Ring,
confined: env.Confined,
}
impl.shutdownCtx, impl.shutdownStore = context.WithCancel(context.Background())
impl.pipeCtx, impl.cancelPipe = context.WithCancel(impl.shutdownCtx)
if env.Profile {
httpserver.ProfileServer(env.Binder)
}
return &impl, nil
}
func (s *storeServiceImpl) Type() base.Types {
return base.Store
}
func (s *storeServiceImpl) SetConf(c conf.BaseConfig) {
}
func (s *storeServiceImpl) SetConfAndRestart(c conf.BaseConfig) ([]model.ListenerInfo, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.doStop(nil)
s.config = c
if c.Main.EncryptIPC {
secret, err := s.ring.GetBoxSecret()
if err != nil {
return nil, err
}
s.logger.Debug("The store receives messages from an encrypted pipe")
s.secret = secret
} else {
s.secret = nil
}
return s.doStart()
}
func (s *storeServiceImpl) FatalError() chan struct{} {
// Errors return a channel to signal the Store fatal errors.
// (Typically no space left on disk.)
return s.store.Errors()
}
func (s *storeServiceImpl) Start() ([]model.ListenerInfo, error) {
// unused
return nil, nil
}
func (s *storeServiceImpl) create() error {
var destinations conf.DestinationType
destinations, err := s.config.Main.GetDestinations()
if err != nil {
return eerrors.Wrap(err, "Error getting destinations")
}
sto, err := store.NewStore(s.shutdownCtx, s.config.Store, s.ring, destinations, s.confined, s.logger)
if err != nil {
return eerrors.Wrap(err, "Error creating the Store")
}
s.store = sto
err = s.store.StoreAllSyslogConfigs(s.config)
if err != nil {
return eerrors.Wrap(err, "Error storing configurations in store")
}
reserv := reservoir.NewReservoir(uint64(s.store.BatchSize))
// send messages to the store
s.ingestwg.Add(1)
go func() {
defer s.ingestwg.Done()
m := make(map[utils.MyULID]string, s.store.BatchSize)
w := waiter.Default()
for {
err := reserv.DeliverTo(m)
if err == eerrors.ErrQDisposed {
return
}
if len(m) == 0 {
w.WaitCtx(s.pipeCtx)
continue
}
w.Reset()
_, e := s.store.Ingest(m)
if e != nil {
// TODO: damned
}
for k := range m {
delete(m, k)
}
}
}()
// receive syslog messages on the pipe
s.ingestwg.Add(1)
go func() {
defer func() {
reserv.Dispose()
s.logger.Debug("Stopped to read the ingestion store pipe")
s.ingestwg.Done()
}()
scanner := utils.WithRecover(utils.WithContext(s.pipeCtx, bufio.NewScanner(s.pipe)))
scanner.Split(utils.MakeDecryptSplit(s.secret))
scanner.Buffer(make([]byte, 0, 65536), 65536)
protobuff := proto.NewBuffer(make([]byte, 0, 4096))
for scanner.Scan() {
msgBytes := scanner.Bytes()
protobuff.SetBuf(msgBytes)
message, err := model.FromBuf(protobuff) // we need to parse to get the message uid
if err != nil {
model.FullFree(message)
s.logger.Error("Unexpected error decoding message from the Store pipe", "error", err)
go func() { s.Shutdown() }()
return
}
uid := message.Uid
model.FullFree(message)
reserv.Add(uid, string(msgBytes))
}
if err != nil && !eerrors.HasFileClosed(err) {
s.logger.Warn("Unexpected error decoding message from the Store pipe", "error", err)
}
}()
return nil
}
func (s *storeServiceImpl) startAllForwarders(dests conf.DestinationType) {
// returns immediately
var gforwarderCtx context.Context
gforwarderCtx, s.cancelForwarders = context.WithCancel(s.shutdownCtx)
for _, dtype := range dests.Iterate() {
desttype := dtype
s.fwdersWg.Add(1)
go s.startForwarder(gforwarderCtx, desttype)
}
}
func (s *storeServiceImpl) stopAllForwarders() {
if s.cancelForwarders != nil {
s.cancelForwarders()
}
s.fwdersWg.Wait()
}
func (s *storeServiceImpl) startForwarder(ctx context.Context, desttype conf.DestinationType) {
defer s.fwdersWg.Done()
s.logger.Info("Starting forwarder", "type", conf.DestinationNames[desttype])
forwarder := store.NewForwarder(desttype, s.store, s.config, s.logger, s.binder)
cb := circuit.NewConsecutiveBreaker(3)
for {
fctx, fcancel := context.WithCancel(ctx)
// we use a circuit breaker to prevent from trying to create the destination too often
err := cb.CallContext(
fctx,
func() error { return forwarder.CreateDestination(fctx) },
time.Minute,
)
if err != nil {
fcancel()
if err != circuit.ErrBreakerOpen {
s.logger.Error("Forwarder faced an error when creating destination", "dest", desttype, "error", err)
}
} else {
// destination was successfully created
err = forwarder.Forward(fctx)
fcancel()
if err == nil {
return
}
s.logger.Error("Forwarder error", "dest", desttype, "error", err)
}
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
}
}
func (s *storeServiceImpl) doStart() ([]model.ListenerInfo, error) {
infos := []model.ListenerInfo{}
select {
case <-s.shutdownCtx.Done():
// the Store is shutdown
return infos, nil
default:
}
if s.status {
// already started
return infos, nil
}
destinations, err := s.config.Main.GetDestinations()
if err != nil {
s.logger.Error("Error parsing destinations (should not happen!!!)", "error", err)
return nil, err
}
// create the store if needed
if s.store == nil {
err = s.create()
if err != nil {
return infos, err
}
}
// refresh destinations
s.store.SetDestinations(destinations)
s.status = true
// create and start the forwarders
s.startAllForwarders(destinations)
return infos, nil
}
// Stop stops the Kafka forwarder
func (s *storeServiceImpl) Stop() {
s.doStop(&s.mu)
}
func (s *storeServiceImpl) doStop(mu *sync.Mutex) {
if mu != nil {
mu.Lock()
defer mu.Unlock()
}
select {
case <-s.shutdownCtx.Done():
// the Store is shutdown
return
default:
}
if !s.status {
// already stopped
return
}
// stop the kafka forwarders
s.stopAllForwarders()
s.status = false
}
// Shutdown stops the forwarders and shutdowns the Store
func (s *storeServiceImpl) Shutdown() {
select {
case <-s.shutdownCtx.Done():
// the Store is already shutdown
return
default:
}
s.Stop()
s.cancelPipe()
s.ingestwg.Wait() // wait until we are done ingesting new messages
s.shutdownStore()
s.logger.Debug("Store service waits for end of store goroutines")
s.store.WaitFinished()
_ = s.pipe.Close()
}
// Gather returns the metrics for the Store and the Kafka forwarder
func (s *storeServiceImpl) Gather() ([]*dto.MetricFamily, error) {
var couple prometheus.Gatherers = []prometheus.Gatherer{store.Registry, dests.Registry}
return couple.Gather()
}