Files
metrics_agent/config.go
T

66 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"os"
"strconv"
)
// Config holds the agent runtime configuration. It is read from an optional
// JSON file and can be overridden by environment variables, which is handy for
// systemd drop-ins and for deploying the same binary to many nodes.
type Config struct {
Node string `json:"node"` // value of the "instance" label attached to every series
HubURL string `json:"hub_url"` // full ingest URL, e.g. https://metrics-…/api/v1/import/prometheus
User string `json:"user"` // basic-auth user (empty disables auth)
Pass string `json:"pass"` // basic-auth password
IntervalSec int `json:"interval_sec"` // push period in seconds (default 15)
}
// defaultConfig returns the baseline configuration: the machine hostname as the
// node name and a 15-second push interval.
func defaultConfig() Config {
host, _ := os.Hostname()
return Config{Node: host, IntervalSec: 15}
}
// loadConfig reads the JSON file at path (when non-empty) and then applies
// environment overrides. Recognised env vars: FLEET_NODE, FLEET_HUB_URL,
// FLEET_USER, FLEET_PASS, FLEET_INTERVAL.
func loadConfig(path string) (Config, error) {
cfg := defaultConfig()
if path != "" {
b, err := os.ReadFile(path)
if err != nil {
return cfg, err
}
if err := json.Unmarshal(b, &cfg); err != nil {
return cfg, err
}
}
if v := os.Getenv("FLEET_NODE"); v != "" {
cfg.Node = v
}
if v := os.Getenv("FLEET_HUB_URL"); v != "" {
cfg.HubURL = v
}
if v := os.Getenv("FLEET_USER"); v != "" {
cfg.User = v
}
if v := os.Getenv("FLEET_PASS"); v != "" {
cfg.Pass = v
}
if v := os.Getenv("FLEET_INTERVAL"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
cfg.IntervalSec = n
}
}
if cfg.IntervalSec <= 0 {
cfg.IntervalSec = 15
}
if cfg.Node == "" {
cfg.Node, _ = os.Hostname()
}
return cfg, nil
}