-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathconfig.go
More file actions
1675 lines (1442 loc) · 49 KB
/
Copy pathconfig.go
File metadata and controls
1675 lines (1442 loc) · 49 KB
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 (c) F5, Inc.
//
// This source code is licensed under the Apache License, Version 2.0 license found in the
// LICENSE file in the root directory of this source tree.
package config
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/nginx/agent/v3/pkg/host"
"github.com/nginx/agent/v3/internal/datasource/file"
"github.com/nginx/agent/v3/internal/logger"
"github.com/goccy/go-yaml"
uuidLibrary "github.com/nginx/agent/v3/pkg/id"
selfsignedcerts "github.com/nginx/agent/v3/pkg/tls"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
)
const (
ConfigFileName = "nginx-agent.conf"
EnvPrefix = "NGINX_AGENT"
KeyDelimiter = "_"
KeyValueNumber = 2
AgentDirName = "/etc/nginx-agent"
DefaultMetricsBatchProcessor = "default_metrics"
DefaultLogsBatchProcessor = "default_logs"
DefaultExporter = "default"
DefaultPipeline = "default"
// Regular expression to match invalid characters in paths.
// It matches whitespace, control characters, non-printable characters, and specific Unicode characters.
regexInvalidPath = "\\s|[[:cntrl:]]|[[:space:]]|[[^:print:]]|ㅤ|\\.\\.|\\*"
regexLabelPattern = "^[a-zA-Z0-9]([a-zA-Z0-9-_.]{0,254}[a-zA-Z0-9])?$"
)
var domainRegex = regexp.MustCompile(
`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`,
)
var viperInstance = viper.NewWithOptions(viper.KeyDelimiter(KeyDelimiter))
func RegisterRunner(r func(cmd *cobra.Command, args []string)) {
RootCommand.Run = r
}
func Execute(ctx context.Context) error {
RootCommand.AddCommand(CompletionCommand)
return RootCommand.ExecuteContext(ctx)
}
func Init(version, commit string) {
setVersion(version, commit)
registerFlags()
checkDeprecatedEnvVars()
}
func checkDeprecatedEnvVars() {
allViperKeys := make(map[string]struct{})
for _, key := range viperInstance.AllKeys() {
allViperKeys[key] = struct{}{}
}
const v3Prefix = EnvPrefix + KeyDelimiter
for _, env := range os.Environ() {
parts := strings.SplitN(env, "=", KeyValueNumber)
if len(parts) != KeyValueNumber {
continue
}
envKey := parts[0]
if !strings.HasPrefix(envKey, v3Prefix) {
continue
}
viperKey := strings.TrimPrefix(envKey, v3Prefix)
viperKey = strings.ToLower(viperKey)
if _, exists := allViperKeys[viperKey]; !exists {
slog.Warn("Detected deprecated or unknown environment variables. "+
"Please update to use the latest environment variables. For more information, visit "+
"https://docs.nginx.com/nginx-one/agent/configure-instances/configuration-overview/.",
"deprecated_env_var", envKey,
)
}
}
}
func RegisterConfigFile() error {
configPath, err := seekFileInPaths(ConfigFileName, configFilePaths()...)
if err != nil {
return err
}
if err = loadPropertiesFromFile(configPath); err != nil {
return err
}
slog.Debug("Configuration file loaded", "config_path", configPath)
viperInstance.Set(ConfigPathKey, configPath)
exePath, err := os.Executable()
if err != nil {
return err
}
viperInstance.Set(UUIDKey, uuidLibrary.Generate(exePath, configPath))
return nil
}
func ResolveConfig() (*Config, error) {
log := resolveLog()
slogger := logger.New(log.Path, log.Level)
slog.SetDefault(slogger)
// Collect allowed directories, so that paths in the config can be validated.
directories := viperInstance.GetStringSlice(AllowedDirectoriesKey)
allowedDirs := resolveAllowedDirectories(directories)
slog.Info("Configured allowed directories", "allowed_directories", allowedDirs)
// Collect all parsing errors before returning the error, so the user sees all issues with config
// in one error message.
var err error
collector, otelcolErr := resolveCollector(allowedDirs)
err = errors.Join(err, otelcolErr)
if err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
config := &Config{
UUID: viperInstance.GetString(UUIDKey),
Version: viperInstance.GetString(VersionKey),
Path: viperInstance.GetString(ConfigPathKey),
Log: log,
DataPlaneConfig: resolveDataPlaneConfig(),
Client: resolveClient(),
AllowedDirectories: allowedDirs,
Collector: collector,
Command: resolveCommand(),
AuxiliaryCommand: resolveAuxiliaryCommand(),
Watchers: resolveWatchers(),
Features: viperInstance.GetStringSlice(FeaturesKey),
Labels: resolveLabels(),
LibDir: viperInstance.GetString(LibDirPathKey),
SyslogServer: resolveSyslogServer(),
ExternalDataSource: resolveExternalDataSource(),
}
defaultCollector(collector, config)
AddLabelsAsOTelHeaders(collector, config.Labels)
slog.Debug("Agent config", "config", config)
slog.Info("Excluded files from being watched for file changes", "exclude_files",
config.Watchers.FileWatcher.ExcludeFiles)
return config, nil
}
// resolveAllowedDirectories checks if the provided directories are valid and returns a slice of cleaned absolute paths.
// It ignores empty paths, paths that are not absolute, and paths containing invalid characters.
// Invalid paths are logged as warnings.
func resolveAllowedDirectories(dirs []string) []string {
allowed := []string{AgentDirName}
for _, dir := range dirs {
re := regexp.MustCompile(regexInvalidPath)
invalidChars := re.MatchString(dir)
if dir == "" || dir == "/" || !filepath.IsAbs(dir) || invalidChars {
slog.Warn("Ignoring invalid directory", "dir", dir)
continue
}
dir = filepath.Clean(dir)
if dir == AgentDirName {
// If the directory is the default agent directory, we skip adding it again.
continue
}
allowed = append(allowed, dir)
}
return allowed
}
func defaultCollector(collector *Collector, config *Config) {
// Always add default host metric receiver and default processor
addDefaultHostMetricsReceiver(collector)
addDefaultProcessors(collector)
// Only add default otlp exporter and pipelines if connected to a management plane
if config.IsCommandGrpcClientConfigured() || config.IsAuxiliaryCommandGrpcClientConfigured() {
addDefaultOtlpExporter(collector, config)
addDefaultPipelines(collector)
}
}
func addDefaultPipelines(collector *Collector) {
if collector.Pipelines.Metrics == nil {
collector.Pipelines.Metrics = make(map[string]*Pipeline)
}
// add check if container and nginx plus or oss
if _, ok := collector.Pipelines.Metrics[DefaultPipeline]; !ok {
collector.Pipelines.Metrics[DefaultPipeline] = &Pipeline{
Receivers: []string{"host_metrics"},
Processors: []string{"batch/default_metrics"},
Exporters: []string{"otlp_grpc/default"},
}
}
if collector.Pipelines.Logs == nil {
collector.Pipelines.Logs = make(map[string]*Pipeline)
}
if _, ok := collector.Pipelines.Logs[DefaultPipeline]; !ok {
collector.Pipelines.Logs[DefaultPipeline] = &Pipeline{
Receivers: []string{"tcplog/nginx_app_protect"},
Processors: []string{"securityviolationsfilter/default", "batch/default_logs"},
Exporters: []string{"otlp_grpc/default"},
}
}
}
func addDefaultOtlpExporter(collector *Collector, config *Config) {
if collector.Exporters.OtlpExporters == nil {
collector.Exporters.OtlpExporters = make(map[string]*OtlpExporter)
}
defaultCommandServer := config.Command
if config.IsAuxiliaryCommandGrpcClientConfigured() {
defaultCommandServer = config.AuxiliaryCommand
}
if _, ok := collector.Exporters.OtlpExporters[DefaultExporter]; !ok && defaultCommandServer != nil {
collector.Exporters.OtlpExporters[DefaultExporter] = &OtlpExporter{
Server: defaultCommandServer.Server,
TLS: defaultCommandServer.TLS,
Compression: "",
}
if defaultCommandServer.Auth != nil {
token := extractTokenFromAuth(defaultCommandServer.Auth)
if token != "" {
addAuthHeader(collector, token)
collector.Exporters.OtlpExporters[DefaultExporter].Authenticator = "headers_setter"
}
}
}
}
func extractTokenFromAuth(auth *AuthConfig) string {
token := auth.Token
if auth.TokenPath != "" {
slog.Debug("Reading token from file", "path", auth.TokenPath)
tokenFromFile, err := file.ReadFromFile(auth.TokenPath)
if err != nil {
slog.Error("Error adding token to default collector, "+
"default collector configuration not started", "error", err)
return ""
}
token = tokenFromFile
}
return token
}
func addAuthHeader(collector *Collector, token string) {
header := []Header{
{
Action: "insert",
Key: "authorization",
Value: token,
},
}
if collector.Extensions.HeadersSetter == nil {
collector.Extensions.HeadersSetter = &HeadersSetter{
Headers: header,
}
} else {
collector.Extensions.HeadersSetter.Headers = append(collector.Extensions.HeadersSetter.
Headers, header...)
}
}
func addDefaultProcessors(collector *Collector) {
if collector.Processors.Batch == nil {
collector.Processors.Batch = make(map[string]*Batch)
}
if _, ok := collector.Processors.Batch[DefaultMetricsBatchProcessor]; !ok {
collector.Processors.Batch[DefaultMetricsBatchProcessor] = &Batch{
SendBatchSize: DefCollectorMetricsBatchProcessorSendBatchSize,
SendBatchMaxSize: DefCollectorMetricsBatchProcessorSendBatchMaxSize,
Timeout: DefCollectorMetricsBatchProcessorTimeout,
}
}
if _, ok := collector.Processors.Batch[DefaultLogsBatchProcessor]; !ok {
collector.Processors.Batch[DefaultLogsBatchProcessor] = &Batch{
SendBatchSize: DefCollectorLogsBatchProcessorSendBatchSize,
SendBatchMaxSize: DefCollectorLogsBatchProcessorSendBatchMaxSize,
Timeout: DefCollectorLogsBatchProcessorTimeout,
}
}
if collector.Processors.SecurityViolationsFilter == nil {
collector.Processors.SecurityViolationsFilter = make(map[string]*SecurityViolationsFilter)
}
if _, ok := collector.Processors.SecurityViolationsFilter["default"]; !ok {
collector.Processors.SecurityViolationsFilter["default"] = &SecurityViolationsFilter{}
}
}
func addDefaultHostMetricsReceiver(collector *Collector) {
isContainer, err := host.NewInfo().IsContainer()
if err != nil {
slog.Debug("No container information found", "error", err)
}
if isContainer {
addDefaultContainerHostMetricsReceiver(collector)
} else {
addDefaultVMHostMetricsReceiver(collector)
}
}
func addDefaultContainerHostMetricsReceiver(collector *Collector) {
if collector.Receivers.ContainerMetrics == nil {
collector.Receivers.ContainerMetrics = &ContainerMetricsReceiver{
CollectionInterval: 1 * time.Minute,
}
}
if collector.Receivers.HostMetrics == nil {
collector.Receivers.HostMetrics = &HostMetrics{
Scrapers: &HostMetricsScrapers{
Network: &NetworkScraper{},
},
CollectionInterval: 1 * time.Minute,
InitialDelay: 1 * time.Second,
}
}
if collector.Log == nil {
collector.Log = &Log{
Path: "stdout",
Level: "info",
}
}
}
func addDefaultVMHostMetricsReceiver(collector *Collector) {
if collector.Receivers.HostMetrics == nil {
collector.Receivers.HostMetrics = &HostMetrics{
Scrapers: &HostMetricsScrapers{
CPU: &CPUScraper{},
Memory: &MemoryScraper{},
Disk: &DiskScraper{},
Filesystem: &FilesystemScraper{},
Network: &NetworkScraper{},
},
CollectionInterval: 1 * time.Minute,
InitialDelay: 1 * time.Second,
}
}
}
func AddLabelsAsOTelHeaders(collector *Collector, labels map[string]any) {
slog.Debug("Adding labels as headers to collector", "labels", labels)
if collector.Extensions.HeadersSetter != nil {
for key, value := range labels {
valueString, ok := value.(string)
if ok {
collector.Extensions.HeadersSetter.Headers = append(collector.Extensions.HeadersSetter.Headers, Header{
Action: "insert",
Key: key,
Value: valueString,
})
}
}
}
}
func setVersion(version, commit string) {
RootCommand.Version = version + "-" + commit
viperInstance.SetDefault(VersionKey, version)
}
func registerFlags() {
viperInstance.SetEnvPrefix(EnvPrefix)
viperInstance.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viperInstance.AutomaticEnv()
fs := RootCommand.Flags()
fs.String(
LogLevelKey,
"info",
"The desired verbosity level for logging messages from nginx-agent. "+
"Available options, in order of severity from highest to lowest, are: "+
"error, warn, info and debug.",
)
fs.String(
LogPathKey,
"",
"The path to output log messages to. "+
"If the default path doesn't exist, log messages are output to stdout/stderr.",
)
fs.String(
LibDirPathKey,
DefLibDir,
"Specifies the path to the nginx-agent lib directory",
)
fs.StringSlice(AllowedDirectoriesKey,
DefaultAllowedDirectories(),
"A comma-separated list of paths that you want to grant NGINX Agent read/write access to. Allowed "+
"directories are case sensitive")
fs.Duration(
InstanceWatcherMonitoringFrequencyKey,
DefInstanceWatcherMonitoringFrequency,
"How often the NGINX Agent will check for instance changes.",
)
fs.Duration(
InstanceHealthWatcherMonitoringFrequencyKey,
DefInstanceHealthWatcherMonitoringFrequency,
"How often the NGINX Agent will check for instance health changes.",
)
fs.Duration(
FileWatcherMonitoringFrequencyKey,
DefFileWatcherMonitoringFrequency,
"How often the NGINX Agent will check for file changes.",
)
fs.StringSlice(
NginxExcludeFilesKey, DefaultExcludedFiles(),
"A comma-separated list of one or more file paths that you want to exclude from file monitoring. "+
"This includes absolute paths or regex patterns",
)
fs.StringSlice(
FeaturesKey,
DefaultFeatures(),
"A comma-separated list of features enabled for the agent.",
)
fs.String(
SyslogServerPort,
DefSyslogServerPort,
"The port Agent will start the syslog server on for logs collection",
)
registerCommonFlags(fs)
registerCommandFlags(fs)
registerAuxiliaryCommandFlags(fs)
registerCollectorFlags(fs)
registerClientFlags(fs)
registerDataPlaneFlags(fs)
registerExternalDataSourceFlags(fs)
fs.SetNormalizeFunc(normalizeFunc)
fs.VisitAll(func(flag *flag.Flag) {
if err := viperInstance.BindPFlag(strings.ReplaceAll(flag.Name, "-", "_"), fs.Lookup(flag.Name)); err != nil {
return
}
err := viperInstance.BindEnv(flag.Name)
if err != nil {
slog.Warn("Error occurred binding env", "env", flag.Name, "error", err)
}
})
}
func registerExternalDataSourceFlags(fs *flag.FlagSet) {
fs.String(
ExternalDataSourceProxyUrlKey,
DefExternalDataSourceProxyUrl,
"Url to the proxy service for fetching external files.",
)
fs.StringSlice(
ExternalDataSourceAllowDomainsKey,
[]string{},
"List of allowed domains for external data sources.",
)
fs.StringSlice(
ExternalDataSourceAllowedFileTypesKey,
[]string{},
"List of allowed file types for external data sources.",
)
fs.Int64(
ExternalDataSourceMaxBytesKey,
DefExternalDataSourceMaxBytes,
"Maximum size in bytes for external data sources.",
)
}
func registerDataPlaneFlags(fs *flag.FlagSet) {
fs.Duration(
NginxReloadMonitoringPeriodKey,
DefNginxReloadMonitoringPeriod,
"The amount of time to monitor NGINX after a reload of configuration.",
)
fs.Bool(
NginxTreatWarningsAsErrorsKey,
DefTreatErrorsAsWarnings,
"Warning messages in the NGINX errors logs after a NGINX reload will be treated as an error.",
)
fs.String(
NginxApiURLKey,
"",
"The NGINX Plus API URL.",
)
fs.String(
NginxApiSocketKey,
"",
"The NGINX Plus API Unix socket path.",
)
fs.String(
NginxApiTlsCaKey,
DefNginxApiTlsCa,
"The NGINX Plus CA certificate file location needed to call the NGINX Plus API if SSL is enabled.",
)
fs.StringSlice(
NginxExcludeLogsKey, []string{},
"A comma-separated list of one or more NGINX log paths that you want to exclude from metrics "+
"collection or error monitoring. This includes absolute paths or regex patterns",
)
// NGINX Reload Backoff Flags
fs.Duration(
NginxReloadBackoffInitialIntervalKey,
DefNginxReloadBackoffInitialInterval,
"The NGINX reload backoff initial interval, value in seconds")
fs.Duration(
NginxReloadBackoffMaxIntervalKey,
DefNginxReloadBackoffMaxInterval,
"The NGINX reload backoff max interval, value in seconds")
fs.Duration(
NginxReloadBackoffMaxElapsedTimeKey,
DefNginxReloadBackoffMaxElapsedTime,
"The NGINX reload backoff max elapsed time, value in seconds")
fs.Float64(
NginxReloadBackoffRandomizationFactorKey,
DefNginxReloadBackoffRandomizationFactor,
"The NGINX reload backoff randomization factor, value float")
fs.Float64(
NginxReloadBackoffMultiplierKey,
DefNginxReloadBackoffMultiplier,
"The NGINX reload backoff multiplier, value float")
}
func registerCommonFlags(fs *flag.FlagSet) {
fs.StringToString(
LabelsRootKey,
DefaultLabels(),
"A list of labels associated with these instances",
)
}
func registerClientFlags(fs *flag.FlagSet) {
// HTTP Flags
fs.Duration(
ClientHTTPTimeoutKey,
DefHTTPTimeout,
"The client HTTP Timeout, value in seconds")
// Backoff Flags
fs.Duration(
ClientBackoffInitialIntervalKey,
DefBackoffInitialInterval,
"The client backoff initial interval, value in seconds")
fs.Duration(
ClientBackoffMaxIntervalKey,
DefBackoffMaxInterval,
"The client backoff max interval, value in seconds")
fs.Duration(
ClientBackoffMaxElapsedTimeKey,
DefBackoffMaxElapsedTime,
"The client backoff max elapsed time, value in seconds")
fs.Float64(
ClientBackoffRandomizationFactorKey,
DefBackoffRandomizationFactor,
"The client backoff randomization factor, value float")
fs.Float64(
ClientBackoffMultiplierKey,
DefBackoffMultiplier,
"The client backoff multiplier, value float")
// GRPC Flags
fs.Duration(
ClientKeepAliveTimeoutKey,
DefGRPCKeepAliveTimeout,
"Updates the client grpc setting, KeepAlive Timeout with the specific value in seconds.",
)
fs.Duration(
ClientKeepAliveTimeKey,
DefGRPCKeepAliveTime,
"Updates the client grpc setting, KeepAlive Time with the specific value in seconds.",
)
fs.Bool(
ClientKeepAlivePermitWithoutStreamKey,
DefGRPCKeepAlivePermitWithoutStream,
"Update the client grpc setting, KeepAlive PermitWithoutStream value")
fs.Int(
ClientGRPCMaxMessageSizeKey,
DefMaxMessageSize,
"The value used, if not 0, for both max_message_send_size and max_message_receive_size",
)
fs.Int(
ClientGRPCMaxMessageReceiveSizeKey,
DefMaxMessageRecieveSize,
"Updates the client grpc setting MaxRecvMsgSize with the specific value in bytes.",
)
fs.Int(
ClientGRPCMaxMessageSendSizeKey,
DefMaxMessageSendSize,
"Updates the client grpc setting MaxSendMsgSize with the specific value in bytes.",
)
fs.Uint32(
ClientGRPCFileChunkSizeKey,
DefFileChunkSize,
"File chunk size in bytes.",
)
fs.Duration(
ClientGRPCConnectionResetTimeoutKey,
DefGRPCConnectionResetTimeout,
"Duration to wait for in-progress management plane requests to complete before resetting the gRPC connection.",
)
fs.Uint32(
ClientGRPCMaxFileSizeKey,
DefMaxFileSize,
"Max file size in bytes.",
)
fs.Duration(
ClientGRPCResponseTimeoutKey,
DefResponseTimeout,
"Duration to wait for a response before retrying request",
)
fs.Int(
ClientGRPCMaxParallelFileOperationsKey,
DefMaxParallelFileOperations,
"Maximum number of file downloads or uploads performed in parallel",
)
fs.Duration(
ClientFileDownloadTimeoutKey,
DefClientFileDownloadTimeout,
"Timeout value in seconds, for downloading a file during a config apply.",
)
// Deprecated fields
markFieldDeprecated(
fs,
ClientGRPCConnectionResetTimeoutKey,
"this field is no longer supported",
)
}
func markFieldDeprecated(fs *flag.FlagSet, field, message string) {
err := fs.MarkDeprecated(field, message)
if err != nil {
slog.Error("Failed to deprecate field", "field", field, "error", err)
}
}
func registerCommandFlags(fs *flag.FlagSet) {
fs.String(
CommandServerHostKey,
DefCommandServerHostKey,
"The target hostname of the command server endpoint for command and control.",
)
fs.Int32(
CommandServerPortKey,
DefCommandServerPortKey,
"The target port of the command server endpoint for command and control.",
)
fs.String(
CommandServerTypeKey,
DefCommandServerTypeKey,
"The target protocol (gRPC or HTTP) the command server endpoint for command and control.",
)
fs.String(
CommandAuthTokenKey,
DefCommandAuthTokenKey,
"The token used in the authentication handshake with the command server endpoint for command and control.",
)
fs.String(
CommandAuthTokenPathKey,
DefCommandAuthTokenPathKey,
"The path to the file containing the token used in the authentication handshake with "+
"the command server endpoint for command and control.",
)
fs.String(
CommandTLSCertKey,
DefCommandTLSCertKey,
"The path to the certificate file to use for TLS communication with the command server.",
)
fs.String(
CommandTLSKeyKey,
DefCommandTLSKeyKey,
"The path to the certificate key file to use for TLS communication with the command server.",
)
fs.String(
CommandTLSCaKey,
DefCommandTLSCaKey,
"The path to CA certificate file to use for TLS communication with the command server.",
)
fs.Bool(
CommandTLSSkipVerifyKey,
DefCommandTLSSkipVerifyKey,
"Testing only. Skip verify controls client verification of a server's certificate chain and host name.",
)
fs.String(
CommandTLSServerNameKey,
DefCommandTLServerNameKey,
"Specifies the name of the server sent in the TLS configuration.",
)
fs.Duration(
CommandServerProxyTimeoutKey,
DefCommandServerProxyTimeoutKey,
"The explicit forward proxy HTTP Timeout, value in seconds")
fs.String(
CommandServerProxyURLKey,
DefCommandServerProxyURlKey,
"The Proxy URL to use for explicit forward proxy.",
)
fs.String(
CommandServerProxyNoProxyKey,
DefCommandServerProxyNoProxyKey,
"The No-Proxy URL to use for explicit forward proxy.",
)
fs.String(
CommandServerProxyAuthMethodKey,
DefCommandServerProxyAuthMethodKey,
"The Authentication method used for explicit forward proxy.",
)
fs.String(
CommandServerProxyUsernameKey,
DefCommandServerProxyUsernameKey,
"The Username used for basic authentication for explicit forward proxy.",
)
fs.String(
CommandServerProxyPasswordKey,
DefCommandServerProxyPasswordKey,
"The Password used for basic authentication for explicit forward proxy.",
)
fs.String(
CommandServerProxyTokenKey,
DefCommandServerProxyTokenKey,
"The bearer token used for authentication for explicit forward proxy.",
)
fs.String(
CommandServerProxyTLSCertKey,
DefCommandServerProxyTLSCertKey,
"The path to the certificate file to use for TLS communication with the command server.",
)
fs.String(
CommandServerProxyTLSKeyKey,
DefCommandServerProxyTLSKeyKey,
"The path to the certificate key file to use for TLS communication with the command server.",
)
fs.String(
CommandServerProxyTLSCaKey,
DefCommandServerProxyTLSCaKey,
"The path to CA certificate file to use for TLS communication with the command server.",
)
fs.Bool(
CommandServerProxyTLSSkipVerifyKey,
DefCommandServerProxyTLSSkipVerifyKey,
"Testing only. Skip verify controls client verification of a server's certificate chain and host name.",
)
fs.String(
CommandServerProxyTLSServerNameKey,
DefCommandServerProxyTLServerNameKey,
"Specifies the name of the server sent in the TLS configuration.",
)
}
func registerAuxiliaryCommandFlags(fs *flag.FlagSet) {
fs.String(
AuxiliaryCommandServerHostKey,
DefAuxiliaryCommandServerHostKey,
"The target hostname of the auxiliary server endpoint for read only mode.",
)
fs.Int32(
AuxiliaryCommandServerPortKey,
DefAuxiliaryCommandServerPortKey,
"The target port of the auxiliary server endpoint for read only mode.",
)
fs.String(
AuxiliaryCommandServerTypeKey,
DefAuxiliaryCommandServerTypeKey,
"The target protocol (gRPC or HTTP) the auxiliary server endpoint for read only mode.",
)
fs.String(
AuxiliaryCommandAuthTokenKey,
DefAuxiliaryCommandAuthTokenKey,
"The token used in the authentication handshake with the auxiliary server endpoint for read only mode.",
)
fs.String(
AuxiliaryCommandAuthTokenPathKey,
DefAuxiliaryCommandAuthTokenPathKey,
"The path to the file containing the token used in the authentication handshake with "+
"the auxiliary server endpoint for read only mode.",
)
fs.String(
AuxiliaryCommandTLSCertKey,
DefAuxiliaryCommandTLSCertKey,
"The path to the certificate file to use for TLS communication with the auxiliary command server.",
)
fs.String(
AuxiliaryCommandTLSKeyKey,
DefAuxiliaryCommandTLSKeyKey,
"The path to the certificate key file to use for TLS communication with the auxiliary command server.",
)
fs.String(
AuxiliaryCommandTLSCaKey,
DefAuxiliaryCommandTLSCaKey,
"The path to CA certificate file to use for TLS communication with the auxiliary command server.",
)
fs.Bool(
AuxiliaryCommandTLSSkipVerifyKey,
DefAuxiliaryCommandTLSSkipVerifyKey,
"Testing only. Skip verify controls client verification of a server's certificate chain and host name.",
)
fs.String(
AuxiliaryCommandTLSServerNameKey,
DefAuxiliaryCommandTLServerNameKey,
"Specifies the name of the server sent in the TLS configuration.",
)
}
func registerCollectorFlags(fs *flag.FlagSet) {
fs.String(
CollectorConfigPathKey,
DefCollectorConfigPath,
"The path to the Opentelemetry Collector configuration file.",
)
fs.StringSlice(
CollectorAdditionalConfigPathsKey,
[]string{},
"Paths to additional OpenTelemetry Collector configuration files. The order of the configuration files"+
" determines which config file takes priority. The last config file will take precedent over other files "+
"if they have the same setting. Paths to configuration files must be absolute",
)
fs.String(
CollectorLogLevelKey,
DefCollectorLogLevel,
"The desired verbosity level for logging messages from nginx-agent OTel collector. "+
"Available options, in order of severity from highest to lowest, are: "+
"ERROR, WARN, INFO and DEBUG.",
)
fs.String(
CollectorLogPathKey,
DefCollectorLogPath,
"The path to output OTel collector log messages to. "+
"If the default path doesn't exist, log messages are output to stdout/stderr.",
)
fs.String(
CollectorExtensionsHealthServerHostKey,
DefCollectorExtensionsHealthServerHost,
`The hostname of the address to publish the OTel collector health check status.`,
)
fs.Int32(
CollectorExtensionsHealthServerPortKey,
DefCollectorExtensionsHealthServerPort,
`The port of the address to publish the OTel collector health check status.`,
)
fs.String(
CollectorExtensionsHealthPathKey,
DefCollectorExtensionsHealthPath,
`The path to be configured for the OTel collector health check server`,
)
fs.String(
CollectorExtensionsHealthTLSCertKey,
DefCollectorExtensionsHealthTLSCertPath,
"The path to the certificate file to use for TLS communication with the OTel collector health check server.",
)
fs.String(
CollectorExtensionsHealthTLSKeyKey,
DefCollectorExtensionsHealthTLSKeyPath,
"The path to the certificate key file to use for TLS communication "+
"with the OTel collector health check server.",
)
fs.String(
CollectorExtensionsHealthTLSCaKey,
DefCollectorExtensionsHealthTLSCAPath,
"The path to CA certificate file to use for TLS communication with the OTel collector health check server.",
)
fs.Bool(
CollectorExtensionsHealthTLSSkipVerifyKey,
DefCollectorExtensionsHealthTLSSkipVerify,
"Testing only. Skip verify controls client verification of a server's certificate chain and host name.",
)
fs.String(
CollectorExtensionsHealthTLSServerNameKey,
DefCollectorExtensionsHealthTLServerNameKey,
"Specifies the name of the server sent in the TLS configuration.",
)
}
func seekFileInPaths(fileName string, directories ...string) (string, error) {
for _, directory := range directories {
f := filepath.Join(directory, fileName)
if _, err := os.Stat(f); err == nil {
return f, nil
}
}
return "", errors.New("a valid configuration has not been found in any of the search paths")
}
func configFilePaths() []string {
paths := []string{
"/etc/nginx-agent/",
}
path, err := os.Getwd()
if err == nil {
paths = append(paths, path)
} else {
slog.Warn("Unable to determine process's current directory", "error", err)
}
return paths
}
func loadPropertiesFromFile(cfg string) error {
validationError := validateYamlFile(cfg)
if validationError != nil {
return validationError
}
viperInstance.SetConfigFile(cfg)
viperInstance.SetConfigType("yaml")
err := viperInstance.MergeInConfig()
if err != nil {
return fmt.Errorf("error loading config file %s: %w", cfg, err)
}
return nil
}
func validateYamlFile(filePath string) error {
fileContents, readError := os.ReadFile(filePath)
if readError != nil {
return fmt.Errorf("failed to read file %s: %w", filePath, readError)
}
decoder := yaml.NewDecoder(bytes.NewReader(fileContents), yaml.DisallowUnknownField())
if err := decoder.Decode(&Config{}); err != nil {
return errors.New(yaml.FormatError(err, false, false))
}