-
Notifications
You must be signed in to change notification settings - Fork 22
/
checks.go
939 lines (760 loc) · 25.9 KB
/
checks.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
package checks
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"strconv"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/prompb"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
logproto "github.com/grafana/loki/pkg/push"
"github.com/grafana/synthetic-monitoring-agent/internal/feature"
"github.com/grafana/synthetic-monitoring-agent/internal/k6runner"
"github.com/grafana/synthetic-monitoring-agent/internal/limits"
"github.com/grafana/synthetic-monitoring-agent/internal/model"
"github.com/grafana/synthetic-monitoring-agent/internal/pusher"
"github.com/grafana/synthetic-monitoring-agent/internal/scraper"
"github.com/grafana/synthetic-monitoring-agent/internal/telemetry"
"github.com/grafana/synthetic-monitoring-agent/internal/version"
"github.com/grafana/synthetic-monitoring-agent/pkg/pb/synthetic_monitoring"
sm "github.com/grafana/synthetic-monitoring-agent/pkg/pb/synthetic_monitoring"
)
type Error string
func (e Error) Error() string { return string(e) }
// TransientError is an error that can be recovered.
type TransientError Error
func (e TransientError) Error() string { return string(e) }
var _ error = TransientError("")
// FatalError is an error that causes the program to terminate.
type FatalError Error
func (e FatalError) Error() string { return string(e) }
var _ error = FatalError("")
const (
errCapabilityK6Missing = FatalError("k6 is required for scripted check support")
errIncompatibleApi = FatalError("API does not support required features")
errNotAuthorized = FatalError("probe not authorized")
errProbeUnregistered = TransientError("probe no longer registered")
errTransportClosing = TransientError("transport closing")
)
// Backoffer defines an interface to provide backoff durations.
//
// The implementation of this interface SHOULD NOT perform the actual
// sleep, but rather return the duration to sleep.
type Backoffer interface {
// Reset causes the backoff provider to go back its initial
// state, before any calls to Duration() were made.
Reset()
// Duration returns the duration to sleep.
Duration() time.Duration
}
// Updater represents a probe along with the collection of scrapers
// running on that probe and it manages the configuration for
// blackbox-exporter that corresponds to the collection of scrapers.
type Updater struct {
api apiInfo
logger zerolog.Logger
features feature.Collection
backoff Backoffer
publisher pusher.Publisher
tenantCh chan<- sm.Tenant
IsConnected func(bool)
probe *sm.Probe
scrapersMutex sync.Mutex
scrapers map[model.GlobalID]*scraper.Scraper
metrics metrics
k6Runner k6runner.Runner
scraperFactory scraper.Factory
tenantLimits *limits.TenantLimits
telemeter *telemetry.Telemeter
}
type apiInfo struct {
conn *grpc.ClientConn
}
type metrics struct {
changeErrorsCounter *prometheus.CounterVec
changesCounter *prometheus.CounterVec
connectionStatus prometheus.Gauge
probeInfo *prometheus.GaugeVec
runningScrapers *prometheus.GaugeVec
scrapeErrorCounter *prometheus.CounterVec
scrapesCounter *prometheus.CounterVec
}
type (
TimeSeries = []prompb.TimeSeries
Streams = []logproto.Stream
)
type UpdaterOptions struct {
Conn *grpc.ClientConn
Logger zerolog.Logger
Backoff Backoffer
Publisher pusher.Publisher
TenantCh chan<- sm.Tenant
IsConnected func(bool)
PromRegisterer prometheus.Registerer
Features feature.Collection
K6Runner k6runner.Runner
ScraperFactory scraper.Factory
TenantLimits *limits.TenantLimits
Telemeter *telemetry.Telemeter
}
func NewUpdater(opts UpdaterOptions) (*Updater, error) {
changesCounter := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "sm_agent",
Subsystem: "updater",
Name: "changes_total",
Help: "Total number of changes processed.",
}, []string{
"type",
})
if err := opts.PromRegisterer.Register(changesCounter); err != nil {
return nil, err
}
changeErrorsCounter := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "sm_agent",
Subsystem: "updater",
Name: "change_errors_total",
Help: "Total number of errors during change processing.",
}, []string{
"type",
})
if err := opts.PromRegisterer.Register(changeErrorsCounter); err != nil {
return nil, err
}
runningScrapers := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "sm_agent",
Subsystem: "updater",
Name: "scrapers_total",
Help: "Total number of running scrapers.",
}, []string{
"type",
})
if err := opts.PromRegisterer.Register(runningScrapers); err != nil {
return nil, err
}
scrapesCounter := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "sm_agent",
Subsystem: "scraper",
Name: "operations_total",
Help: "Total number of scrape operations performed by type.",
}, []string{
"type",
"tenantId",
"regionId",
})
if err := opts.PromRegisterer.Register(scrapesCounter); err != nil {
return nil, err
}
scrapeErrorCounter := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "sm_agent",
Subsystem: "scraper",
Name: "errors_total",
Help: "Total number of scraper errors by type and status.",
}, []string{
"type",
"source",
"tenantId",
"regionId",
})
if err := opts.PromRegisterer.Register(scrapeErrorCounter); err != nil {
return nil, err
}
connectionStatusGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "sm_agent",
Subsystem: "api_connection",
Name: "status",
Help: "API connection status.",
})
if err := opts.PromRegisterer.Register(connectionStatusGauge); err != nil {
return nil, err
}
connectionStatusGauge.Set(0)
probeInfoGauge := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "sm_agent",
Name: "info",
Help: "Agent information.",
}, []string{
"id",
"name",
"version",
"commit",
"buildstamp",
})
if err := opts.PromRegisterer.Register(probeInfoGauge); err != nil {
return nil, err
}
scraperFactory := scraper.New
if opts.ScraperFactory != nil {
scraperFactory = opts.ScraperFactory
}
return &Updater{
api: apiInfo{
conn: opts.Conn,
},
logger: opts.Logger,
features: opts.Features,
backoff: opts.Backoff,
publisher: opts.Publisher,
tenantCh: opts.TenantCh,
IsConnected: opts.IsConnected,
scrapers: make(map[model.GlobalID]*scraper.Scraper),
k6Runner: opts.K6Runner,
scraperFactory: scraperFactory,
tenantLimits: opts.TenantLimits,
telemeter: opts.Telemeter,
metrics: metrics{
changeErrorsCounter: changeErrorsCounter,
changesCounter: changesCounter,
connectionStatus: connectionStatusGauge,
probeInfo: probeInfoGauge,
runningScrapers: runningScrapers,
scrapeErrorCounter: scrapeErrorCounter,
scrapesCounter: scrapesCounter,
},
}, nil
}
func (c *Updater) Run(ctx context.Context) error {
c.backoff.Reset()
for {
wasConnected, err := c.loop(ctx)
logger := c.logger.With().Str("connection_state", c.api.conn.GetState().String()).Logger()
logger.Info().Err(err).Bool("was_connected", wasConnected).Msg("broke out of loop")
done, err := handleError(ctx, logger, c.backoff, wasConnected, err)
if done {
return err
}
}
}
// handleError takes care of handling errors that occur during the execution of
// the updater loop. It returns a boolean indicating whether the updater should
// stop and an error that should be returned to the caller of this function.
// That error might be nil.
//
// TODO(mem): `wasConnected` is passed to preserve the previous behavior of the
// updater. It might be possible to remove it and handle this in the caller.
func handleError(ctx context.Context, logger zerolog.Logger, backoff Backoffer, wasConnected bool, err error) (bool, error) {
var (
transientErr TransientError
fatalError FatalError
)
switch {
case err == nil:
return true, nil
case errors.As(err, &transientErr):
logger.Warn().Err(err).Msg("transient error, trying to reconnect")
if err := sleepCtx(ctx, backoff.Duration()); err != nil {
return true, err
}
if wasConnected {
backoff.Reset()
}
return false, nil
case errors.As(err, &fatalError):
logger.Error().Err(err).Msg("fatal error, bailing out")
return true, err
case errors.Is(err, context.Canceled):
// context was cancelled, clean up
logger.Error().
Err(err).
Msg("context cancelled, closing updater")
return true, nil
default:
logger.Warn().
Msg("handling check changes")
// TODO(mem): this might be a transient error (e.g. bad connection). We probably need to
// fine-tune GRPPC's backoff parameters. We might also need to keep count of the reconnects, and
// give up if they hit some threshold?
if err := sleepCtx(ctx, backoff.Duration()); err != nil {
return true, err
}
}
return false, nil
}
func (c *Updater) loop(ctx context.Context) (bool, error) {
connected := false
c.logger.Info().Msg("fetching check configuration from synthetic-monitoring-api")
client := sm.NewChecksClient(c.api.conn)
grpcErrorHandler := func(action string, err error) error {
status, ok := status.FromError(err)
c.logger.Error().Err(err).Str("action", action).Uint32("code", uint32(status.Code())).Msg(status.Message())
switch {
case !ok:
return fmt.Errorf("%s: %w", action, err)
case status.Code() == codes.Canceled:
// either we were told to shut down
return context.Canceled
case status.Message() == "transport is closing":
// the other end is shutting down
return errTransportClosing
case status.Code() == codes.PermissionDenied:
return errNotAuthorized
case status.Code() == codes.Unimplemented:
return errIncompatibleApi
default:
return status.Err()
}
}
result, err := client.RegisterProbe(ctx, &sm.ProbeInfo{Version: version.Short(), Commit: version.Commit(), Buildstamp: version.Buildstamp()})
if err != nil {
return connected, grpcErrorHandler("registering probe with synthetic-monitoring-api", err)
}
switch result.Status.Code {
case sm.StatusCode_OK:
// continue
case sm.StatusCode_NOT_AUTHORIZED:
return connected, errNotAuthorized
default:
return connected, fmt.Errorf("registering probe with synthetic-monitoring-api, response: %s", result.Status.Message)
}
if err := c.validateProbeCapabilities(result.Probe.Capabilities); err != nil {
return connected, err
}
c.probe = &result.Probe
logger := c.logger.With().Int64("probe_id", c.probe.Id).Logger()
logger.Info().Str("probe_name", c.probe.Name).Msg("registered probe with synthetic-monitoring-api")
c.metrics.connectionStatus.Set(1)
defer c.metrics.connectionStatus.Set(0)
// true indicates that probe is connected to API
connected = true
c.IsConnected(true)
defer c.IsConnected(false)
// this is constant throughout the life of the probe, but since
// we don't know the probe's id or name until this point, set it
// here.
c.metrics.probeInfo.Reset()
c.metrics.probeInfo.With(map[string]string{
"id": strconv.FormatInt(c.probe.Id, 10),
"name": c.probe.Name,
"version": version.Short(),
"commit": version.Commit(),
"buildstamp": version.Buildstamp(),
}).Set(1)
// groupCtx is used to coordinate shutting down all the
// goroutines started here.
g, groupCtx := errgroup.WithContext(ctx)
// We get _another_ context from the signal handler that we can
// use tell the GRPC client that we need to break out. We have
// multiple ways of cancelling the context (another signal
// elsewhere in the system communicated through the parent
// context; cancelling the child context because we are
// returning from this function; cancelling the new context
// because the signal fired), so we need an additional way of
// telling them apart.
sigCtx, signalFired := installSignalHandler(groupCtx)
errorHandler := func(err error, action string, signalFired *int32) error {
switch {
case err == nil:
return nil
case atomic.LoadInt32(signalFired) == 1:
return errProbeUnregistered
default:
return grpcErrorHandler(action, err)
}
}
knownChecks := sm.ProbeState{
Checks: make([]sm.EntityRef, 0, len(c.scrapers)),
}
for cID, scraper := range c.scrapers {
knownChecks.Checks = append(knownChecks.Checks, sm.EntityRef{
Id: int64(cID),
LastModified: scraper.LastModified(),
})
}
cc, err := client.GetChanges(sigCtx, &knownChecks)
if err != nil {
return connected, errorHandler(err, "requesting changes from synthetic-monitoring-api", signalFired)
}
// Run a ping to the GRPC server. Bail out if there's an error here.
g.Go(func() error {
err := ping(sigCtx, client)
logger.Warn().Err(err).Msg("health check ping stopped")
return err
})
g.Go(func() error {
// processChanges uses the context in its first argument to
// create scrapers. This means that cancelling that context
// cancels all the running scrapers. That's why we are passing
// the _original_ context, not sigCtx, so that scrapers are
// _not_ stopped if the signal is trapped. We want scrapers to
// continue running in case the agent is _not_ killed.
err := c.processChanges(ctx, cc)
logger.Warn().Err(err).Msg("processing changes stopped")
return err
})
err = g.Wait()
return connected, errorHandler(err, "getting changes from synthetic-monitoring-api", signalFired)
}
func (c *Updater) validateProbeCapabilities(capabilities *sm.Probe_Capabilities) error {
// k6 is only not required on this probe if explicitly disabled
requireK6 := capabilities == nil || !capabilities.DisableScriptedChecks
if requireK6 && c.k6Runner == nil {
return errCapabilityK6Missing
}
return nil
}
// ping will use the provided client to send a health signal to the GRPC
// server. Any error is returned, the caller should take the necessary
// steps to correct the problem.
func ping(ctx context.Context, client synthetic_monitoring.ChecksClient) error {
var (
req synthetic_monitoring.PingRequest
opts = []grpc.CallOption{
grpc.WaitForReady(false),
}
)
// Send one ping to try to figure out if the API understands
// what we are trying to do.
_, err := client.Ping(ctx, &req, opts...)
if err != nil {
status, ok := status.FromError(err)
switch {
case !ok:
return fmt.Errorf("sending ping: %w", err)
case status.Code() == codes.Unimplemented:
// The API does not support this. Return without error.
return nil
default:
return status.Err()
}
}
req.Sequence++
ticker := time.NewTicker(synthetic_monitoring.HealthCheckInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
_, err := client.Ping(ctx, &req, opts...)
if err != nil {
return err
}
req.Sequence++
}
}
}
// installSignalHandler installs a signal handler for SIGUSR1.
//
// The returned context's Done channel is closed if the signal is
// delivered. To make it simpler to determine if the signal was
// delivered, a value of 1 is written to the location pointed to by the
// returned int32 pointer.
//
// If the provided context's Done channel is closed before the signal is
// delivered, the signal handler is removed and the returned context's
// Done channel is closed, too. It's the callers responsibility to
// cancel the provided context if it's no longer interested in the
// signal.
func installSignalHandler(ctx context.Context) (context.Context, *int32) {
sigCtx, cancel := context.WithCancel(ctx)
fired := new(int32)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGUSR1)
go func() {
select {
case <-sigCh:
atomic.StoreInt32(fired, 1)
cancel()
case <-ctx.Done():
}
signal.Stop(sigCh)
}()
return sigCtx, fired
}
func (c *Updater) processChanges(ctx context.Context, cc sm.Checks_GetChangesClient) error {
firstBatch := true
for {
select {
case <-cc.Context().Done():
return cc.Context().Err()
case <-ctx.Done():
return ctx.Err()
default:
switch msg, err := cc.Recv(); err {
case nil:
c.handleChangeBatch(ctx, msg, firstBatch)
firstBatch = false
case io.EOF:
c.logger.Warn().Err(err).Msg("no more messages?")
// XXX(mem): what happened here? The
// other end told us there are no more
// changes. Stop? Is it restarting?
return nil
default:
return err
}
}
}
}
func (c *Updater) handleCheckAdd(ctx context.Context, check model.Check) error {
c.metrics.changesCounter.WithLabelValues("add").Inc()
if err := check.Validate(); err != nil {
return fmt.Errorf("invalid check: %w", err)
}
c.scrapersMutex.Lock()
defer c.scrapersMutex.Unlock()
if running, found := c.scrapers[check.GlobalID()]; found {
// we can get here if the API sent us a check add twice:
// once during the initial connection and another right
// after that. The window for that is small, but it
// exists.
return fmt.Errorf("check with id %d already exists (version %s)", check.GlobalID(), running.ConfigVersion())
}
return c.addAndStartScraperWithLock(ctx, check)
}
func (c *Updater) handleCheckUpdate(ctx context.Context, check model.Check) error {
c.metrics.changesCounter.WithLabelValues("update").Inc()
if err := check.Validate(); err != nil {
return fmt.Errorf("invalid check: %w", err)
}
c.scrapersMutex.Lock()
defer c.scrapersMutex.Unlock()
return c.handleCheckUpdateWithLock(ctx, check)
}
// handleCheckUpdateWithLock is the bottom half of handleCheckUpdate. It
// MUST be called with the scrapersMutex lock held.
func (c *Updater) handleCheckUpdateWithLock(ctx context.Context, check model.Check) error {
cid := check.GlobalID()
scraper, found := c.scrapers[cid]
if !found {
c.logger.Warn().Int64("check_id", check.Id).Int("region_id", check.RegionId).Msg("update request for an unknown check")
return c.addAndStartScraperWithLock(ctx, check)
}
// this is the lazy way to update the scraper: tear everything
// down, start it again.
scraper.Stop()
checkType := scraper.CheckType().String()
delete(c.scrapers, cid)
c.metrics.runningScrapers.WithLabelValues(checkType).Dec()
return c.addAndStartScraperWithLock(ctx, check)
}
func (c *Updater) handleCheckDelete(ctx context.Context, check model.Check) error {
c.metrics.changesCounter.WithLabelValues("delete").Inc()
cid := check.GlobalID()
c.scrapersMutex.Lock()
defer c.scrapersMutex.Unlock()
scraper, found := c.scrapers[cid]
if !found {
c.logger.Warn().Int64("check_id", check.Id).Int("region_id", check.RegionId).Msg("delete request for an unknown check")
return errors.New("check not found")
}
scraper.Stop()
checkType := scraper.CheckType().String()
delete(c.scrapers, cid)
c.metrics.runningScrapers.WithLabelValues(checkType).Dec()
return nil
}
// handleFirstBatch takes a list of changes and adds them to the running set
// and stops any scrapers that shouldn't be running.
//
// When handling this, we don't know which scrapers the server thinks we are
// no longer running and which scrapers we are running. If we got
// disconnected, the server will send a bunch of ADD operations, and no DELETE
// or UPDATE ones. After we reconnect, we still have a bunch of running
// scrapers that the server might think we are NOT running, so build a list of
// checks the server sent our way and compare it with the list of checks we
// actually have (from the running scrapers). Remove anything that the server
// didn't send, because that means it didn't know we have those (they got
// deleted during the reconnect, and the server didn't send them).
//
// We have to do this exactly once per reconnect. It's up to the calling code
// to ensure this.
func (c *Updater) handleFirstBatch(ctx context.Context, changes *sm.Changes) {
newChecks := make(map[model.GlobalID]struct{})
c.scrapersMutex.Lock()
defer c.scrapersMutex.Unlock()
// add checks from the provided list
for _, checkChange := range changes.Checks {
c.logger.Debug().Interface("check change", checkChange).Msg("got check change")
switch checkChange.Operation {
case sm.CheckOperation_CHECK_ADD:
var check model.Check
if err := check.FromSM(checkChange.Check); err != nil {
c.logger.Error().Err(err).Interface("check_change", checkChange).Msg("dropping check during add operation")
continue
}
if err := c.handleInitialChangeAddWithLock(ctx, check); err != nil {
c.metrics.changeErrorsCounter.WithLabelValues("add").Inc()
c.logger.Error().Err(err).Int64("check_id", check.Id).Int("region_id", check.RegionId).
Msg("adding check failed, dropping check")
continue
}
// add this to the list of checks we have seen during
// this operation
newChecks[check.GlobalID()] = struct{}{}
default:
// we should never hit this because the first time we
// connect the server will only send adds.
c.logger.Warn().
Interface("check", checkChange.Check).
Str("operation", checkChange.Operation.String()).
Msg("unexpected operation, dropping check change")
continue
}
}
// remove all the running scrapers that weren't sent with the first batch
for id, scraper := range c.scrapers {
if _, found := newChecks[id]; found {
continue
}
cid, rid := model.GetLocalAndRegionIDs(id)
c.logger.Debug().
Int64("check_id", cid).
Int("region_id", rid).
Msg("stopping scraper during first batch handling")
checkType := scraper.CheckType().String()
scraper.Stop()
delete(c.scrapers, id)
c.metrics.runningScrapers.WithLabelValues(checkType).Dec()
}
}
// handleCheckUpdateWithLock the specified check to the running checks.
//
// It deals with the case where this check is the product of a reconnection
// and changes the operation to an update if necessary.
//
// This function MUST be called with the scrapers mutex held.
func (c *Updater) handleInitialChangeAddWithLock(ctx context.Context, check model.Check) error {
if running, found := c.scrapers[check.GlobalID()]; found {
oldVersion := running.ConfigVersion()
newVersion := check.ConfigVersion()
if oldVersion == newVersion {
// we already have this, skip
//
// XXX(mem): beware, the probe might have changed
return nil
}
// transform this request into an update
c.logger.Debug().Str("old_check_version", oldVersion).Str("new_check_version", newVersion).Msg("transforming add into update")
return c.handleCheckUpdateWithLock(ctx, check)
}
c.metrics.changesCounter.WithLabelValues("add").Inc()
if err := check.Validate(); err != nil {
return err
}
if err := c.addAndStartScraperWithLock(ctx, check); err != nil {
c.metrics.changeErrorsCounter.WithLabelValues("add").Inc()
return err
}
return nil
}
func (c *Updater) handleChangeBatch(ctx context.Context, changes *sm.Changes, firstBatch bool) {
if firstBatch && !changes.IsDeltaFirstBatch {
c.handleFirstBatch(ctx, changes)
return
}
for _, tenant := range changes.Tenants {
c.tenantCh <- tenant
}
for _, checkChange := range changes.Checks {
c.logger.Debug().Interface("check change", checkChange).Msg("got check change")
var check model.Check
if err := check.FromSM(checkChange.Check); err != nil {
c.logger.Error().Err(err).Interface("check_change", checkChange).Msg("dropping check change")
continue
}
switch checkChange.Operation {
case sm.CheckOperation_CHECK_ADD:
if err := c.handleCheckAdd(ctx, check); err != nil {
c.metrics.changeErrorsCounter.WithLabelValues("add").Inc()
c.logger.Error().Err(err).Msg("handling check add")
}
case sm.CheckOperation_CHECK_UPDATE:
if err := c.handleCheckUpdate(ctx, check); err != nil {
c.metrics.changeErrorsCounter.WithLabelValues("update").Inc()
c.logger.Error().Err(err).Msg("handling check update")
}
case sm.CheckOperation_CHECK_DELETE:
if err := c.handleCheckDelete(ctx, check); err != nil {
c.metrics.changeErrorsCounter.WithLabelValues("delete").Inc()
c.logger.Error().Err(err).Msg("handling check delete")
}
}
}
}
// addAndStartScraperWithLock creates a new scraper, adds it to the list of
// scrapers managed by this updater and starts running it.
//
// This MUST be called with the scrapersMutex held.
func (c *Updater) addAndStartScraperWithLock(ctx context.Context, check model.Check) error {
// This is a good place to filter out checks by feature flags.
//
// If we need to accept checks based on whether a feature flag
// is enabled or not, we can "accept" the check from the point
// of view of the API, and skip running it here, e.g.
switch check.Type() {
case sm.CheckTypeScripted:
if !c.features.IsSet(feature.K6) {
return nil
}
case sm.CheckTypeMultiHttp:
// This is correct, MultiHttp is a K6 check. We probably want
// to abstrct this by adding a function to the settings that
// returns whether the check requires k6 or not.
if !c.features.IsSet(feature.K6) {
return nil
}
default:
}
checkType := check.Type().String()
tidStr := strconv.FormatInt(check.TenantId, 10)
ridStr := strconv.Itoa(check.RegionId)
scrapeCounter, err := c.metrics.scrapesCounter.GetMetricWith(prometheus.Labels{
"type": checkType,
"tenantId": tidStr,
"regionId": ridStr,
})
if err != nil {
return err
}
scrapeErrorCounter, err := c.metrics.scrapeErrorCounter.CurryWith(prometheus.Labels{
"type": checkType,
"tenantId": tidStr,
"regionId": ridStr,
})
if err != nil {
return err
}
metrics := scraper.NewMetrics(
scrapeCounter,
scraper.NewIncrementerFromCounterVec(scrapeErrorCounter),
)
scraper, err := c.scraperFactory(
ctx, check, c.publisher, *c.probe, c.logger,
metrics,
c.k6Runner,
c.tenantLimits, c.telemeter,
)
if err != nil {
return fmt.Errorf("cannot create new scraper: %w", err)
}
c.scrapers[check.GlobalID()] = scraper
go scraper.Run(ctx)
c.metrics.runningScrapers.WithLabelValues(checkType).Inc()
return nil
}
// sleepCtx is like time.Sleep, but it pays attention to the
// cancellation of the provided context.
func sleepCtx(ctx context.Context, d time.Duration) error {
var err error
timer := time.NewTimer(d)
select {
case <-ctx.Done():
err = ctx.Err()
if !timer.Stop() {
<-timer.C
}
case <-timer.C:
}
return err
}