-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathconfig.go
1399 lines (1266 loc) · 44.2 KB
/
config.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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package confgenerator
import (
"context"
"fmt"
"log"
"path/filepath"
"reflect"
"runtime"
"sort"
"strings"
"time"
"github.com/GoogleCloudPlatform/ops-agent/confgenerator/filter"
"github.com/GoogleCloudPlatform/ops-agent/confgenerator/fluentbit"
"github.com/GoogleCloudPlatform/ops-agent/confgenerator/otel"
"github.com/GoogleCloudPlatform/ops-agent/internal/platform"
"github.com/GoogleCloudPlatform/ops-agent/internal/secret"
"github.com/GoogleCloudPlatform/ops-agent/internal/set"
"github.com/go-playground/validator/v10"
yaml "github.com/goccy/go-yaml"
"github.com/kardianos/osext"
promconfig "github.com/prometheus/prometheus/config"
"go.uber.org/multierr"
"golang.org/x/exp/constraints"
)
// Ops Agent config.
type UnifiedConfig struct {
Combined *Combined `yaml:"combined,omitempty"`
Logging *Logging `yaml:"logging"`
Metrics *Metrics `yaml:"metrics"`
// FIXME: OTel uses metrics/logs/traces but we appear to be using metrics/logging/traces
Traces *Traces `yaml:"traces,omitempty"`
Global *Global `yaml:"global,omitempty"`
}
func (uc *UnifiedConfig) HasLogging() bool {
return uc.Logging != nil
}
func (uc *UnifiedConfig) HasMetrics() bool {
return uc.Metrics != nil
}
func (uc *UnifiedConfig) HasCombined() bool {
return uc.Combined != nil
}
func (uc *UnifiedConfig) DeepCopy(ctx context.Context) (*UnifiedConfig, error) {
toYaml, err := yaml.Marshal(uc)
if err != nil {
return nil, fmt.Errorf("failed to convert UnifiedConfig to yaml: %w.", err)
}
fromYaml, err := UnmarshalYamlToUnifiedConfig(ctx, toYaml)
if err != nil {
return nil, fmt.Errorf("failed to convert yaml to UnifiedConfig: %w.", err)
}
return fromYaml, nil
}
func (uc *UnifiedConfig) String() string {
marshalledConfig, err := yaml.Marshal(uc)
if err != nil {
return fmt.Sprintf("failed to convert Unified config to yaml: %v", err)
}
return string(marshalledConfig)
}
type Combined struct {
Receivers combinedReceiverMap `yaml:"receivers,omitempty" validate:"dive,keys,startsnotwith=lib:"`
}
type validatorContext struct {
ctx context.Context
v *validator.Validate
}
type validationErrors []validationError
func (ve validationErrors) Error() string {
var out []string
for _, err := range ve {
out = append(out, err.Error())
}
sort.Strings(out)
return strings.Join(out, ",")
}
type validationError struct {
validator.FieldError
}
func (ve validationError) StructField() string {
// TODO: Fix yaml library so that this is unnecessary.
// Remove subscript on field name so go-yaml can associate this with a line number.
parts := strings.Split(ve.FieldError.StructField(), "[")
return parts[0]
}
func (ve validationError) Error() string {
switch ve.Tag() {
case "duration":
return fmt.Sprintf("%q must be a duration of at least %s", ve.Field(), ve.Param())
case "endswith":
return fmt.Sprintf("%q must end with %q", ve.Field(), ve.Param())
case "experimental":
return experimentalValidationErrorString(ve)
case "ip":
return fmt.Sprintf("%q must be an IP address", ve.Field())
case "min":
return fmt.Sprintf("%q must be a minimum of %s", ve.Field(), ve.Param())
case "multipleof_time":
return fmt.Sprintf("%q must be a multiple of %s", ve.Field(), ve.Param())
case "oneof":
return fmt.Sprintf("%q must be one of [%s]", ve.Field(), ve.Param())
case "required":
return fmt.Sprintf("%q is a required field", ve.Field())
case "required_with":
return fmt.Sprintf("%q is required when %q is set", ve.Field(), ve.Param())
case "startsnotwith":
return fmt.Sprintf("%q must not start with %q", ve.Field(), ve.Param())
case "startswith":
return fmt.Sprintf("%q must start with %q", ve.Field(), ve.Param())
case "url":
return fmt.Sprintf("%q must be a URL", ve.Field())
case "excluded_with":
return fmt.Sprintf("%q cannot be set if one of [%s] is set", ve.Field(), ve.Param())
case "filter":
_, err := filter.NewFilter(ve.Value().(string))
return fmt.Sprintf("%q: %v", ve.Field(), err)
case "field":
_, err := filter.NewMember(ve.Value().(string))
return fmt.Sprintf("%q: %v", ve.Field(), err)
case "fieldlegacy":
_, err := filter.NewMemberLegacy(ve.Value().(string))
return fmt.Sprintf("%q: %v", ve.Field(), err)
case "distinctfield":
return fmt.Sprintf("%q specified multiple times", ve.Value().(string))
case "writablefield":
return fmt.Sprintf("%q is not a writable field", ve.Value().(string))
case "winlogchannels":
// Assume validation has already failed by this point, that is, receiver_version must already be > 1
channels := ve.Value().([]string)
return validateWinlogChannels(channels).Error()
}
return ve.FieldError.Error()
}
func (v *validatorContext) Struct(s interface{}) error {
err := v.v.StructCtx(v.ctx, s)
errors, ok := err.(validator.ValidationErrors)
if !ok {
// Including nil
return err
}
var out validationErrors
for _, err := range errors {
out = append(out, validationError{err})
}
return out
}
func newValidator() *validator.Validate {
v := validator.New()
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("yaml"), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
// duration validates that the value is a valid duration and >= the parameter
v.RegisterValidation("duration", func(fl validator.FieldLevel) bool {
fieldStr := fl.Field().String()
if fieldStr == "" {
// Ignore the case where this field is not actually specified or is left empty.
return true
}
t, err := time.ParseDuration(fl.Field().String())
if err != nil {
return false
}
tmin, err := time.ParseDuration(fl.Param())
if err != nil {
panic(err)
}
return t >= tmin
})
v.RegisterStructValidation(validatePrometheusConfig, &promconfig.Config{})
// filter validates that a Cloud Logging filter condition is valid
v.RegisterValidation("filter", func(fl validator.FieldLevel) bool {
_, err := filter.NewFilter(fl.Field().String())
return err == nil
})
// field validates that a Cloud Logging field expression is valid
v.RegisterValidation("field", func(fl validator.FieldLevel) bool {
_, err := filter.NewMember(fl.Field().String())
// TODO: Disallow specific target fields?
return err == nil
})
v.RegisterValidation("fieldlegacy", func(fl validator.FieldLevel) bool {
_, err := filter.NewMemberLegacy(fl.Field().String())
// TODO: Disallow specific target fields?
return err == nil
})
// distinctfield validates that a key in a map refers to different fields from the other keys in the map.
// Use this as keys,distinctfield,endkeys
v.RegisterValidation("distinctfield", func(fl validator.FieldLevel) bool {
// Get the map that contains this key.
parent, parentkind, found := fl.GetStructFieldOKAdvanced(fl.Parent(), fl.StructFieldName()[:strings.Index(fl.StructFieldName(), "[")])
if !found {
return false
}
if parentkind != reflect.Map {
fmt.Printf("not map\n")
return false
}
k1 := fl.Field().String()
field, err := filter.NewMember(k1)
if err != nil {
fmt.Printf("newmember %q: %v", fl.Field().String(), err)
return false
}
for _, key := range parent.MapKeys() {
k2 := key.String()
if k1 == k2 {
// Skip itself
continue
}
field2, err := filter.NewMember(k2)
if err != nil {
continue
}
if field2.Equals(*field) {
return false
}
}
return true
})
// writablefield checks to make sure the field is writable
v.RegisterValidation("writablefield", func(fl validator.FieldLevel) bool {
m1, err := filter.NewMember(fl.Field().String())
if err != nil {
// The "field" validator will handle this better.
return true
}
// Currently, instrumentation_source is the only field that is not writable.
m2, err := filter.NewMember(InstrumentationSourceLabel)
if err != nil {
panic(err)
}
return !m2.Equals(*m1)
})
// multipleof_time validates that the value duration is a multiple of the parameter
v.RegisterValidation("multipleof_time", func(fl validator.FieldLevel) bool {
t, ok := fl.Field().Interface().(time.Duration)
if !ok {
panic(fmt.Sprintf("multipleof_time: could not convert %s to time duration", fl.Field().String()))
}
tfactor, err := time.ParseDuration(fl.Param())
if err != nil {
panic(fmt.Sprintf("multipleof_time: could not convert %s to time duration", fl.Param()))
}
return t%tfactor == 0
})
// winlogchannels wraps validateWinlogChannels when receiver_version > 1 and validateWinlogV1Channels when receiver_version = 1
// TODO: relax the "receiver_version > 1" constraint and replace validateWinlogChannels with built-in validator primitives
v.RegisterValidationCtx("winlogchannels", func(ctx context.Context, fl validator.FieldLevel) bool {
receiver, ok := fl.Parent().Interface().(LoggingReceiverWindowsEventLog)
if !ok {
panic(fmt.Sprintf("winlogchannels: could not convert %s's parent to LoggingReceiverWindowsEventLog", fl.Field().String()))
}
if receiver.IsDefaultVersion() {
if err := validateWinlogV1Channels(ctx, receiver.Channels); err != nil {
// Only emit a soft failure (warning) here, because:
// 1) we want this to be backwards compatible, and
// 2) the implementation of the validation is not officially documented to be the "correct" way to do it
log.Print(err)
}
return true
}
return validateWinlogChannels(receiver.Channels) == nil
})
// Validates that experimental config components are enabled via EXPERIMENTAL_FEATURES
registerExperimentalValidations(v)
return v
}
// validateWinlogChannels validates a handful of things at once:
// - that at least one channel is defined
// - that channels do not contain commas
// - that channels are unique (case-insensitive)
func validateWinlogChannels(channels []string) error {
if len(channels) == 0 {
return fmt.Errorf(`"channels" must contain at least one channel when "receiver_version" is 2 or higher`)
}
for i, channel := range channels {
if strings.ContainsRune(channel, ',') {
return fmt.Errorf(`"channels[%d]" (%s) contains an invalid character: ,`, i, channel)
}
}
duplicate := getFirstNonUniqueString(channels)
if duplicate != "" {
return fmt.Errorf(`"channels" contains the same value more than once: %s`, duplicate)
}
return nil
}
// validateWinlogV1Channels checks whether any channels defined by a v1 winlog receiver
// actually exist as "old API" channels, because if they don't, then a v2 winlog receiver
// would be needed instead.
// Caveat: there is little official documentation to support that this is a guaranteed
// method of determining whether a channel is accessible via the "old API".
func validateWinlogV1Channels(ctx context.Context, channels []string) error {
oldChannels := platform.FromContext(ctx).WinlogV1Channels
var err error
for i, channel := range channels {
if !stringContainedInSliceCaseInsensitive(channel, oldChannels) {
err = multierr.Append(err, fmt.Errorf(
`"channels[%d]" contains a channel, "%s", which may not work properly on version 1 of windows_event_log. Please use "receiver_version: 2" or higher for this receiver`,
i, channel,
))
}
}
return err
}
// getFirstNonUniqueString returns the first non-unique (duplicate) string
// from the given slice. Equality is determined by direct comparison after strings.ToLower().
// If no non-unique strings are found, or if the given slice is empty, then
// an empty string is returned.
func getFirstNonUniqueString(slice []string) string {
seen := map[string]bool{}
for _, value := range slice {
lower := strings.ToLower(value)
if seen[lower] {
return value
}
seen[lower] = true
}
return ""
}
func UnmarshalYamlToUnifiedConfig(ctx context.Context, input []byte) (*UnifiedConfig, error) {
config := UnifiedConfig{}
v := &validatorContext{
ctx: ctx,
v: newValidator(),
}
if err := yaml.UnmarshalContext(ctx, input, &config, yaml.Strict(), yaml.Validator(v)); err != nil {
return nil, err
}
return &config, nil
}
type Component interface {
// Type returns the component type string as used in the configuration file (e.g. "hostmetrics")
Type() string
}
// ConfigComponent holds the shared configuration fields that all components have.
// It is also used by itself when unmarshaling a component's configuration.
type ConfigComponent struct {
Type string `yaml:"type" validate:"required" tracking:""`
}
type componentInterface interface {
Component
}
// componentFactory is the value type for the componentTypeRegistry map.
type componentFactory[CI componentInterface] struct {
// constructor creates a concrete instance for this component. For example, the "files" constructor would return a *LoggingReceiverFiles, which has an IncludePaths field.
constructor func() CI
// platforms is a bitmask of platforms on which the component is valid
platforms platform.Type
}
func (ct componentFactory[CI]) supportsPlatform(ctx context.Context) bool {
platformType := platform.FromContext(ctx).Type
return ct.platforms&platformType == platformType
}
type componentTypeRegistry[CI componentInterface, M ~map[string]CI] struct {
// Subagent is "logging" or "metric" (only used for error messages)
Subagent string
// Kind is "receiver" or "processor" (only used for error messages)
Kind string
// TypeMap contains a map of component "type" string as used in the configuration file to information about that component.
TypeMap map[string]*componentFactory[CI]
}
func (r *componentTypeRegistry[CI, M]) RegisterType(constructor func() CI, platforms ...platform.Type) {
name := constructor().Type()
if _, ok := r.TypeMap[name]; ok {
panic(fmt.Sprintf("attempt to register duplicate %s %s type: %q", r.Subagent, r.Kind, name))
}
if r.TypeMap == nil {
r.TypeMap = make(map[string]*componentFactory[CI])
}
var platformsValue platform.Type
for _, p := range platforms {
platformsValue = platformsValue | p
}
if platformsValue == 0 {
platformsValue = platform.All
}
r.TypeMap[name] = &componentFactory[CI]{constructor, platformsValue}
}
// UnmarshalComponentYaml is the custom unmarshaller for reading a component's configuration from the config file.
// It first unmarshals into a struct containing only the "type" field, then looks up the config struct with the full set of fields for that type, and finally unmarshals into an instance of that struct.
func (r *componentTypeRegistry[CI, M]) UnmarshalComponentYaml(ctx context.Context, inner *CI, unmarshal func(interface{}) error) error {
c := ConfigComponent{}
unmarshal(&c) // Get the type; ignore the error
var o interface{}
if ct := r.TypeMap[c.Type]; ct != nil && ct.supportsPlatform(ctx) {
o = ct.constructor()
}
if o == nil {
var supportedTypes []string
for k, ct := range r.TypeMap {
if ct.supportsPlatform(ctx) {
supportedTypes = append(supportedTypes, k)
}
}
sort.Strings(supportedTypes)
return fmt.Errorf(`%s %s with type %q is not supported. Supported %s %s types: [%s].`,
r.Subagent, r.Kind, c.Type,
r.Subagent, r.Kind, strings.Join(supportedTypes, ", "))
}
*inner = o.(CI)
return unmarshal(*inner)
}
// GetComponentsFromRegistry returns all components that belong to the associated registry
func (r *componentTypeRegistry[CI, M]) GetComponentsFromRegistry() []Component {
components := make([]Component, len(r.TypeMap))
i := 0
for _, comp := range r.TypeMap {
components[i] = comp.constructor()
i++
}
return components
}
// unmarshalValue is a bogus unmarshalling destination that just captures the unmarshal() function pointer for later reuse.
type unmarshalValue struct {
unmarshal func(interface{}) error
}
func (v *unmarshalValue) UnmarshalYAML(ctx context.Context, unmarshal func(interface{}) error) error {
v.unmarshal = unmarshal
return nil
}
type unmarshalMap map[string]unmarshalValue
// unmarshalToMap unmarshals a YAML structure to a config map.
// It should be called from UnmarshalYAML() on a concrete type.
// N.B. The map type itself can't be generic because it needs to point to a specific type registry, not just a type registry type (whew).
func (r *componentTypeRegistry[CI, M]) unmarshalToMap(ctx context.Context, m *M, unmarshal func(interface{}) error) error {
if *m == nil {
*m = make(M)
}
// Step 1: Capture unmarshal functions for each component
um := unmarshalMap{}
if err := unmarshal(&um); err != nil {
return err
}
// Step 2: Unmarshal into the destination map
for k, u := range um {
var inner CI
if err := r.UnmarshalComponentYaml(ctx, &inner, u.unmarshal); err != nil {
return err
}
(*m)[k] = inner
}
return nil
}
// Ops Agent logging config.
type loggingReceiverMap map[string]LoggingReceiver
type loggingProcessorMap map[string]LoggingProcessor
type Logging struct {
Receivers loggingReceiverMap `yaml:"receivers,omitempty" validate:"dive,keys,startsnotwith=lib:"`
Processors loggingProcessorMap `yaml:"processors,omitempty" validate:"dive,keys,startsnotwith=lib:"`
// Exporters are deprecated and ignored, so do not have any validation.
Exporters map[string]interface{} `yaml:"exporters,omitempty"`
Service *LoggingService `yaml:"service"`
}
type LoggingReceiver interface {
Component
Components(ctx context.Context, tag string) []fluentbit.Component
}
var LoggingReceiverTypes = &componentTypeRegistry[LoggingReceiver, loggingReceiverMap]{
Subagent: "logging", Kind: "receiver",
}
func (m *loggingReceiverMap) UnmarshalYAML(ctx context.Context, unmarshal func(interface{}) error) error {
return LoggingReceiverTypes.unmarshalToMap(ctx, m, unmarshal)
}
// Logging receivers that listen on a port of the host
type LoggingNetworkReceiver interface {
LoggingReceiver
GetListenPort() uint16
}
// GetListenPorts returns a map of receiver IDs to ports for all LoggingNetworkReceivers
func (m *loggingReceiverMap) GetListenPorts() map[string]uint16 {
receiverPortMap := map[string]uint16{}
for rID, receiver := range *m {
if nr, ok := receiver.(LoggingNetworkReceiver); ok {
receiverPortMap[rID] = nr.GetListenPort()
}
}
return receiverPortMap
}
type LoggingProcessor interface {
Component
// Components returns fluentbit components that implement this processor.
// tag is the log tag that should be matched by those components, and uid is a string which should be used when needed to generate unique names.
Components(ctx context.Context, tag string, uid string) []fluentbit.Component
}
var LoggingProcessorTypes = &componentTypeRegistry[LoggingProcessor, loggingProcessorMap]{
Subagent: "logging", Kind: "processor",
}
func (m *loggingProcessorMap) UnmarshalYAML(ctx context.Context, unmarshal func(interface{}) error) error {
return LoggingProcessorTypes.unmarshalToMap(ctx, m, unmarshal)
}
type LoggingService struct {
Compress string `yaml:"compress,omitempty" validate:"omitempty,oneof=gzip,experimental=log_compression"`
LogLevel string `yaml:"log_level,omitempty" validate:"omitempty,oneof=error warn info debug trace"`
Pipelines map[string]*Pipeline `validate:"dive,keys,startsnotwith=lib:"`
OTelLogging bool `yaml:"experimental_otel_logging,omitempty" validate:"omitempty,experimental=otel_logging"`
}
type Pipeline struct {
ReceiverIDs []string `yaml:"receivers,omitempty,flow"`
ProcessorIDs []string `yaml:"processors,omitempty,flow"`
// ExporterIDs is deprecated and ignored.
ExporterIDs []string `yaml:"exporters,omitempty,flow"`
}
// Ops Agent metrics config.
type metricsReceiverMap map[string]MetricsReceiver
type metricsProcessorMap map[string]MetricsProcessor
type Metrics struct {
Receivers metricsReceiverMap `yaml:"receivers" validate:"dive,keys,startsnotwith=lib:"`
Processors metricsProcessorMap `yaml:"processors" validate:"dive,keys,startsnotwith=lib:"`
// Exporters are deprecated and ignored, so do not have any validation.
Exporters map[string]interface{} `yaml:"exporters,omitempty"`
Service *MetricsService `yaml:"service"`
}
type OTelReceiver interface {
Component
Pipelines(ctx context.Context) ([]otel.ReceiverPipeline, error)
}
type MetricsProcessorMerger interface {
// MergeMetricsProcessor attempts to merge p into the current receiver.
// It returns the new receiver; and true if the processor has been merged
// into the receiver completely
MergeMetricsProcessor(p MetricsProcessor) (MetricsReceiver, bool)
}
type MetricsReceiver interface {
OTelReceiver
}
type TracesReceiver interface {
// TODO: Distinguish from metrics somehow?
OTelReceiver
}
type MetricsReceiverShared struct {
CollectionInterval string `yaml:"collection_interval" validate:"duration=10s"` // time.Duration format
}
func (m MetricsReceiverShared) CollectionIntervalString() string {
// TODO: Remove when https://github.com/goccy/go-yaml/pull/246 is merged
if m.CollectionInterval != "" {
return m.CollectionInterval
}
return "60s"
}
type MetricsReceiverSharedTLS struct {
Insecure *bool `yaml:"insecure" validate:"omitempty"`
InsecureSkipVerify *bool `yaml:"insecure_skip_verify" validate:"omitempty"`
CertFile string `yaml:"cert_file" validate:"required_with=KeyFile"`
KeyFile string `yaml:"key_file" validate:"required_with=CertFile"`
CAFile string `yaml:"ca_file" validate:"omitempty"`
}
func (m MetricsReceiverSharedTLS) TLSConfig(defaultInsecure bool) map[string]interface{} {
if m.Insecure == nil {
m.Insecure = &defaultInsecure
}
tls := map[string]interface{}{
"insecure": *m.Insecure,
}
if m.InsecureSkipVerify != nil {
tls["insecure_skip_verify"] = *m.InsecureSkipVerify
}
if m.CertFile != "" {
tls["cert_file"] = m.CertFile
}
if m.CAFile != "" {
tls["ca_file"] = m.CAFile
}
if m.KeyFile != "" {
tls["key_file"] = m.KeyFile
}
return tls
}
type MetricsReceiverSharedJVM struct {
MetricsReceiverShared `yaml:",inline"`
Endpoint string `yaml:"endpoint" validate:"omitempty,hostname_port|startswith=service:jmx:"`
Username string `yaml:"username" validate:"required_with=Password"`
Password secret.String `yaml:"password" validate:"required_with=Username"`
AdditionalJars []string `yaml:"additional_jars" validate:"omitempty,dive,file"`
}
// WithDefaultEndpoint overrides the MetricReceiverSharedJVM's Endpoint if it is empty.
// It then returns a new MetricReceiverSharedJVM with this change.
func (m MetricsReceiverSharedJVM) WithDefaultEndpoint(defaultEndpoint string) MetricsReceiverSharedJVM {
if m.Endpoint == "" {
m.Endpoint = defaultEndpoint
}
return m
}
// WithDefaultAdditionalJars overrides the MetricReceiverSharedJVM's AdditionalJars if it is empty.
// It then returns a new MetricReceiverSharedJVM with this change.
func (m MetricsReceiverSharedJVM) WithDefaultAdditionalJars(defaultAdditionalJars ...string) MetricsReceiverSharedJVM {
if len(m.AdditionalJars) == 0 {
m.AdditionalJars = defaultAdditionalJars
}
return m
}
// ConfigurePipelines sets up a Receiver using the MetricsReceiverSharedJVM and the targetSystem.
// This is used alongside the passed in processors to return a single Pipeline in an array.
func (m MetricsReceiverSharedJVM) ConfigurePipelines(targetSystem string, processors []otel.Component) ([]otel.ReceiverPipeline, error) {
jarPath, err := FindJarPath()
if err != nil {
return nil, fmt.Errorf("failed to discover the location of the JMX metrics exporter: %w", err)
}
config := map[string]interface{}{
"target_system": targetSystem,
"collection_interval": m.CollectionIntervalString(),
"endpoint": m.Endpoint,
"jar_path": jarPath,
}
if len(m.AdditionalJars) > 0 {
config["additional_jars"] = m.AdditionalJars
}
// Only set the username & password fields if provided
if m.Username != "" {
config["username"] = m.Username
}
secretPassword := m.Password.SecretValue()
if secretPassword != "" {
config["password"] = secretPassword
}
return []otel.ReceiverPipeline{{
Receiver: otel.Component{
Type: "jmx",
Config: config,
},
Processors: map[string][]otel.Component{"metrics": processors},
}}, nil
}
type MetricsReceiverSharedCollectJVM struct {
CollectJVMMetrics *bool `yaml:"collect_jvm_metrics"`
}
func (m MetricsReceiverSharedCollectJVM) TargetSystemString(targetSystem string) string {
if m.ShouldCollectJVMMetrics() {
targetSystem = fmt.Sprintf("%s,%s", targetSystem, "jvm")
}
return targetSystem
}
func (m MetricsReceiverSharedCollectJVM) ShouldCollectJVMMetrics() bool {
return m.CollectJVMMetrics == nil || *m.CollectJVMMetrics
}
var FindJarPath = func() (string, error) {
jarName := "opentelemetry-java-contrib-jmx-metrics.jar"
executableDir, err := osext.ExecutableFolder()
if err != nil {
return jarName, fmt.Errorf("could not determine binary path for jvm receiver: %w", err)
}
// TODO(djaglowski) differentiate behavior via build tags
if runtime.GOOS != "windows" {
return filepath.Join(executableDir, "../subagents/opentelemetry-collector/", jarName), nil
}
return filepath.Join(executableDir, jarName), nil
}
type MetricsReceiverSharedCluster struct {
CollectClusterMetrics *bool `yaml:"collect_cluster_metrics" validate:"omitempty"`
}
func (m MetricsReceiverSharedCluster) ShouldCollectClusterMetrics() bool {
return m.CollectClusterMetrics == nil || *m.CollectClusterMetrics
}
var MetricsReceiverTypes = &componentTypeRegistry[MetricsReceiver, metricsReceiverMap]{
Subagent: "metrics", Kind: "receiver",
}
func (m *metricsReceiverMap) UnmarshalYAML(ctx context.Context, unmarshal func(interface{}) error) error {
return MetricsReceiverTypes.unmarshalToMap(ctx, m, unmarshal)
}
type CombinedReceiver interface {
// TODO: Add more types of signals
MetricsReceiver
}
var CombinedReceiverTypes = &componentTypeRegistry[CombinedReceiver, combinedReceiverMap]{
Subagent: "generic", Kind: "receiver",
}
type combinedReceiverMap map[string]CombinedReceiver
func (m *combinedReceiverMap) UnmarshalYAML(ctx context.Context, unmarshal func(interface{}) error) error {
return CombinedReceiverTypes.unmarshalToMap(ctx, m, unmarshal)
}
type OTelProcessor interface {
Component
Processors(context.Context) ([]otel.Component, error)
}
type MetricsProcessor interface {
OTelProcessor
}
var MetricsProcessorTypes = &componentTypeRegistry[MetricsProcessor, metricsProcessorMap]{
Subagent: "metrics", Kind: "processor",
}
func (m *metricsProcessorMap) UnmarshalYAML(ctx context.Context, unmarshal func(interface{}) error) error {
return MetricsProcessorTypes.unmarshalToMap(ctx, m, unmarshal)
}
type MetricsService struct {
LogLevel string `yaml:"log_level,omitempty" validate:"omitempty,oneof=error warn info debug"`
Pipelines map[string]*Pipeline `yaml:"pipelines" validate:"dive,keys,startsnotwith=lib:"`
}
type Traces struct {
Service *TracesService `yaml:"service"`
}
type TracesService struct {
Pipelines map[string]*Pipeline
}
func (uc *UnifiedConfig) Validate(ctx context.Context) error {
if uc.Logging != nil {
if err := uc.ValidateLogging(); err != nil {
return err
}
}
if uc.Metrics != nil {
if err := uc.ValidateMetrics(ctx); err != nil {
return err
}
}
if uc.Traces != nil {
if err := uc.ValidateTraces(); err != nil {
return err
}
}
if uc.Combined != nil {
if err := uc.ValidateCombined(); err != nil {
return err
}
}
return nil
}
func (uc *UnifiedConfig) ValidateLogging() error {
l := uc.Logging
subagent := "logging"
if len(l.Exporters) > 0 {
log.Print(`The "logging.exporters" field is no longer needed and will be ignored. This does not change any functionality. Please remove it from your configuration.`)
}
if l.Service == nil {
return nil
}
validReceivers := map[string]bool{}
for k := range l.Receivers {
validReceivers[k] = true
}
if uc.Combined != nil {
for k := range uc.Combined.Receivers {
// TODO: What about combined receivers that don't support logging (none exist today)?
validReceivers[k] = true
}
}
validProcessors := map[string]LoggingProcessor{}
for k, v := range l.Processors {
validProcessors[k] = v
}
for _, k := range defaultProcessors {
validProcessors[k] = nil
}
portTaken := map[uint16]string{} // port -> receiverId map
for _, id := range sortedKeys(l.Service.Pipelines) {
p := l.Service.Pipelines[id]
if err := validateComponentKeys(validReceivers, p.ReceiverIDs, subagent, "receiver", id); err != nil {
return err
}
if err := validateComponentKeys(validProcessors, p.ProcessorIDs, subagent, "processor", id); err != nil {
return err
}
if _, err := validateComponentTypeCounts(l.Receivers, p.ReceiverIDs, subagent, "receiver"); err != nil {
return err
}
if _, err := validateComponentTypeCounts(l.Processors, p.ProcessorIDs, subagent, "processor"); err != nil {
return err
}
// portTaken will be modified/updated by the validation function
if _, err := validateReceiverPorts(portTaken, l.Receivers.GetListenPorts(), p.ReceiverIDs); err != nil {
return err
}
if err := validateWinlogRenderAsXML(l.Receivers, p.ReceiverIDs); err != nil {
return err
}
if len(p.ExporterIDs) > 0 {
log.Printf(`The "logging.service.pipelines.%s.exporters" field is deprecated and will be ignored. Please remove it from your configuration.`, id)
}
}
return nil
}
func (uc *UnifiedConfig) ValidateCombined() error {
m := uc.Metrics
t := uc.Traces
c := uc.Combined
if c == nil {
return nil
}
for k, _ := range c.Receivers {
for _, f := range []struct {
name string
missing bool
}{
{"metrics", m == nil},
{"traces", t == nil},
// TODO: Add "logging" here?
} {
if f.missing {
return fmt.Errorf("combined receiver %q found with no %s section; separate metrics and traces pipelines are required for this receiver, or an empty %s configuration if the data is being intentionally dropped", k, f.name, f.name)
}
}
}
return nil
}
func (uc *UnifiedConfig) MetricsReceivers() (map[string]MetricsReceiver, error) {
validReceivers := map[string]MetricsReceiver{}
if uc.Metrics != nil {
for k, v := range uc.Metrics.Receivers {
validReceivers[k] = v
}
}
if uc.Combined != nil {
for k, v := range uc.Combined.Receivers {
if uc.Metrics != nil {
if _, ok := uc.Metrics.Receivers[k]; ok {
return nil, fmt.Errorf("metrics receiver %q has the same name as combined receiver %q", k, k)
}
}
if v, ok := v.(MetricsReceiver); ok {
validReceivers[k] = v
}
}
}
return validReceivers, nil
}
func (uc *UnifiedConfig) TracesReceivers() (map[string]TracesReceiver, error) {
validReceivers := map[string]TracesReceiver{}
if uc.Combined != nil {
for k, v := range uc.Combined.Receivers {
if _, ok := v.(TracesReceiver); ok {
validReceivers[k] = v
}
}
}
return validReceivers, nil
}
type pipelineBackend int
const (
backendOTel pipelineBackend = iota
backendFluentBit
)
type pipelineInstance struct {
pID, rID string
pipelineType string
receiver Component
processors []struct {
id string
Component
}
backend pipelineBackend
}
func (pi *pipelineInstance) Types() (string, string) {
return pi.pipelineType, pi.receiver.Type()
}
func (uc *UnifiedConfig) metricsPipelines(ctx context.Context) ([]pipelineInstance, error) {
receivers, err := uc.MetricsReceivers()
if err != nil {
return nil, err
}
var out []pipelineInstance
if uc.Metrics != nil && uc.Metrics.Service != nil {
for pID, p := range uc.Metrics.Service.Pipelines {
for _, rID := range p.ReceiverIDs {
receiver, ok := receivers[rID]
if !ok {
return nil, fmt.Errorf("metrics receiver %q not found", rID)
}
var processors []struct {
id string
Component
}
canMerge := true
for _, prID := range p.ProcessorIDs {
processor, ok := uc.Metrics.Processors[prID]
if !ok {
return nil, fmt.Errorf("processor %q not found", prID)
}
if mr, ok := receiver.(MetricsProcessorMerger); ok && canMerge {
receiver, ok = mr.MergeMetricsProcessor(processor)
if ok {
// Only continue when the receiver can completely merge the processor;
// If the receiver is no longer a MetricsProcessorMerger, or it can't
// completely merge the current processor, break the loop
continue
}
}
canMerge = false
processors = append(processors, struct {
id string
Component
}{prID, processor})