-
Notifications
You must be signed in to change notification settings - Fork 7
/
config.go
551 lines (502 loc) · 16.6 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
package config
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"sync"
"time"
"github.com/gwos/tcg/logzer"
"github.com/gwos/tcg/sdk/clients"
"github.com/gwos/tcg/sdk/logper"
"github.com/gwos/tcg/sdk/transit"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
"gopkg.in/yaml.v3"
)
var (
once sync.Once
cfg *Config
liblogger zerolog.Logger
)
const (
InstallationModeEnv = "INSTALLATION_MODE"
InstallationModeCMC = "CHILD_MANAGED_CHILD"
InstallationModePMC = "PARENT_MANAGED_CHILD"
InstallationModeP = "PARENT"
InstallationModeS = "STANDALONE"
SecVerPrefix = "_v1_"
)
// LogLevel defines levels in logrus-style
type LogLevel int
// Enum levels
const (
Error LogLevel = iota
Warn
Info
Debug
)
func (l LogLevel) String() string {
return [...]string{"Error", "Warn", "Info", "Debug"}[l]
}
type Nats struct {
// NatsAckWait is the time the NATS server will wait before resending a message
// Should be greater then the GWClient request duration
NatsAckWait time.Duration `yaml:"-"`
// designates the maximum number of outstanding acknowledgements
// (messages that have been delivered but not acknowledged)
// that NATS Streaming will allow for a given subscription.
// When this limit is reached, NATS Streaming will suspend delivery of messages
// to this subscription until the number of unacknowledged messages falls below the specified limit
NatsMaxInflight int `yaml:"-"`
// NatsMaxPubAcksInflight accepts number of unacknowledged messages
// that a publisher may have in-flight at any given time.
// When this maximum is reached, further async publish calls will block
// until the number of unacknowledged messages falls below the specified limit
NatsMaxPubAcksInflight int `yaml:"-"`
NatsMaxPayload int32 `yaml:"-"`
// NatsMonitorPort enables monitoring on http port useful for debug
// curl 'localhost:8222/streaming/channelsz?limit=0&offset=0&subs=1'
// More info: https://docs.nats.io/nats-streaming-concepts/monitoring
NatsMonitorPort int `yaml:"-"`
NatsStoreDir string `yaml:"natsFilestoreDir"`
// NatsStoreType accepts "FILE"|"MEMORY"
NatsStoreType string `yaml:"natsStoreType"`
// How long messages are kept
NatsStoreMaxAge time.Duration `yaml:"natsStoreMaxAge"`
// How many bytes are allowed per-channel
NatsStoreMaxBytes int64 `yaml:"natsStoreMaxBytes"`
// How many messages are allowed per-channel
NatsStoreMaxMsgs int64 `yaml:"natsStoreMaxMsgs"`
// NatsServerConfigFile is used to override yaml values for
// NATS server configuration (debug only).
NatsServerConfigFile string `yaml:"natsServerConfigFile"`
}
// Hashsum calculates FNV non-cryptographic hash suitable for checking the equality
func (c Nats) Hashsum() ([]byte, error) {
return Hashsum(c)
}
// Connector defines TCG Connector configuration
// see GetConfig() for defaults
type Connector struct {
transit.AgentIdentity `yaml:",inline"`
BatchEvents time.Duration `yaml:"batchEvents"`
BatchMetrics time.Duration `yaml:"batchMetrics"`
BatchMaxBytes int `yaml:"batchMaxBytes"`
// ControllerAddr accepts value for combined "host:port"
// used as `http.Server{Addr}`
ControllerAddr string `yaml:"controllerAddr"`
ControllerCertFile string `yaml:"controllerCertFile"`
ControllerKeyFile string `yaml:"controllerKeyFile"`
// ControllerPin accepts value from environment
// provides local access for debug
ControllerPin string `yaml:"-"`
// Custom HTTP configuration
ControllerReadTimeout time.Duration `yaml:"-"`
ControllerWriteTimeout time.Duration `yaml:"-"`
ControllerStartTimeout time.Duration `yaml:"-"`
ControllerStopTimeout time.Duration `yaml:"-"`
Enabled bool `yaml:"enabled"`
InstallationMode string `yaml:"installationMode,omitempty"`
IsDynamicInventory bool `yaml:"-"`
// GWEncode defines using HTTPEncode in Groundwork client: child|force|off
// enabled for child by default
GWEncode string `yaml:"-"`
// LogCondense accepts time duration for condensing similar records
// if 0 turn off condensing
LogCondense time.Duration `yaml:"logCondense"`
// LogFile accepts file path to log in addition to stdout
LogFile string `yaml:"logFile"`
LogFileMaxSize int64 `yaml:"logFileMaxSize"`
// Log files are rotated count times before being removed.
// If count is 0, old versions are removed rather than rotated.
LogFileRotate int `yaml:"logFileRotate"`
LogLevel LogLevel `yaml:"logLevel"`
LogColors bool `yaml:"logColors"`
LogTimeFormat string `yaml:"logTimeFormat"`
Nats `yaml:",inline"`
TransportStartRndDelay int `yaml:"-"`
}
// ConnectorDTO defines TCG Connector configuration
type ConnectorDTO struct {
AgentID string `json:"agentId"`
AppName string `json:"appName"`
AppType string `json:"appType"`
TcgURL string `json:"tcgUrl"`
LogLevel LogLevel `json:"logLevel"`
Enabled bool `json:"enabled"`
DSConnection DSConnection `json:"dalekservicesConnection"`
GWConnections GWConnections `json:"groundworkConnections"`
// TODO: extend LoadConnectorDTO to handle more fields
// MonitorConnection MonitorConnectionDto
// MetricsProfile MetricsProfileDto
}
// DSConnection defines DalekServices Connection configuration
type DSConnection clients.DSConnection
// GWConnection defines Groundwork Connection configuration
type GWConnection clients.GWConnection
// MarshalYAML implements yaml.Marshaler interface
// overrides the password field
func (con GWConnection) MarshalYAML() (interface{}, error) {
type plain GWConnection
c := plain(con)
if s := os.Getenv(SecKeyEnv); s != "" {
encrypted, err := Encrypt([]byte(c.Password), []byte(s))
if err != nil {
return nil, err
}
c.Password = fmt.Sprintf("%s%x", SecVerPrefix, encrypted)
}
return c, nil
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
// overrides the password field
func (con *GWConnection) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain GWConnection
if err := unmarshal((*plain)(con)); err != nil {
return err
}
if strings.HasPrefix(con.Password, SecVerPrefix) {
s := os.Getenv(SecKeyEnv)
if s == "" {
return fmt.Errorf("unmarshaler error: %s SecKeyEnv is empty", SecVerPrefix)
}
var encrypted []byte
fmt.Sscanf(con.Password, SecVerPrefix+"%x", &encrypted)
decrypted, err := Decrypt(encrypted, []byte(s))
if err != nil {
return err
}
con.Password = string(decrypted)
}
return nil
}
// GWConnections defines a set of configurations
type GWConnections []*GWConnection
// UnmarshalYAML implements the yaml.Unmarshaler interface.
// Applies decode to items in collection for setting only fields present in yaml.
// Note (as for gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b):
//
// if yaml defines an empty set this method is not called but target is truncated.
func (cc *GWConnections) UnmarshalYAML(value *yaml.Node) error {
for i, node := range value.Content {
if len(*cc) < i+1 {
*cc = append(*cc, GWConnections{{}}...)
}
if err := node.Decode((*cc)[i]); err != nil {
return err
}
}
return nil
}
// Config defines TCG Agent configuration
type Config struct {
Connector Connector `yaml:"connector"`
DSConnection DSConnection `yaml:"dsConnection"`
GWConnections GWConnections `yaml:"gwConnections"`
}
func defaults() Config {
return Config{
Connector: Connector{
BatchEvents: 0,
BatchMetrics: 0,
BatchMaxBytes: 1024 * 1024, // 1MB
ControllerAddr: ":8099",
ControllerReadTimeout: time.Second * 10,
ControllerWriteTimeout: time.Second * 20,
ControllerStartTimeout: time.Second * 4,
ControllerStopTimeout: time.Second * 4,
LogCondense: 0,
LogFileMaxSize: 1024 * 1024 * 10, // 10MB
LogFileRotate: 5,
LogLevel: 1,
LogColors: false,
LogTimeFormat: time.RFC3339,
Nats: Nats{
NatsAckWait: time.Second * 30,
NatsMaxInflight: 4,
NatsMaxPubAcksInflight: 4,
NatsMaxPayload: 1024 * 1024 * 8, // 8MB github.com/nats-io/nats-server/releases/tag/v2.3.4
NatsMonitorPort: 0,
NatsStoreDir: "natsstore",
NatsStoreType: "FILE",
NatsStoreMaxAge: time.Hour * 24 * 10, // 10days
NatsStoreMaxBytes: 1024 * 1024 * 1024 * 20, // 20GB
NatsStoreMaxMsgs: 1_000_000, // 1 000 000
NatsServerConfigFile: "",
},
TransportStartRndDelay: 60,
},
// create disabled connections to support partial setting with struct-path
// 4 items should be enough
GWConnections: GWConnections{{}, {}, {}, {}},
DSConnection: DSConnection{},
}
}
// GetConfig implements Singleton pattern
func GetConfig() *Config {
once.Do(func() {
/* buffer the logging while configuring */
logBuf := &logzer.LogBuffer{
Level: zerolog.TraceLevel,
Size: 16,
}
log.Logger = zerolog.New(logBuf).
With().Timestamp().Caller().Logger()
log.Info().Msgf("Build info: %s / %s", buildTag, buildTime)
/* merge defaults, file, and env */
applyFlags()
cfg = new(Config)
*cfg = defaults()
if data, err := os.ReadFile(cfg.ConfigPath()); err != nil {
log.Warn().Err(err).
Str("configPath", cfg.ConfigPath()).
Msg("could not read config")
} else {
if err := yaml.Unmarshal(data, cfg); err != nil {
log.Err(err).
Str("configData", string(data)).
Str("configPath", cfg.ConfigPath()).
Msg("could not parse config")
}
}
if data, err := yaml.Marshal(cfg); err == nil {
data = applyEnv(data)
if err := yaml.Unmarshal(data, cfg); err != nil {
log.Err(err).
Str("configData", string(data)).
Msg("could not apply env vars")
}
} else {
log.Warn().Err(err).
Msg("could not apply env vars")
}
/* init logger and flush buffer */
cfg.initLogger()
logzer.WriteLogBuffer(logBuf)
})
return cfg
}
// ConfigPath returns config file path
func (cfg Config) ConfigPath() string {
configPath := os.Getenv(ConfigEnv)
if configPath == "" {
configPath = ConfigName
if wd, err := os.Getwd(); err == nil {
configPath = path.Join(wd, ConfigName)
}
}
return configPath
}
func (cfg *Config) loadConnector(data []byte) (*ConnectorDTO, error) {
var dto ConnectorDTO
if err := json.Unmarshal(data, &dto); err != nil {
log.Err(err).Msg("could not parse connector")
return nil, err
}
cfg.Connector.AgentID = dto.AgentID
cfg.Connector.AppName = dto.AppName
cfg.Connector.AppType = dto.AppType
cfg.Connector.LogLevel = dto.LogLevel
cfg.Connector.Enabled = dto.Enabled
cfg.GWConnections = dto.GWConnections
if len(dto.DSConnection.HostName) != 0 {
cfg.DSConnection.HostName = dto.DSConnection.HostName
}
return &dto, nil
}
func (cfg *Config) loadAdvancedPrefixes(data []byte) error {
var s struct {
Advanced struct {
Prefixes []struct {
GWConnectionID int `json:"groundworkConnectionId"`
Prefix string `json:"prefix"`
} `json:"prefixes,omitempty"`
} `json:"advanced,omitempty"`
}
if err := json.Unmarshal(data, &s); err != nil {
log.Err(err).Msg("could not parse advanced")
return err
}
for _, c := range cfg.GWConnections {
c.PrefixResourceNames = false
c.ResourceNamePrefix = ""
for _, p := range s.Advanced.Prefixes {
if c.ID == p.GWConnectionID && p.Prefix != "" {
c.PrefixResourceNames = true
c.ResourceNamePrefix = p.Prefix
}
}
}
return nil
}
func (cfg *Config) loadDynamicInventoryFlag(data []byte) error {
/* TODO: Support dynamic flag in UI
var s struct {
Connection struct {
Extensions struct {
IsDynamicInventory bool `json:"isDynamicInventory"`
} `json:"extensions,omitempty"`
} `json:"monitorConnection,omitempty"`
}
if err := json.Unmarshal(data, &s); err != nil {
log.Error("|config.go| : [loadDynamicInventoryFlag] : ", err.Error())
return err
} */
switch cfg.Connector.AppType {
case "CHECKER", "APM", "EVENTS":
cfg.Connector.IsDynamicInventory = true
default:
cfg.Connector.IsDynamicInventory = false
}
return nil
}
// LoadConnectorDTO loads ConnectorDTO into Config
func (cfg *Config) LoadConnectorDTO(data []byte) (*ConnectorDTO, error) {
newCfg := new(Config)
*newCfg = defaults()
/* load config file */
if data, err := os.ReadFile(newCfg.ConfigPath()); err != nil {
log.Warn().Err(err).
Str("configPath", newCfg.ConfigPath()).
Msg("could not read config")
} else {
if err := yaml.Unmarshal(data, newCfg); err != nil {
log.Warn().Err(err).
Str("configData", string(data)).
Str("configPath", newCfg.ConfigPath()).
Msg("could not parse config")
}
}
/* load as ConnectorDTO */
dto, err := newCfg.loadConnector(data)
if err != nil {
return nil, err
}
/* load as struct with advanced prefixes field */
if err := newCfg.loadAdvancedPrefixes(data); err != nil {
return nil, err
}
/* load as struct with dynamic inventory flag */
if err := newCfg.loadDynamicInventoryFlag(data); err != nil {
return nil, err
}
if output, err := yaml.Marshal(newCfg); err != nil {
log.Err(err).
Str("configData", string(output)).
Msg("could not prepare config for writing")
} else {
/* override config file */
if err := os.WriteFile(newCfg.ConfigPath(), output, 0644); err != nil {
log.Err(err).
Str("configData", string(output)).
Str("configPath", newCfg.ConfigPath()).
Msg("could not write config")
}
/* load environment */
output = applyEnv(output)
if err := yaml.Unmarshal(output, newCfg); err != nil {
log.Err(err).
Str("configData", string(output)).
Msg("could not apply env vars")
}
}
/* process PMC */
if cfg.IsConfiguringPMC() {
newCfg.Connector.InstallationMode = InstallationModePMC
}
/* prepare gwConnections */
gwEncode := strings.ToLower(newCfg.Connector.GWEncode)
for i := range newCfg.GWConnections {
newCfg.GWConnections[i].IsDynamicInventory = newCfg.Connector.IsDynamicInventory
newCfg.GWConnections[i].HTTPEncode = gwEncode == "force" ||
(gwEncode != "off" && newCfg.GWConnections[i].IsChild)
}
/* update config */
cfg.Connector = newCfg.Connector
cfg.DSConnection = newCfg.DSConnection
cfg.GWConnections = newCfg.GWConnections
/* update logger */
cfg.initLogger()
return dto, nil
}
// IsConfiguringPMC checks configuration stage
func (cfg *Config) IsConfiguringPMC() bool {
return os.Getenv(InstallationModeEnv) == InstallationModePMC &&
cfg.Connector.InstallationMode != InstallationModePMC
}
// InitTracerProvider inits provider
func (cfg Config) InitTracerProvider() (*tracesdk.TracerProvider, error) {
return initOTLP(fmt.Sprintf("%s:%s:%s",
cfg.Connector.AppType, cfg.Connector.AppName, cfg.Connector.AgentID))
}
// Hashsum calculates FNV non-cryptographic hash suitable for checking the equality
func (cfg Config) Hashsum() ([]byte, error) {
return Hashsum(cfg)
}
func (cfg Config) initLogger() {
opts := []logzer.Option{
logzer.WithCondense(cfg.Connector.LogCondense),
logzer.WithLastErrors(10),
logzer.WithLevel([...]zerolog.Level{3, 2, 1, 0}[cfg.Connector.LogLevel]),
logzer.WithColors(cfg.Connector.LogColors),
logzer.WithTimeFormat(cfg.Connector.LogTimeFormat),
}
if cfg.Connector.LogFile != "" {
opts = append(opts, logzer.WithLogFile(&logzer.LogFile{
FilePath: cfg.Connector.LogFile,
MaxSize: cfg.Connector.LogFileMaxSize,
Rotate: cfg.Connector.LogFileRotate,
}))
}
/* prevent writes in global logger */
log.Logger = zerolog.Nop()
/* reset to defaults */
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
/* apply options */
w := logzer.NewLoggerWriter(opts...)
/* set global logger */
log.Logger = zerolog.New(w).
With().Timestamp().Caller().
Logger()
/* set wrapped logger */
liblogger = zerolog.New(w).
With().Timestamp().CallerWithSkipFrameCount(4).
Logger()
logper.SetLogger(
func(fields interface{}, format string, a ...interface{}) {
log2zerolog(zerolog.ErrorLevel, fields, format, a...)
},
func(fields interface{}, format string, a ...interface{}) {
log2zerolog(zerolog.WarnLevel, fields, format, a...)
},
func(fields interface{}, format string, a ...interface{}) {
log2zerolog(zerolog.InfoLevel, fields, format, a...)
},
func(fields interface{}, format string, a ...interface{}) {
if zerolog.GlobalLevel() <= zerolog.DebugLevel {
log2zerolog(zerolog.DebugLevel, fields, format, a...)
}
},
func() bool { return zerolog.GlobalLevel() <= zerolog.DebugLevel },
)
}
func log2zerolog(lvl zerolog.Level, fields interface{}, format string, a ...interface{}) {
e := liblogger.WithLevel(lvl)
if ff, ok := fields.(interface {
LogFields() (map[string]interface{}, map[string][]byte)
}); ok {
m1, m2 := ff.LogFields()
e.Fields(m1)
for k, v := range m2 {
e.RawJSON(k, v)
}
} else if _, ok := fields.(map[string]interface{}); ok {
e.Fields(fields)
} else if _, ok := fields.([]interface{}); ok {
e.Fields(fields)
}
e.Msgf(format, a...)
}