-
Notifications
You must be signed in to change notification settings - Fork 142
/
vmagent.go
1471 lines (1361 loc) · 51.3 KB
/
vmagent.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
package vmagent
import (
"context"
"fmt"
"path"
"sort"
"strconv"
"strings"
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmalert/utils"
victoriametricsv1beta1 "github.com/VictoriaMetrics/operator/api/v1beta1"
"github.com/VictoriaMetrics/operator/controllers/factory/build"
"github.com/VictoriaMetrics/operator/controllers/factory/finalize"
"github.com/VictoriaMetrics/operator/controllers/factory/k8stools"
"github.com/VictoriaMetrics/operator/controllers/factory/logger"
"github.com/VictoriaMetrics/operator/controllers/factory/reconcile"
"github.com/VictoriaMetrics/operator/internal/config"
"github.com/hashicorp/go-version"
"gopkg.in/yaml.v2"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
vmAgentConfDir = "/etc/vmagent/config"
vmAgentConOfOutDir = "/etc/vmagent/config_out"
vmAgentPersistentQueueDir = "/tmp/vmagent-remotewrite-data"
vmAgentPersistentQueueSTSDir = "/vmagent_pq/vmagent-remotewrite-data"
vmAgentPersistentQueueMountName = "persistent-queue-data"
globalRelabelingName = "global_relabeling.yaml"
urlRelabelingName = "url_relabeling-%d.yaml"
shardNumPlaceholder = "%SHARD_NUM%"
tlsAssetsDir = "/etc/vmagent-tls/certs"
vmagentGzippedFilename = "vmagent.yaml.gz"
configEnvsubstFilename = "vmagent.env.yaml"
)
// To save compatibility in the single-shard version still need to fill in %SHARD_NUM% placeholder
var defaultPlaceholders = map[string]string{shardNumPlaceholder: "0"}
// CreateOrUpdateVMAgentService creates service for vmagent
func CreateOrUpdateVMAgentService(ctx context.Context, cr *victoriametricsv1beta1.VMAgent, rclient client.Client, c *config.BaseOperatorConf) (*corev1.Service, error) {
cr = cr.DeepCopy()
if cr.Spec.Port == "" {
cr.Spec.Port = c.VMAgentDefault.Port
}
newService := build.Service(cr, cr.Spec.Port, func(svc *corev1.Service) {
if cr.Spec.StatefulMode {
svc.Spec.ClusterIP = "None"
}
build.AppendInsertPortsToService(cr.Spec.InsertPorts, svc)
})
if err := cr.Spec.ServiceSpec.IsSomeAndThen(func(s *victoriametricsv1beta1.AdditionalServiceSpec) error {
additionalService := build.AdditionalServiceFromDefault(newService, cr.Spec.ServiceSpec)
if additionalService.Name == newService.Name {
logger.WithContext(ctx).Error(fmt.Errorf("vmagent additional service name: %q cannot be the same as crd.prefixedname: %q", additionalService.Name, newService.Name), "cannot create additional service")
} else if err := reconcile.ServiceForCRD(ctx, rclient, additionalService); err != nil {
return fmt.Errorf("cannot reconcile additional service for vmagent: %w", err)
}
return nil
}); err != nil {
return nil, err
}
rca := finalize.RemoveSvcArgs{SelectorLabels: cr.SelectorLabels, GetNameSpace: cr.GetNamespace, PrefixedName: cr.PrefixedName}
if err := finalize.RemoveOrphanedServices(ctx, rclient, rca, cr.Spec.ServiceSpec); err != nil {
return nil, err
}
if err := reconcile.ServiceForCRD(ctx, rclient, newService); err != nil {
return nil, fmt.Errorf("cannot reconcile service for vmagent: %w", err)
}
return newService, nil
}
// CreateOrUpdateVMAgent creates deployment for vmagent and configures it
// waits for healthy state
func CreateOrUpdateVMAgent(ctx context.Context, cr *victoriametricsv1beta1.VMAgent, rclient client.Client, c *config.BaseOperatorConf) error {
l := logger.WithContext(ctx).WithValues("controller", "vmagent.crud", "namespace", cr.Namespace, "vmagent", cr.PrefixedName())
ctx = logger.AddToContext(ctx, l)
if cr.IsOwnsServiceAccount() {
if err := reconcile.ServiceAccount(ctx, rclient, build.ServiceAccount(cr)); err != nil {
return fmt.Errorf("failed create service account: %w", err)
}
if !cr.Spec.IngestOnlyMode {
if err := createVMAgentK8sAPIAccess(ctx, cr, rclient, config.IsClusterWideAccessAllowed()); err != nil {
return fmt.Errorf("cannot create vmagent role and binding for it, err: %w", err)
}
}
}
ssCache, err := createOrUpdateConfigurationSecret(ctx, cr, rclient, c)
if err != nil {
return err
}
if err := createOrUpdateRelabelConfigsAssets(ctx, cr, rclient); err != nil {
return fmt.Errorf("cannot update relabeling asset for vmagent: %w", err)
}
if err := CreateOrUpdateVMAgentStreamAggrConfig(ctx, cr, rclient); err != nil {
return fmt.Errorf("cannot update stream aggregation config for vmagent: %w", err)
}
if cr.Spec.PodDisruptionBudget != nil {
err = reconcile.PDB(ctx, rclient, build.PodDisruptionBudget(cr, cr.Spec.PodDisruptionBudget))
if err != nil {
return fmt.Errorf("cannot update pod disruption budget for vmagent: %w", err)
}
}
newDeploy, err := newDeployForVMAgent(cr, c, ssCache)
if err != nil {
return fmt.Errorf("cannot build new deploy for vmagent: %w", err)
}
deploymentNames := make(map[string]struct{})
stsNames := make(map[string]struct{})
if cr.Spec.ShardCount != nil && *cr.Spec.ShardCount > 1 {
shardsCount := *cr.Spec.ShardCount
l.Info("using cluster version of VMAgent with", "shards", shardsCount)
for shardNum := 0; shardNum < shardsCount; shardNum++ {
shardedDeploy := newDeploy.DeepCopyObject()
addShardSettingsToVMAgent(shardNum, shardsCount, shardedDeploy)
placeholders := map[string]string{shardNumPlaceholder: strconv.Itoa(shardNum)}
switch shardedDeploy := shardedDeploy.(type) {
case *appsv1.Deployment:
shardedDeploy, err = k8stools.RenderPlaceholders(shardedDeploy, placeholders)
if err != nil {
return fmt.Errorf("cannot fill placeholders for deployment sharded vmagent: %w", err)
}
if err := reconcile.Deployment(ctx, rclient, shardedDeploy, c.PodWaitReadyTimeout, false); err != nil {
return err
}
deploymentNames[shardedDeploy.Name] = struct{}{}
case *appsv1.StatefulSet:
shardedDeploy, err = k8stools.RenderPlaceholders(shardedDeploy, placeholders)
if err != nil {
return fmt.Errorf("cannot fill placeholders for sts in sharded vmagent: %w", err)
}
stsOpts := reconcile.STSOptions{
HasClaim: len(shardedDeploy.Spec.VolumeClaimTemplates) > 0,
SelectorLabels: func() map[string]string {
selectorLabels := cr.SelectorLabels()
selectorLabels["shard-num"] = strconv.Itoa(shardNum)
return selectorLabels
},
VolumeName: func() string {
return vmAgentPersistentQueueMountName
},
UpdateStrategy: cr.STSUpdateStrategy,
}
if err := reconcile.HandleSTSUpdate(ctx, rclient, stsOpts, shardedDeploy, c); err != nil {
return err
}
stsNames[shardedDeploy.Name] = struct{}{}
}
}
} else {
switch newDeploy := newDeploy.(type) {
case *appsv1.Deployment:
newDeploy, err = k8stools.RenderPlaceholders(newDeploy, defaultPlaceholders)
if err != nil {
return fmt.Errorf("cannot fill placeholders for deployment in vmagent: %w", err)
}
if err := reconcile.Deployment(ctx, rclient, newDeploy, c.PodWaitReadyTimeout, false); err != nil {
return err
}
deploymentNames[newDeploy.Name] = struct{}{}
case *appsv1.StatefulSet:
newDeploy, err = k8stools.RenderPlaceholders(newDeploy, defaultPlaceholders)
if err != nil {
return fmt.Errorf("cannot fill placeholders for sts in vmagent: %w", err)
}
stsOpts := reconcile.STSOptions{
HasClaim: len(newDeploy.Spec.VolumeClaimTemplates) > 0,
SelectorLabels: cr.SelectorLabels,
VolumeName: func() string {
return vmAgentPersistentQueueMountName
},
UpdateStrategy: cr.STSUpdateStrategy,
}
if err := reconcile.HandleSTSUpdate(ctx, rclient, stsOpts, newDeploy, c); err != nil {
return err
}
stsNames[newDeploy.Name] = struct{}{}
}
}
if err := finalize.RemoveOrphanedDeployments(ctx, rclient, cr, deploymentNames); err != nil {
return err
}
if err := finalize.RemoveOrphanedSTSs(ctx, rclient, cr, stsNames); err != nil {
return err
}
return nil
}
func setDefaultForVMAgent(cr *victoriametricsv1beta1.VMAgent, c *config.BaseOperatorConf) {
// inject default
if cr.Spec.Image.Repository == "" {
cr.Spec.Image.Repository = c.VMAgentDefault.Image
}
if cr.Spec.Image.Tag == "" {
cr.Spec.Image.Tag = c.VMAgentDefault.Version
}
if cr.Spec.Image.PullPolicy == "" {
cr.Spec.Image.PullPolicy = corev1.PullIfNotPresent
}
if cr.Spec.Port == "" {
cr.Spec.Port = c.VMAgentDefault.Port
}
}
// newDeployForVMAgent builds vmagent deployment spec.
func newDeployForVMAgent(cr *victoriametricsv1beta1.VMAgent, c *config.BaseOperatorConf, ssCache *scrapesSecretsCache) (runtime.Object, error) {
cr = cr.DeepCopy()
setDefaultForVMAgent(cr, c)
podSpec, err := makeSpecForVMAgent(cr, c, ssCache)
if err != nil {
return nil, err
}
// fast path, use sts
if cr.Spec.StatefulMode {
stsSpec := &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: cr.PrefixedName(),
Namespace: cr.Namespace,
Labels: c.Labels.Merge(cr.AllLabels()),
Annotations: cr.AnnotationsFiltered(),
OwnerReferences: cr.AsOwner(),
Finalizers: []string{victoriametricsv1beta1.FinalizerName},
},
Spec: appsv1.StatefulSetSpec{
MinReadySeconds: cr.Spec.MinReadySeconds,
Replicas: cr.Spec.ReplicaCount,
RevisionHistoryLimit: cr.Spec.RevisionHistoryLimitCount,
Selector: &metav1.LabelSelector{
MatchLabels: cr.SelectorLabels(),
},
UpdateStrategy: appsv1.StatefulSetUpdateStrategy{
Type: appsv1.OnDeleteStatefulSetStrategyType,
},
PodManagementPolicy: appsv1.ParallelPodManagement,
ServiceName: buildSTSServiceName(cr),
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: cr.PodLabels(),
Annotations: cr.PodAnnotations(),
},
Spec: *podSpec,
},
},
}
if cr.STSUpdateStrategy() == appsv1.RollingUpdateStatefulSetStrategyType {
stsSpec.Spec.PodManagementPolicy = appsv1.OrderedReadyPodManagement
}
cr.Spec.StatefulStorage.IntoSTSVolume(vmAgentPersistentQueueMountName, &stsSpec.Spec)
stsSpec.Spec.VolumeClaimTemplates = append(stsSpec.Spec.VolumeClaimTemplates, cr.Spec.ClaimTemplates...)
return stsSpec, nil
}
strategyType := appsv1.RollingUpdateDeploymentStrategyType
if cr.Spec.UpdateStrategy != nil {
strategyType = *cr.Spec.UpdateStrategy
}
depSpec := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: cr.PrefixedName(),
Namespace: cr.Namespace,
Labels: c.Labels.Merge(cr.AllLabels()),
Annotations: cr.AnnotationsFiltered(),
OwnerReferences: cr.AsOwner(),
Finalizers: []string{victoriametricsv1beta1.FinalizerName},
},
Spec: appsv1.DeploymentSpec{
MinReadySeconds: cr.Spec.MinReadySeconds,
Replicas: cr.Spec.ReplicaCount,
RevisionHistoryLimit: cr.Spec.RevisionHistoryLimitCount,
Selector: &metav1.LabelSelector{
MatchLabels: cr.SelectorLabels(),
},
Strategy: appsv1.DeploymentStrategy{
Type: strategyType,
RollingUpdate: cr.Spec.RollingUpdate,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: cr.PodLabels(),
Annotations: cr.PodAnnotations(),
},
Spec: *podSpec,
},
},
}
return depSpec, nil
}
func buildSTSServiceName(cr *victoriametricsv1beta1.VMAgent) string {
// set service name for sts if additional service is headless
if cr.Spec.ServiceSpec != nil &&
!cr.Spec.ServiceSpec.UseAsDefault &&
cr.Spec.ServiceSpec.Spec.ClusterIP == corev1.ClusterIPNone {
return cr.Spec.ServiceSpec.NameOrDefault(cr.PrefixedName())
}
return ""
}
func makeSpecForVMAgent(cr *victoriametricsv1beta1.VMAgent, c *config.BaseOperatorConf, ssCache *scrapesSecretsCache) (*corev1.PodSpec, error) {
var args []string
if len(cr.Spec.RemoteWrite) > 0 {
args = append(args, buildRemoteWrites(cr, ssCache)...)
}
args = append(args, buildRemoteWriteSettings(cr)...)
args = append(args, fmt.Sprintf("-httpListenAddr=:%s", cr.Spec.Port))
if cr.Spec.LogLevel != "" {
args = append(args, fmt.Sprintf("-loggerLevel=%s", cr.Spec.LogLevel))
}
if cr.Spec.LogFormat != "" {
args = append(args, fmt.Sprintf("-loggerFormat=%s", cr.Spec.LogFormat))
}
if len(cr.Spec.ExtraEnvs) > 0 {
args = append(args, "-envflag.enable=true")
}
args = cr.Spec.License.MaybeAddToArgs(args, victoriametricsv1beta1.SecretsDir)
var envs []corev1.EnvVar
envs = append(envs, cr.Spec.ExtraEnvs...)
var ports []corev1.ContainerPort
ports = append(ports, corev1.ContainerPort{Name: "http", Protocol: "TCP", ContainerPort: intstr.Parse(cr.Spec.Port).IntVal})
ports = build.AppendInsertPorts(ports, cr.Spec.InsertPorts)
var agentVolumeMounts []corev1.VolumeMount
// mount data path any way, even if user changes its value
// we cannot rely on value of remoteWriteSettings.
pqMountPath := vmAgentPersistentQueueDir
if cr.Spec.StatefulMode {
pqMountPath = vmAgentPersistentQueueSTSDir
}
agentVolumeMounts = append(agentVolumeMounts,
corev1.VolumeMount{
Name: vmAgentPersistentQueueMountName,
MountPath: pqMountPath,
},
)
agentVolumeMounts = append(agentVolumeMounts, cr.Spec.VolumeMounts...)
var volumes []corev1.Volume
// in case for sts, we have to use persistentVolumeClaimTemplate instead
if !cr.Spec.StatefulMode {
volumes = append(volumes, corev1.Volume{
Name: vmAgentPersistentQueueMountName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
})
}
volumes = append(volumes, cr.Spec.Volumes...)
if !cr.Spec.IngestOnlyMode {
args = append(args,
fmt.Sprintf("-promscrape.config=%s", path.Join(vmAgentConOfOutDir, configEnvsubstFilename)))
volumes = append(volumes,
corev1.Volume{
Name: "tls-assets",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: cr.TLSAssetName(),
},
},
},
corev1.Volume{
Name: "config-out",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
)
agentVolumeMounts = append(agentVolumeMounts,
corev1.VolumeMount{
Name: "config-out",
ReadOnly: true,
MountPath: vmAgentConOfOutDir,
},
corev1.VolumeMount{
Name: "tls-assets",
ReadOnly: true,
MountPath: tlsAssetsDir,
},
)
volumes = append(volumes,
corev1.Volume{
Name: "config",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: cr.PrefixedName(),
},
},
})
agentVolumeMounts = append(agentVolumeMounts,
corev1.VolumeMount{
Name: "config",
ReadOnly: true,
MountPath: vmAgentConfDir,
})
}
if cr.HasAnyStreamAggrConfigs() {
volumes = append(volumes, corev1.Volume{
Name: "stream-aggr-conf",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: cr.StreamAggrConfigName(),
},
},
},
},
)
agentVolumeMounts = append(agentVolumeMounts, corev1.VolumeMount{
Name: "stream-aggr-conf",
ReadOnly: true,
MountPath: victoriametricsv1beta1.StreamAggrConfigDir,
},
)
}
if cr.HasAnyRelabellingConfigs() {
volumes = append(volumes,
corev1.Volume{
Name: "relabeling-assets",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: cr.RelabelingAssetName(),
},
},
},
},
)
agentVolumeMounts = append(agentVolumeMounts,
corev1.VolumeMount{
Name: "relabeling-assets",
ReadOnly: true,
MountPath: victoriametricsv1beta1.RelabelingConfigDir,
},
)
}
for _, s := range cr.Spec.Secrets {
volumes = append(volumes, corev1.Volume{
Name: k8stools.SanitizeVolumeName("secret-" + s),
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: s,
},
},
})
agentVolumeMounts = append(agentVolumeMounts, corev1.VolumeMount{
Name: k8stools.SanitizeVolumeName("secret-" + s),
ReadOnly: true,
MountPath: path.Join(victoriametricsv1beta1.SecretsDir, s),
})
}
for _, c := range cr.Spec.ConfigMaps {
volumes = append(volumes, corev1.Volume{
Name: k8stools.SanitizeVolumeName("configmap-" + c),
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: c,
},
},
},
})
agentVolumeMounts = append(agentVolumeMounts, corev1.VolumeMount{
Name: k8stools.SanitizeVolumeName("configmap-" + c),
ReadOnly: true,
MountPath: path.Join(victoriametricsv1beta1.ConfigMapsDir, c),
})
}
volumes, agentVolumeMounts = cr.Spec.License.MaybeAddToVolumes(volumes, agentVolumeMounts, victoriametricsv1beta1.SecretsDir)
args = cr.Spec.License.MaybeAddToArgs(args, victoriametricsv1beta1.SecretsDir)
if cr.Spec.RelabelConfig != nil || len(cr.Spec.InlineRelabelConfig) > 0 {
args = append(args, "-remoteWrite.relabelConfig="+path.Join(victoriametricsv1beta1.RelabelingConfigDir, globalRelabelingName))
}
args = build.AppendArgsForInsertPorts(args, cr.Spec.InsertPorts)
specRes := build.Resources(cr.Spec.Resources, config.Resource(c.VMAgentDefault.Resource), c.VMAgentDefault.UseDefaultResources)
args = build.AddExtraArgsOverrideDefaults(args, cr.Spec.ExtraArgs, "-")
sort.Strings(args)
vmagentContainer := corev1.Container{
Name: "vmagent",
Image: fmt.Sprintf("%s:%s", build.FormatContainerImage(c.ContainerRegistry, cr.Spec.Image.Repository), cr.Spec.Image.Tag),
ImagePullPolicy: cr.Spec.Image.PullPolicy,
Ports: ports,
Args: args,
Env: envs,
VolumeMounts: agentVolumeMounts,
Resources: specRes,
TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
}
vmagentContainer = build.Probe(vmagentContainer, cr)
var operatorContainers []corev1.Container
var ic []corev1.Container
// conditional add config reloader container
if !cr.Spec.IngestOnlyMode || cr.HasAnyRelabellingConfigs() || cr.HasAnyStreamAggrConfigs() {
configReloader := buildConfigReloaderContainer(cr, c)
operatorContainers = append(operatorContainers, configReloader)
if !cr.Spec.IngestOnlyMode {
ic = append(ic,
buildInitConfigContainer(c.VMAgentDefault.ConfigReloadImage, buildConfigReloaderResourceReqsForVMAgent(c), c, configReloader.Args)...)
if len(cr.Spec.InitContainers) > 0 {
var err error
ic, err = k8stools.MergePatchContainers(ic, cr.Spec.InitContainers)
if err != nil {
return nil, fmt.Errorf("cannot apply patch for initContainers: %w", err)
}
}
}
}
operatorContainers = append(operatorContainers, vmagentContainer)
containers, err := k8stools.MergePatchContainers(operatorContainers, cr.Spec.Containers)
if err != nil {
return nil, err
}
for i := range cr.Spec.TopologySpreadConstraints {
if cr.Spec.TopologySpreadConstraints[i].LabelSelector == nil {
cr.Spec.TopologySpreadConstraints[i].LabelSelector = &metav1.LabelSelector{
MatchLabels: cr.SelectorLabels(),
}
}
}
useStrictSecurity := c.EnableStrictSecurity
if cr.Spec.UseStrictSecurity != nil {
useStrictSecurity = *cr.Spec.UseStrictSecurity
}
return &corev1.PodSpec{
NodeSelector: cr.Spec.NodeSelector,
Volumes: volumes,
InitContainers: build.AddStrictSecuritySettingsToContainers(ic, useStrictSecurity),
Containers: build.AddStrictSecuritySettingsToContainers(containers, useStrictSecurity),
ServiceAccountName: cr.GetServiceAccountName(),
SecurityContext: build.AddStrictSecuritySettingsToPod(cr.Spec.SecurityContext, useStrictSecurity),
ImagePullSecrets: cr.Spec.ImagePullSecrets,
Affinity: cr.Spec.Affinity,
SchedulerName: cr.Spec.SchedulerName,
Tolerations: cr.Spec.Tolerations,
PriorityClassName: cr.Spec.PriorityClassName,
HostNetwork: cr.Spec.HostNetwork,
DNSPolicy: cr.Spec.DNSPolicy,
DNSConfig: cr.Spec.DNSConfig,
RuntimeClassName: cr.Spec.RuntimeClassName,
HostAliases: cr.Spec.HostAliases,
TopologySpreadConstraints: cr.Spec.TopologySpreadConstraints,
TerminationGracePeriodSeconds: cr.Spec.TerminationGracePeriodSeconds,
ReadinessGates: cr.Spec.ReadinessGates,
}, nil
}
func addShardSettingsToVMAgent(shardNum, shardsCount int, dep runtime.Object) {
var containers []corev1.Container
switch dep := dep.(type) {
case *appsv1.StatefulSet:
containers = dep.Spec.Template.Spec.Containers
dep.Name = fmt.Sprintf("%s-%d", dep.Name, shardNum)
// need to mutate selectors ?
dep.Spec.Selector.MatchLabels["shard-num"] = strconv.Itoa(shardNum)
dep.Spec.Template.Labels["shard-num"] = strconv.Itoa(shardNum)
case *appsv1.Deployment:
containers = dep.Spec.Template.Spec.Containers
dep.Name = fmt.Sprintf("%s-%d", dep.Name, shardNum)
// need to mutate selectors ?
dep.Spec.Selector.MatchLabels["shard-num"] = strconv.Itoa(shardNum)
dep.Spec.Template.Labels["shard-num"] = strconv.Itoa(shardNum)
}
for i := range containers {
container := &containers[i]
if container.Name == "vmagent" {
args := container.Args
// filter extraArgs defined by user
cnt := 0
for i := range args {
arg := args[i]
if !strings.Contains(arg, "promscrape.cluster.membersCount") && !strings.Contains(arg, "promscrape.cluster.memberNum") {
args[cnt] = arg
cnt++
}
}
args = args[:cnt]
args = append(args, fmt.Sprintf("-promscrape.cluster.membersCount=%d", shardsCount))
args = append(args, fmt.Sprintf("-promscrape.cluster.memberNum=%d", shardNum))
container.Args = args
}
}
}
// buildVMAgentRelabelingsAssets combines all possible relabeling config configuration and adding it to the configmap.
func buildVMAgentRelabelingsAssets(ctx context.Context, cr *victoriametricsv1beta1.VMAgent, rclient client.Client) (*corev1.ConfigMap, error) {
cfgCM := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: cr.Namespace,
Name: cr.RelabelingAssetName(),
Labels: cr.AllLabels(),
Annotations: cr.AnnotationsFiltered(),
OwnerReferences: cr.AsOwner(),
},
Data: make(map[string]string),
}
// global section
if len(cr.Spec.InlineRelabelConfig) > 0 {
rcs := addRelabelConfigs(nil, cr.Spec.InlineRelabelConfig)
data, err := yaml.Marshal(rcs)
if err != nil {
return nil, fmt.Errorf("cannot serialize relabelConfig as yaml: %w", err)
}
if len(data) > 0 {
cfgCM.Data[globalRelabelingName] = string(data)
}
}
if cr.Spec.RelabelConfig != nil {
// need to fetch content from
data, err := fetchConfigMapContentByKey(ctx, rclient,
&corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: cr.Spec.RelabelConfig.Name, Namespace: cr.Namespace}},
cr.Spec.RelabelConfig.Key)
if err != nil {
return nil, fmt.Errorf("cannot fetch configmap: %s, err: %w", cr.Spec.RelabelConfig.Name, err)
}
if len(data) > 0 {
cfgCM.Data[globalRelabelingName] += data
}
}
// per remoteWrite section.
for i := range cr.Spec.RemoteWrite {
rw := cr.Spec.RemoteWrite[i]
if len(rw.InlineUrlRelabelConfig) > 0 {
rcs := addRelabelConfigs(nil, rw.InlineUrlRelabelConfig)
data, err := yaml.Marshal(rcs)
if err != nil {
return nil, fmt.Errorf("cannot serialize urlRelabelConfig as yaml: %w", err)
}
if len(data) > 0 {
cfgCM.Data[fmt.Sprintf(urlRelabelingName, i)] = string(data)
}
}
if rw.UrlRelabelConfig != nil {
data, err := fetchConfigMapContentByKey(ctx, rclient,
&corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: rw.UrlRelabelConfig.Name, Namespace: cr.Namespace}},
rw.UrlRelabelConfig.Key)
if err != nil {
return nil, fmt.Errorf("cannot fetch configmap: %s, err: %w", rw.UrlRelabelConfig.Name, err)
}
if len(data) > 0 {
cfgCM.Data[fmt.Sprintf(urlRelabelingName, i)] += data
}
}
}
return cfgCM, nil
}
// createOrUpdateRelabelConfigsAssets builds relabeling configs for vmagent at separate configmap, serialized as yaml
func createOrUpdateRelabelConfigsAssets(ctx context.Context, cr *victoriametricsv1beta1.VMAgent, rclient client.Client) error {
if !cr.HasAnyRelabellingConfigs() {
return nil
}
assestsCM, err := buildVMAgentRelabelingsAssets(ctx, cr, rclient)
if err != nil {
return err
}
var existCM corev1.ConfigMap
if err := rclient.Get(ctx, types.NamespacedName{Namespace: cr.Namespace, Name: cr.RelabelingAssetName()}, &existCM); err != nil {
if errors.IsNotFound(err) {
return rclient.Create(ctx, assestsCM)
}
}
assestsCM.Annotations = labels.Merge(existCM.Annotations, assestsCM.Annotations)
victoriametricsv1beta1.MergeFinalizers(assestsCM, victoriametricsv1beta1.FinalizerName)
return rclient.Update(ctx, assestsCM)
}
// buildVMAgentStreamAggrConfig combines all possible stream aggregation configs and adding it to the configmap.
func buildVMAgentStreamAggrConfig(cr *victoriametricsv1beta1.VMAgent) (*corev1.ConfigMap, error) {
cfgCM := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: cr.Namespace,
Name: cr.StreamAggrConfigName(),
Labels: cr.AllLabels(),
Annotations: cr.AnnotationsFiltered(),
OwnerReferences: cr.AsOwner(),
},
Data: make(map[string]string),
}
for i, rw := range cr.Spec.RemoteWrite {
if !rw.HasStreamAggr() {
continue
}
data, err := yaml.Marshal(rw.StreamAggrConfig.Rules)
if err != nil {
return nil, fmt.Errorf("cannot serialize StreamAggrConfig rules as yaml for remoteWrite with url %s: %w", rw.URL, err)
}
if len(data) > 0 {
cfgCM.Data[rw.AsConfigMapKey(i, "stream-aggr-conf")] = string(data)
}
}
return cfgCM, nil
}
// CreateOrUpdateVMAgentStreamAggrConfig builds stream aggregation configs for vmagent at separate configmap, serialized as yaml
func CreateOrUpdateVMAgentStreamAggrConfig(ctx context.Context, cr *victoriametricsv1beta1.VMAgent, rclient client.Client) error {
// fast path
if !cr.HasAnyStreamAggrConfigs() {
return nil
}
streamAggrCM, err := buildVMAgentStreamAggrConfig(cr)
if err != nil {
return err
}
var existCM corev1.ConfigMap
if err := rclient.Get(ctx, types.NamespacedName{Namespace: cr.Namespace, Name: cr.StreamAggrConfigName()}, &existCM); err != nil {
if errors.IsNotFound(err) {
return rclient.Create(ctx, streamAggrCM)
}
}
streamAggrCM.Annotations = labels.Merge(existCM.Annotations, streamAggrCM.Annotations)
victoriametricsv1beta1.MergeFinalizers(streamAggrCM, victoriametricsv1beta1.FinalizerName)
return rclient.Update(ctx, streamAggrCM)
}
func fetchConfigMapContentByKey(ctx context.Context, rclient client.Client, cm *corev1.ConfigMap, key string) (string, error) {
if err := rclient.Get(ctx, types.NamespacedName{Namespace: cm.Namespace, Name: cm.Name}, cm); err != nil {
return "", err
}
return cm.Data[key], nil
}
func createOrUpdateTLSAssets(ctx context.Context, cr *victoriametricsv1beta1.VMAgent, rclient client.Client, assets map[string]string) error {
tlsAssetsSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: cr.TLSAssetName(),
Labels: cr.AllLabels(),
Annotations: cr.AnnotationsFiltered(),
OwnerReferences: cr.AsOwner(),
Namespace: cr.Namespace,
Finalizers: []string{victoriametricsv1beta1.FinalizerName},
},
Data: map[string][]byte{},
}
for key, asset := range assets {
tlsAssetsSecret.Data[key] = []byte(asset)
}
currentAssetSecret := &corev1.Secret{}
if err := rclient.Get(ctx, types.NamespacedName{Namespace: cr.Namespace, Name: tlsAssetsSecret.Name}, currentAssetSecret); err != nil {
if errors.IsNotFound(err) {
logger.WithContext(ctx).Info("creating new tls asset for vmagent", "secret_name", tlsAssetsSecret.Name, "vmagent", cr.Name)
return rclient.Create(ctx, tlsAssetsSecret)
}
return fmt.Errorf("cannot get existing tls secret: %s, for vmagent: %s, err: %w", tlsAssetsSecret.Name, cr.Name, err)
}
tlsAssetsSecret.Annotations = labels.Merge(currentAssetSecret.Annotations, tlsAssetsSecret.Annotations)
victoriametricsv1beta1.MergeFinalizers(tlsAssetsSecret, victoriametricsv1beta1.FinalizerName)
return rclient.Update(ctx, tlsAssetsSecret)
}
func loadTLSAssets(
ctx context.Context,
rclient client.Client,
cr *victoriametricsv1beta1.VMAgent,
scrapes map[string]*victoriametricsv1beta1.VMServiceScrape,
podScrapes map[string]*victoriametricsv1beta1.VMPodScrape,
probes map[string]*victoriametricsv1beta1.VMProbe,
nodes map[string]*victoriametricsv1beta1.VMNodeScrape,
statics map[string]*victoriametricsv1beta1.VMStaticScrape,
) (map[string]string, error) {
assets := map[string]string{}
nsSecretCache := make(map[string]*corev1.Secret)
nsConfigMapCache := make(map[string]*corev1.ConfigMap)
for _, rw := range cr.Spec.RemoteWrite {
if rw.TLSConfig == nil {
continue
}
if err := addAssetsToCache(ctx, rclient, cr.Namespace, rw.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
return nil, fmt.Errorf("cannot add asset for remote write target: %s,err: %w", cr.Name, err)
}
}
if cr.Spec.APIServerConfig != nil && cr.Spec.APIServerConfig.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, cr.Namespace, cr.Spec.APIServerConfig.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
return nil, fmt.Errorf("cannot add asset for remote write target: %s,err: %w", cr.Name, err)
}
}
var errG utils.ErrGroup
for key, pod := range podScrapes {
var epCnt int
for _, ep := range pod.Spec.PodMetricsEndpoints {
if ep.VMScrapeParams != nil && ep.VMScrapeParams.ProxyClientConfig != nil && ep.VMScrapeParams.ProxyClientConfig.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, pod.Namespace, ep.VMScrapeParams.ProxyClientConfig.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
errG.Add(fmt.Errorf("cannot add proxy tlsAsset for VMPodScrape: %w", err))
continue
}
}
if ep.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, pod.Namespace, ep.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
errG.Add(fmt.Errorf("cannot add tlsAsset for VMPodScrape: %w", err))
continue
}
}
pod.Spec.PodMetricsEndpoints[epCnt] = ep
epCnt++
}
pod.Spec.PodMetricsEndpoints = pod.Spec.PodMetricsEndpoints[:epCnt]
if len(pod.Spec.PodMetricsEndpoints) == 0 {
delete(podScrapes, key)
}
}
for key, mon := range scrapes {
var epCnt int
for _, ep := range mon.Spec.Endpoints {
if ep.VMScrapeParams != nil && ep.VMScrapeParams.ProxyClientConfig != nil && ep.VMScrapeParams.ProxyClientConfig.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, mon.Namespace, ep.VMScrapeParams.ProxyClientConfig.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
errG.Add(err)
continue
}
}
if ep.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, mon.Namespace, ep.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
errG.Add(err)
continue
}
}
mon.Spec.Endpoints[epCnt] = ep
epCnt++
}
mon.Spec.Endpoints = mon.Spec.Endpoints[:epCnt]
if len(mon.Spec.Endpoints) == 0 {
delete(scrapes, key)
}
}
for key, probe := range probes {
onErr := func(err error) {
errG.Add(err)
delete(probes, key)
}
if probe.Spec.VMScrapeParams != nil && probe.Spec.VMScrapeParams.ProxyClientConfig != nil && probe.Spec.VMScrapeParams.ProxyClientConfig.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, probe.Namespace, probe.Spec.VMScrapeParams.ProxyClientConfig.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
onErr(err)
continue
}
}
if probe.Spec.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, probe.Namespace, probe.Spec.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
onErr(err)
continue
}
}
}
for key, staticCfg := range statics {
var epCnt int
for _, ep := range staticCfg.Spec.TargetEndpoints {
if ep.VMScrapeParams != nil && ep.VMScrapeParams.ProxyClientConfig != nil && ep.VMScrapeParams.ProxyClientConfig.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, staticCfg.Namespace, ep.VMScrapeParams.ProxyClientConfig.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
errG.Add(err)
continue
}
}
if ep.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, staticCfg.Namespace, ep.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
errG.Add(err)
continue
}
}
staticCfg.Spec.TargetEndpoints[epCnt] = ep
epCnt++
}
staticCfg.Spec.TargetEndpoints = staticCfg.Spec.TargetEndpoints[:epCnt]
if len(staticCfg.Spec.TargetEndpoints) == 0 {
delete(statics, key)
}
}
for key, node := range nodes {
onErr := func(err error) {
errG.Add(err)
delete(nodes, key)
}
if node.Spec.VMScrapeParams != nil && node.Spec.VMScrapeParams.ProxyClientConfig != nil && node.Spec.VMScrapeParams.ProxyClientConfig.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, node.Namespace, node.Spec.VMScrapeParams.ProxyClientConfig.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
onErr(err)
continue
}
}
if node.Spec.TLSConfig != nil {
if err := addAssetsToCache(ctx, rclient, node.Namespace, node.Spec.TLSConfig, assets, nsSecretCache, nsConfigMapCache); err != nil {
onErr(err)
continue
}
}
}
return assets, errG.Err()
}
func addAssetsToCache(
ctx context.Context,
rclient client.Client,
objectNS string,
tlsConfig *victoriametricsv1beta1.TLSConfig,
assets map[string]string,
nsSecretCache map[string]*corev1.Secret,
nsConfigMapCache map[string]*corev1.ConfigMap,
) error {
prefix := objectNS + "/"
secretSelectors := map[string]*corev1.SecretKeySelector{}
configMapSelectors := map[string]*corev1.ConfigMapKeySelector{}
if tlsConfig.CA != (victoriametricsv1beta1.SecretOrConfigMap{}) {
selectorKey := tlsConfig.CA.BuildSelectorWithPrefix(prefix)
switch {
case tlsConfig.CA.Secret != nil:
secretSelectors[selectorKey] = tlsConfig.CA.Secret
case tlsConfig.CA.ConfigMap != nil:
configMapSelectors[selectorKey] = tlsConfig.CA.ConfigMap
}
}
if tlsConfig.Cert != (victoriametricsv1beta1.SecretOrConfigMap{}) {
selectorKey := tlsConfig.Cert.BuildSelectorWithPrefix(prefix)
switch {
case tlsConfig.Cert.Secret != nil:
secretSelectors[selectorKey] = tlsConfig.Cert.Secret
case tlsConfig.Cert.ConfigMap != nil:
configMapSelectors[selectorKey] = tlsConfig.Cert.ConfigMap
}
}
if tlsConfig.KeySecret != nil {
secretSelectors[prefix+tlsConfig.KeySecret.Name+"/"+tlsConfig.KeySecret.Key] = tlsConfig.KeySecret
}
for key, selector := range secretSelectors {
asset, err := k8stools.GetCredFromSecret(
ctx,
rclient,
objectNS,
selector,
key,
nsSecretCache,
)
if err != nil {
return fmt.Errorf(
"failed to extract endpoint tls asset from secret %s and key %s in namespace %s",
selector.Name, selector.Key, objectNS,
)
}
assets[tlsConfig.BuildAssetPath(objectNS, selector.Name, selector.Key)] = asset
}
for key, selector := range configMapSelectors {
asset, err := k8stools.GetCredFromConfigMap(
ctx,
rclient,
objectNS,
*selector,
key,
nsConfigMapCache,
)
if err != nil {