-
Notifications
You must be signed in to change notification settings - Fork 454
/
multitenant_test.go
2154 lines (1826 loc) · 72.7 KB
/
multitenant_test.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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: AGPL-3.0-only
// Provenance-includes-location: https://github.com/cortexproject/cortex/blob/master/pkg/alertmanager/multitenant_test.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Cortex Authors.
package alertmanager
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
"net/http/pprof"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/go-kit/log"
"github.com/grafana/dskit/concurrency"
"github.com/grafana/dskit/flagext"
"github.com/grafana/dskit/kv/consul"
"github.com/grafana/dskit/ring"
"github.com/grafana/dskit/services"
"github.com/grafana/dskit/test"
"github.com/prometheus/alertmanager/cluster/clusterpb"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/pkg/labels"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/thanos-io/thanos/pkg/objstore"
"github.com/weaveworks/common/httpgrpc"
"github.com/weaveworks/common/user"
"go.uber.org/atomic"
"golang.org/x/time/rate"
"google.golang.org/grpc"
"github.com/grafana/mimir/pkg/alertmanager/alertmanagerpb"
"github.com/grafana/mimir/pkg/alertmanager/alertspb"
"github.com/grafana/mimir/pkg/alertmanager/alertstore"
"github.com/grafana/mimir/pkg/alertmanager/alertstore/bucketclient"
"github.com/grafana/mimir/pkg/storage/bucket"
"github.com/grafana/mimir/pkg/util"
"github.com/grafana/mimir/pkg/util/validation"
)
var (
simpleConfigOne = `route:
receiver: dummy
receivers:
- name: dummy`
simpleConfigTwo = `route:
receiver: dummy
receivers:
- name: dummy`
)
func mockAlertmanagerConfig(t *testing.T) *MultitenantAlertmanagerConfig {
t.Helper()
externalURL := flagext.URLValue{}
err := externalURL.Set("http://localhost/alertmanager")
require.NoError(t, err)
tempDir := t.TempDir()
cfg := &MultitenantAlertmanagerConfig{}
flagext.DefaultValues(cfg)
cfg.ExternalURL = externalURL
cfg.DataDir = tempDir
cfg.ShardingRing.InstanceID = "test"
cfg.ShardingRing.InstanceAddr = "127.0.0.1"
cfg.PollInterval = time.Minute
cfg.ShardingRing.ReplicationFactor = 1
cfg.Persister = PersisterConfig{Interval: time.Hour}
return cfg
}
func setupSingleMultitenantAlertmanager(t *testing.T, cfg *MultitenantAlertmanagerConfig, store alertstore.AlertStore, limits Limits, logger log.Logger, registerer prometheus.Registerer) *MultitenantAlertmanager {
// The mock ring store means we do not need a real e.g. Consul running.
ringStore, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil)
t.Cleanup(func() {
assert.NoError(t, closer.Close())
})
am, err := createMultitenantAlertmanager(cfg, nil, store, ringStore, limits, logger, registerer)
require.NoError(t, err)
// The mock client pool allows the distributor to talk to the instance
// without requiring a gRPC server to be running.
clientPool := newPassthroughAlertmanagerClientPool()
clientPool.setServer(cfg.ShardingRing.InstanceAddr+":0", am)
am.alertmanagerClientsPool = clientPool
am.distributor.alertmanagerClientsPool = clientPool
// We need to start the alertmanager for most tests in order for tenant
// ownership checking to work, as it queries the ring.
require.NoError(t, services.StartAndAwaitRunning(context.Background(), am))
t.Cleanup(func() {
require.NoError(t, services.StopAndAwaitTerminated(context.Background(), am))
})
return am
}
func TestMultitenantAlertmanagerConfig_Validate(t *testing.T) {
tests := map[string]struct {
setup func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config)
expected error
}{
"should pass with default config": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {},
expected: nil,
},
"should fail with empty external URL": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
require.NoError(t, cfg.ExternalURL.Set(""))
},
expected: errEmptyExternalURL,
},
"should fail if persistent interval is 0": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
cfg.Persister.Interval = 0
},
expected: errInvalidPersistInterval,
},
"should fail if persistent interval is negative": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
cfg.Persister.Interval = -1
},
expected: errInvalidPersistInterval,
},
"should fail if external URL ends with /": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
require.NoError(t, cfg.ExternalURL.Set("http://localhost/prefix/"))
},
expected: errInvalidExternalURL,
},
"should succeed if external URL does not end with /": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
require.NoError(t, cfg.ExternalURL.Set("http://localhost/prefix"))
},
expected: nil,
},
"should succeed if new storage configuration given with bucket client": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
storageCfg.Backend = "s3"
},
expected: nil,
},
"should fail if new storage store configuration given with local type": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
storageCfg.Backend = "local"
},
expected: errShardingUnsupportedStorage,
},
"should fail if zone aware is enabled but zone is not set": {
setup: func(t *testing.T, cfg *MultitenantAlertmanagerConfig, storageCfg *alertstore.Config) {
cfg.ShardingRing.ZoneAwarenessEnabled = true
},
expected: errZoneAwarenessEnabledWithoutZoneInfo,
},
}
for testName, testData := range tests {
t.Run(testName, func(t *testing.T) {
cfg := &MultitenantAlertmanagerConfig{}
storageCfg := alertstore.Config{}
flagext.DefaultValues(cfg)
flagext.DefaultValues(&storageCfg)
testData.setup(t, cfg, &storageCfg)
assert.Equal(t, testData.expected, cfg.Validate(storageCfg))
})
}
}
func TestMultitenantAlertmanager_loadAndSyncConfigs(t *testing.T) {
ctx := context.Background()
// Run this test using a real storage client.
store := prepareInMemoryAlertStore()
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: "user1",
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: "user2",
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
reg := prometheus.NewPedanticRegistry()
cfg := mockAlertmanagerConfig(t)
am := setupSingleMultitenantAlertmanager(t, cfg, store, nil, log.NewNopLogger(), reg)
// Ensure the configs are synced correctly
err := am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
require.Len(t, am.alertmanagers, 2)
currentConfig, cfgExists := am.cfgs["user1"]
require.True(t, cfgExists)
require.Equal(t, simpleConfigOne, currentConfig.RawConfig)
assert.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP cortex_alertmanager_config_last_reload_successful Boolean set to 1 whenever the last configuration reload attempt was successful.
# TYPE cortex_alertmanager_config_last_reload_successful gauge
cortex_alertmanager_config_last_reload_successful{user="user1"} 1
cortex_alertmanager_config_last_reload_successful{user="user2"} 1
`), "cortex_alertmanager_config_last_reload_successful"))
// Ensure when a 3rd config is added, it is synced correctly
user3Cfg := alertspb.AlertConfigDesc{
User: "user3",
RawConfig: simpleConfigOne + `
templates:
- 'first.tpl'
- 'second.tpl'
`,
Templates: []*alertspb.TemplateDesc{
{
Filename: "first.tpl",
Body: `{{ define "t1" }}Template 1 ... {{end}}`,
},
{
Filename: "second.tpl",
Body: `{{ define "t2" }}Template 2{{ end}}`,
},
},
}
require.NoError(t, store.SetAlertConfig(ctx, user3Cfg))
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
require.Len(t, am.alertmanagers, 3)
dirs := am.getPerUserDirectories()
user3Dir := dirs["user3"]
require.NotZero(t, user3Dir)
require.True(t, dirExists(t, user3Dir))
require.True(t, dirExists(t, filepath.Join(user3Dir, templatesDir)))
require.True(t, fileExists(t, filepath.Join(user3Dir, templatesDir, "first.tpl")))
require.True(t, fileExists(t, filepath.Join(user3Dir, templatesDir, "second.tpl")))
assert.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP cortex_alertmanager_config_last_reload_successful Boolean set to 1 whenever the last configuration reload attempt was successful.
# TYPE cortex_alertmanager_config_last_reload_successful gauge
cortex_alertmanager_config_last_reload_successful{user="user1"} 1
cortex_alertmanager_config_last_reload_successful{user="user2"} 1
cortex_alertmanager_config_last_reload_successful{user="user3"} 1
`), "cortex_alertmanager_config_last_reload_successful"))
// Ensure the config is updated
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: "user1",
RawConfig: simpleConfigTwo,
Templates: []*alertspb.TemplateDesc{},
}))
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
currentConfig, cfgExists = am.cfgs["user1"]
require.True(t, cfgExists)
require.Equal(t, simpleConfigTwo, currentConfig.RawConfig)
// Test Delete User, ensure config is removed and the resources are freed.
require.NoError(t, store.DeleteAlertConfig(ctx, "user3"))
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
currentConfig, cfgExists = am.cfgs["user3"]
require.False(t, cfgExists)
require.Equal(t, "", currentConfig.RawConfig)
_, cfgExists = am.alertmanagers["user3"]
require.False(t, cfgExists)
dirs = am.getPerUserDirectories()
require.NotZero(t, dirs["user1"])
require.NotZero(t, dirs["user2"])
require.Zero(t, dirs["user3"]) // User3 is deleted, so we should have no more files for it.
require.False(t, fileExists(t, user3Dir))
assert.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP cortex_alertmanager_config_last_reload_successful Boolean set to 1 whenever the last configuration reload attempt was successful.
# TYPE cortex_alertmanager_config_last_reload_successful gauge
cortex_alertmanager_config_last_reload_successful{user="user1"} 1
cortex_alertmanager_config_last_reload_successful{user="user2"} 1
`), "cortex_alertmanager_config_last_reload_successful"))
// Ensure when a 3rd config is re-added, it is synced correctly
require.NoError(t, store.SetAlertConfig(ctx, user3Cfg))
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
currentConfig, cfgExists = am.cfgs["user3"]
require.True(t, cfgExists)
require.Equal(t, user3Cfg.RawConfig, currentConfig.RawConfig)
_, cfgExists = am.alertmanagers["user3"]
require.True(t, cfgExists)
dirs = am.getPerUserDirectories()
require.NotZero(t, dirs["user1"])
require.NotZero(t, dirs["user2"])
require.Equal(t, user3Dir, dirs["user3"]) // Dir should exist, even though state files are not generated yet.
// Hierarchy that existed before should exist again.
require.True(t, dirExists(t, user3Dir))
require.True(t, dirExists(t, filepath.Join(user3Dir, templatesDir)))
require.True(t, fileExists(t, filepath.Join(user3Dir, templatesDir, "first.tpl")))
require.True(t, fileExists(t, filepath.Join(user3Dir, templatesDir, "second.tpl")))
assert.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP cortex_alertmanager_config_last_reload_successful Boolean set to 1 whenever the last configuration reload attempt was successful.
# TYPE cortex_alertmanager_config_last_reload_successful gauge
cortex_alertmanager_config_last_reload_successful{user="user1"} 1
cortex_alertmanager_config_last_reload_successful{user="user2"} 1
cortex_alertmanager_config_last_reload_successful{user="user3"} 1
`), "cortex_alertmanager_config_last_reload_successful"))
// Removed template files should be cleaned up
user3Cfg.Templates = []*alertspb.TemplateDesc{
{
Filename: "first.tpl",
Body: `{{ define "t1" }}Template 1 ... {{end}}`,
},
}
require.NoError(t, store.SetAlertConfig(ctx, user3Cfg))
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
require.True(t, dirExists(t, user3Dir))
require.True(t, fileExists(t, filepath.Join(user3Dir, templatesDir, "first.tpl")))
require.False(t, fileExists(t, filepath.Join(user3Dir, templatesDir, "second.tpl")))
}
func TestMultitenantAlertmanager_FirewallShouldBlockHTTPBasedReceiversWhenEnabled(t *testing.T) {
tests := map[string]struct {
getAlertmanagerConfig func(backendURL string) string
}{
"webhook": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: webhook
group_wait: 0s
group_interval: 1s
receivers:
- name: webhook
webhook_configs:
- url: %s
`, backendURL)
},
},
"pagerduty": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: pagerduty
group_wait: 0s
group_interval: 1s
receivers:
- name: pagerduty
pagerduty_configs:
- url: %s
routing_key: secret
`, backendURL)
},
},
"slack": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: slack
group_wait: 0s
group_interval: 1s
receivers:
- name: slack
slack_configs:
- api_url: %s
channel: test
`, backendURL)
},
},
"opsgenie": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: opsgenie
group_wait: 0s
group_interval: 1s
receivers:
- name: opsgenie
opsgenie_configs:
- api_url: %s
api_key: secret
`, backendURL)
},
},
"wechat": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: wechat
group_wait: 0s
group_interval: 1s
receivers:
- name: wechat
wechat_configs:
- api_url: %s
api_secret: secret
corp_id: babycorp
`, backendURL)
},
},
"sns": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: sns
group_wait: 0s
group_interval: 1s
receivers:
- name: sns
sns_configs:
- api_url: %s
topic_arn: arn:aws:sns:us-east-1:123456789012:MyTopic
sigv4:
region: us-east-1
access_key: xxx
secret_key: xxx
`, backendURL)
},
},
"telegram": {
getAlertmanagerConfig: func(backendURL string) string {
return fmt.Sprintf(`
route:
receiver: telegram
group_wait: 0s
group_interval: 1s
receivers:
- name: telegram
telegram_configs:
- api_url: %s
bot_token: xxx
chat_id: 111
`, backendURL)
},
},
}
for receiverName, testData := range tests {
for _, firewallEnabled := range []bool{true, false} {
receiverName := receiverName
testData := testData
firewallEnabled := firewallEnabled
t.Run(fmt.Sprintf("receiver=%s firewall enabled=%v", receiverName, firewallEnabled), func(t *testing.T) {
t.Parallel()
ctx := context.Background()
userID := "user-1"
serverInvoked := atomic.NewBool(false)
// Create a local HTTP server to test whether the request is received.
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
serverInvoked.Store(true)
writer.WriteHeader(http.StatusOK)
}))
defer server.Close()
// Create the alertmanager config.
alertmanagerCfg := testData.getAlertmanagerConfig(fmt.Sprintf("http://%s", server.Listener.Addr().String()))
// Store the alertmanager config in the bucket.
store := prepareInMemoryAlertStore()
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: userID,
RawConfig: alertmanagerCfg,
}))
// Prepare the alertmanager config.
cfg := mockAlertmanagerConfig(t)
// Prepare the limits config.
var limits validation.Limits
flagext.DefaultValues(&limits)
limits.AlertmanagerReceiversBlockPrivateAddresses = firewallEnabled
overrides, err := validation.NewOverrides(limits, nil)
require.NoError(t, err)
// Start the alertmanager.
reg := prometheus.NewPedanticRegistry()
logs := &concurrency.SyncBuffer{}
logger := log.NewLogfmtLogger(logs)
am := setupSingleMultitenantAlertmanager(t, cfg, store, overrides, logger, reg)
// Ensure the configs are synced correctly.
assert.NoError(t, testutil.GatherAndCompare(reg, bytes.NewBufferString(`
# HELP cortex_alertmanager_config_last_reload_successful Boolean set to 1 whenever the last configuration reload attempt was successful.
# TYPE cortex_alertmanager_config_last_reload_successful gauge
cortex_alertmanager_config_last_reload_successful{user="user-1"} 1
`), "cortex_alertmanager_config_last_reload_successful"))
// Create an alert to push.
alerts := types.Alerts(&types.Alert{
Alert: model.Alert{
Labels: map[model.LabelName]model.LabelValue{model.AlertNameLabel: "test"},
StartsAt: time.Now().Add(-time.Minute),
EndsAt: time.Now().Add(time.Minute),
},
UpdatedAt: time.Now(),
Timeout: false,
})
alertsPayload, err := json.Marshal(alerts)
require.NoError(t, err)
// Push an alert.
req := httptest.NewRequest(http.MethodPost, cfg.ExternalURL.String()+"/api/v1/alerts", bytes.NewReader(alertsPayload))
req.Header.Set("content-type", "application/json")
reqCtx := user.InjectOrgID(req.Context(), userID)
{
w := httptest.NewRecorder()
am.ServeHTTP(w, req.WithContext(reqCtx))
resp := w.Result()
_, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, w.Code)
}
// Ensure the server endpoint has not been called if firewall is enabled. Since the alert is delivered
// asynchronously, we should pool it for a short period.
deadline := time.Now().Add(3 * time.Second)
for {
if time.Now().After(deadline) || serverInvoked.Load() {
break
}
time.Sleep(100 * time.Millisecond)
}
assert.Equal(t, !firewallEnabled, serverInvoked.Load())
// Print all alertmanager logs to have more information if this test fails in CI.
t.Logf("Alertmanager logs:\n%s", logs.String())
})
}
}
}
func TestMultitenantAlertmanager_migrateStateFilesToPerTenantDirectories(t *testing.T) {
ctx := context.Background()
const (
user1 = "user1"
user2 = "user2"
)
store := prepareInMemoryAlertStore()
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user2,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
reg := prometheus.NewPedanticRegistry()
cfg := mockAlertmanagerConfig(t)
am, err := createMultitenantAlertmanager(cfg, nil, store, nil, nil, log.NewNopLogger(), reg)
require.NoError(t, err)
createFile(t, filepath.Join(cfg.DataDir, "nflog:"+user1))
createFile(t, filepath.Join(cfg.DataDir, "silences:"+user1))
createFile(t, filepath.Join(cfg.DataDir, "nflog:"+user2))
createFile(t, filepath.Join(cfg.DataDir, "templates", user2, "template.tpl"))
require.NoError(t, am.migrateStateFilesToPerTenantDirectories())
require.True(t, fileExists(t, filepath.Join(cfg.DataDir, user1, notificationLogSnapshot)))
require.True(t, fileExists(t, filepath.Join(cfg.DataDir, user1, silencesSnapshot)))
require.True(t, fileExists(t, filepath.Join(cfg.DataDir, user2, notificationLogSnapshot)))
require.True(t, dirExists(t, filepath.Join(cfg.DataDir, user2, templatesDir)))
require.True(t, fileExists(t, filepath.Join(cfg.DataDir, user2, templatesDir, "template.tpl")))
}
func fileExists(t *testing.T, path string) bool {
return checkExists(t, path, false)
}
func dirExists(t *testing.T, path string) bool {
return checkExists(t, path, true)
}
func checkExists(t *testing.T, path string, dir bool) bool {
fi, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false
}
require.NoError(t, err)
}
require.Equal(t, dir, fi.IsDir())
return true
}
func TestMultitenantAlertmanager_deleteUnusedLocalUserState(t *testing.T) {
ctx := context.Background()
const (
user1 = "user1"
user2 = "user2"
)
store := prepareInMemoryAlertStore()
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user2,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
reg := prometheus.NewPedanticRegistry()
cfg := mockAlertmanagerConfig(t)
am := setupSingleMultitenantAlertmanager(t, cfg, store, nil, log.NewNopLogger(), reg)
createFile(t, filepath.Join(cfg.DataDir, user1, notificationLogSnapshot))
createFile(t, filepath.Join(cfg.DataDir, user1, silencesSnapshot))
createFile(t, filepath.Join(cfg.DataDir, user2, notificationLogSnapshot))
createFile(t, filepath.Join(cfg.DataDir, user2, templatesDir, "template.tpl"))
dirs := am.getPerUserDirectories()
require.Equal(t, 2, len(dirs))
require.NotZero(t, dirs[user1])
require.NotZero(t, dirs[user2])
// Ensure the configs are synced correctly
err := am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
// loadAndSyncConfigs also cleans up obsolete files. Let's verify that.
dirs = am.getPerUserDirectories()
require.Zero(t, dirs[user1]) // has no configuration, files were deleted
require.NotZero(t, dirs[user2]) // has config, files survived
}
func TestMultitenantAlertmanager_zoneAwareSharding(t *testing.T) {
ctx := context.Background()
alertStore := prepareInMemoryAlertStore()
ringStore, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil)
t.Cleanup(func() { assert.NoError(t, closer.Close()) })
const (
user1 = "user1"
user2 = "user2"
user3 = "user3"
)
createInstance := func(i int, zone string, registries *util.UserRegistries) *MultitenantAlertmanager {
reg := prometheus.NewPedanticRegistry()
cfg := mockAlertmanagerConfig(t)
instanceID := fmt.Sprintf("instance-%d", i)
registries.AddUserRegistry(instanceID, reg)
cfg.ShardingRing.ReplicationFactor = 2
cfg.ShardingRing.InstanceID = instanceID
cfg.ShardingRing.InstanceAddr = fmt.Sprintf("127.0.0.1-%d", i)
cfg.ShardingRing.ZoneAwarenessEnabled = true
cfg.ShardingRing.InstanceZone = zone
am, err := createMultitenantAlertmanager(cfg, nil, alertStore, ringStore, nil, log.NewLogfmtLogger(os.Stdout), reg)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, services.StopAndAwaitTerminated(ctx, am))
})
require.NoError(t, services.StartAndAwaitRunning(ctx, am))
return am
}
registriesZoneA := util.NewUserRegistries()
registriesZoneB := util.NewUserRegistries()
am1ZoneA := createInstance(1, "zoneA", registriesZoneA)
am2ZoneA := createInstance(2, "zoneA", registriesZoneA)
am1ZoneB := createInstance(3, "zoneB", registriesZoneB)
{
require.NoError(t, alertStore.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user1,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
require.NoError(t, alertStore.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user2,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
require.NoError(t, alertStore.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user3,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
err := am1ZoneA.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
err = am2ZoneA.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
err = am1ZoneB.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
}
metricsZoneA := registriesZoneA.BuildMetricFamiliesPerUser()
metricsZoneB := registriesZoneB.BuildMetricFamiliesPerUser()
assert.Equal(t, float64(3), metricsZoneA.GetSumOfGauges("cortex_alertmanager_tenants_owned"))
assert.Equal(t, float64(3), metricsZoneB.GetSumOfGauges("cortex_alertmanager_tenants_owned"))
}
func TestMultitenantAlertmanager_deleteUnusedRemoteUserState(t *testing.T) {
ctx := context.Background()
const (
user1 = "user1"
user2 = "user2"
)
alertStore := prepareInMemoryAlertStore()
ringStore, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil)
t.Cleanup(func() { assert.NoError(t, closer.Close()) })
createInstance := func(i int) *MultitenantAlertmanager {
reg := prometheus.NewPedanticRegistry()
cfg := mockAlertmanagerConfig(t)
cfg.ShardingRing.ReplicationFactor = 1
cfg.ShardingRing.InstanceID = fmt.Sprintf("instance-%d", i)
cfg.ShardingRing.InstanceAddr = fmt.Sprintf("127.0.0.1-%d", i)
// Increase state write interval so that state gets written sooner, making test faster.
cfg.Persister.Interval = 500 * time.Millisecond
am, err := createMultitenantAlertmanager(cfg, nil, alertStore, ringStore, nil, log.NewLogfmtLogger(os.Stdout), reg)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, services.StopAndAwaitTerminated(ctx, am))
})
require.NoError(t, services.StartAndAwaitRunning(ctx, am))
return am
}
// Create two instances. With replication factor of 1, this means that only one
// of the instances will own the user. This tests that an instance does not delete
// state for users that are configured, but are owned by other instances.
am1 := createInstance(1)
am2 := createInstance(2)
// Configure the users and wait for the state persister to write some state for both.
{
require.NoError(t, alertStore.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user1,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
require.NoError(t, alertStore.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: user2,
RawConfig: simpleConfigOne,
Templates: []*alertspb.TemplateDesc{},
}))
err := am1.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
err = am2.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
require.Eventually(t, func() bool {
_, err1 := alertStore.GetFullState(context.Background(), user1)
_, err2 := alertStore.GetFullState(context.Background(), user2)
return err1 == nil && err2 == nil
}, 5*time.Second, 100*time.Millisecond, "timed out waiting for state to be persisted")
}
// Perform another sync to trigger cleanup; this should have no effect.
{
err := am1.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
err = am2.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
_, err = alertStore.GetFullState(context.Background(), user1)
require.NoError(t, err)
_, err = alertStore.GetFullState(context.Background(), user2)
require.NoError(t, err)
}
// Delete one configuration and trigger cleanup; state for only that user should be deleted.
{
require.NoError(t, alertStore.DeleteAlertConfig(ctx, user1))
err := am1.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
err = am2.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
_, err = alertStore.GetFullState(context.Background(), user1)
require.Equal(t, alertspb.ErrNotFound, err)
_, err = alertStore.GetFullState(context.Background(), user2)
require.NoError(t, err)
}
}
func createFile(t *testing.T, path string) string {
dir := filepath.Dir(path)
require.NoError(t, os.MkdirAll(dir, 0777))
f, err := os.Create(path)
require.NoError(t, err)
require.NoError(t, f.Close())
return path
}
func TestMultitenantAlertmanager_ServeHTTP(t *testing.T) {
// Run this test using a real storage client.
store := prepareInMemoryAlertStore()
amConfig := mockAlertmanagerConfig(t)
externalURL := flagext.URLValue{}
err := externalURL.Set("http://localhost:8080/alertmanager")
require.NoError(t, err)
amConfig.ExternalURL = externalURL
// Create the Multitenant Alertmanager.
reg := prometheus.NewPedanticRegistry()
am := setupSingleMultitenantAlertmanager(t, amConfig, store, nil, log.NewNopLogger(), reg)
// Request when no user configuration is present.
req := httptest.NewRequest("GET", externalURL.String(), nil)
ctx := user.InjectOrgID(req.Context(), "user1")
{
w := httptest.NewRecorder()
am.ServeHTTP(w, req.WithContext(ctx))
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
require.Equal(t, 404, w.Code)
require.Equal(t, "the Alertmanager is not configured\n", string(body))
}
// Create a configuration for the user in storage.
require.NoError(t, store.SetAlertConfig(ctx, alertspb.AlertConfigDesc{
User: "user1",
RawConfig: simpleConfigTwo,
Templates: []*alertspb.TemplateDesc{},
}))
// Make the alertmanager pick it up.
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
// Request when AM is active.
{
w := httptest.NewRecorder()
am.ServeHTTP(w, req.WithContext(ctx))
require.Equal(t, 301, w.Code) // redirect to UI
}
// Verify that GET /metrics returns 404 even when AM is active.
{
metricURL := externalURL.String() + "/metrics"
require.Equal(t, "http://localhost:8080/alertmanager/metrics", metricURL)
verify404(ctx, t, am, "GET", metricURL)
}
// Verify that POST /-/reload returns 404 even when AM is active.
{
metricURL := externalURL.String() + "/-/reload"
require.Equal(t, "http://localhost:8080/alertmanager/-/reload", metricURL)
verify404(ctx, t, am, "POST", metricURL)
}
// Verify that GET /debug/index returns 404 even when AM is active.
{
// Register pprof Index (under non-standard path, but this path is exposed by AM using default MUX!)
http.HandleFunc("/alertmanager/debug/index", pprof.Index)
metricURL := externalURL.String() + "/debug/index"
require.Equal(t, "http://localhost:8080/alertmanager/debug/index", metricURL)
verify404(ctx, t, am, "GET", metricURL)
}
// Remove the tenant's Alertmanager
require.NoError(t, store.DeleteAlertConfig(ctx, "user1"))
err = am.loadAndSyncConfigs(context.Background(), reasonPeriodic)
require.NoError(t, err)
{
// Request when the alertmanager is gone
w := httptest.NewRecorder()
am.ServeHTTP(w, req.WithContext(ctx))
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
require.Equal(t, 404, w.Code)
require.Equal(t, "the Alertmanager is not configured\n", string(body))
}
}
func verify404(ctx context.Context, t *testing.T, am *MultitenantAlertmanager, method string, url string) {
metricsReq := httptest.NewRequest(method, url, strings.NewReader("Hello")) // Body for POST Request.
w := httptest.NewRecorder()
am.ServeHTTP(w, metricsReq.WithContext(ctx))
require.Equal(t, 404, w.Code)
}
func TestMultitenantAlertmanager_ServeHTTPWithFallbackConfig(t *testing.T) {
ctx := context.Background()
amConfig := mockAlertmanagerConfig(t)
// Run this test using a real storage client.
store := prepareInMemoryAlertStore()
externalURL := flagext.URLValue{}
err := externalURL.Set("http://localhost:8080/alertmanager")
require.NoError(t, err)
fallbackCfg := `
global:
smtp_smarthost: 'localhost:25'
smtp_from: 'youraddress@example.org'
route:
receiver: example-email
receivers:
- name: example-email
email_configs:
- to: 'youraddress@example.org'
`
amConfig.ExternalURL = externalURL
// Create the Multitenant Alertmanager.
am := setupSingleMultitenantAlertmanager(t, amConfig, store, nil, log.NewNopLogger(), nil)
require.NoError(t, err)
am.fallbackConfig = fallbackCfg
// Request when no user configuration is present.
req := httptest.NewRequest("GET", externalURL.String()+"/api/v1/status", nil)
w := httptest.NewRecorder()
am.ServeHTTP(w, req.WithContext(user.InjectOrgID(req.Context(), "user1")))
resp := w.Result()
// It succeeds and the Alertmanager is started.
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Len(t, am.alertmanagers, 1)
_, exists := am.alertmanagers["user1"]
require.True(t, exists)
// Even after a poll...
err = am.loadAndSyncConfigs(ctx, reasonPeriodic)
require.NoError(t, err)
// It does not remove the Alertmanager.
require.Len(t, am.alertmanagers, 1)
_, exists = am.alertmanagers["user1"]
require.True(t, exists)
// Remove the Alertmanager configuration.