-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
199 lines (164 loc) · 5.26 KB
/
Copy pathmain.go
File metadata and controls
199 lines (164 loc) · 5.26 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
package main
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/Puppet-Finland/updates-exporter/distros"
"github.com/Puppet-Finland/updates-exporter/distros/rhel"
"github.com/Puppet-Finland/updates-exporter/distros/ubuntu"
)
type Config struct {
Port int `mapstructure:"port"`
Interval int `mapstructure:"interval"`
Version bool `mapstructure:"version"`
LogLevel string `mapstructure:"log-level"`
Config string `mapstructure:"config"`
}
const (
DEFAULT_INTERVAL = 3600
DEFAULT_PORT = 9101
)
var (
securityUpdates = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "updates_pending_security",
Help: "Number of pending security updates",
})
totalUpdates = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "updates_pending",
Help: "Total number of pending updates",
})
rebootRequired = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "updates_reboot_required",
Help: "1 if a reboot is required, 0 otherwise",
})
latestCacheUpdate = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "updates_latest_cache_change",
Help: "Unix timestamp of latest change to update cache",
})
Version = "dev"
)
func getDistro() distros.Distro {
switch distros.GetLinuxDistro() {
case "ubuntu":
return ubuntu.Ubuntu{}
case "rhel":
return rhel.Rhel{}
default:
return nil
}
}
func updateMetrics(d distros.Distro) {
if d == nil {
return
}
securityUpdates.Set(float64(d.GetSecurityUpdates()))
totalUpdates.Set(float64(d.GetTotalUpdates()))
latestCacheUpdate.Set(float64(d.GetLatestCacheChange().Unix()))
if d.GetRebootRequired() {
rebootRequired.Set(1)
} else {
rebootRequired.Set(0)
}
}
func main() {
logLevel := &slog.LevelVar{}
logLevel.Set(slog.LevelInfo)
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: logLevel,
}))
slog.SetDefault(logger)
cfg, err := loadConfig()
if err != nil {
slog.Error("Unable to load config", slog.Any("error", err))
os.Exit(1)
}
var parsedLevel slog.Level
// UnmarshalText handles string inputs like "DEBUG", "info", "Warn", "ERROR" case-insensitively
if err := parsedLevel.UnmarshalText([]byte(cfg.LogLevel)); err != nil {
slog.Error("Invalid log level provided, falling back to INFO", slog.String("invalid_level", cfg.LogLevel), slog.Any("error", err))
parsedLevel = slog.LevelInfo
}
logLevel.Set(parsedLevel)
cfgBytes, err := json.Marshal(cfg)
if err != nil {
slog.Error("Unable to marshal config", slog.Any("error", err))
}
slog.Debug("Application starting with config", slog.Any("config", string(cfgBytes)))
if cfg.Version {
fmt.Println(Version)
os.Exit(0)
}
prometheus.MustRegister(securityUpdates)
prometheus.MustRegister(totalUpdates)
prometheus.MustRegister(rebootRequired)
prometheus.MustRegister(latestCacheUpdate)
distro := getDistro()
if distro == nil {
slog.Error("Distro not detected")
os.Exit(1)
}
go func() {
slog.Debug("Initialized go routine")
for {
updateMetrics(distro)
slog.Debug("Sleeping", slog.Int("interval", cfg.Interval))
time.Sleep(time.Duration(cfg.Interval) * time.Second)
}
}()
http.Handle("/metrics", promhttp.Handler())
addr := fmt.Sprintf(":%d", cfg.Port)
slog.Info("Starting HTTP server", slog.String("addr", addr), slog.Int("interval", cfg.Interval))
if err := http.ListenAndServe(addr, nil); err != nil {
slog.Error("HTTP server collapsed", slog.Any("error", err))
os.Exit(1)
}
slog.Info("HTTP server stopped gracefully")
}
func loadConfig() (*Config, error) {
pflag.IntP("port", "p", DEFAULT_PORT, "HTTP port")
pflag.IntP("interval", "i", DEFAULT_INTERVAL, "Metrics refresh interval (seconds)")
pflag.BoolP("version", "v", false, "Print version")
pflag.StringP("log-level", "l", "info", "Log verbosity level (debug, info, warn, error)")
pflag.StringP("config", "c", "", "Config file")
pflag.Parse()
if err := viper.BindPFlags(pflag.CommandLine); err != nil {
return nil, fmt.Errorf("unable to bind flags: %w", err)
}
// Environment variable matching setup
viper.SetEnvPrefix("UPDATES_EXPORTER")
viper.AutomaticEnv()
// Critical: Converts dashes in flags ("log-level") to underscores for ENVs ("LOG_LEVEL")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
configFlag := viper.GetString("config")
if configFlag != "" {
slog.Info("Loading configuration from explicit config flag", slog.String("path", configFlag))
viper.SetConfigFile(configFlag)
} else {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".") // Look for the file in the current working directory
viper.AddConfigPath("/etc/updates_exporter/")
}
if err := viper.ReadInConfig(); err != nil {
// It is acceptable if the config file is missing; we fall back to flags/defaults.
// But if it exists and has a syntax error, we want to fail fast.
var configFileNotFoundError viper.ConfigFileNotFoundError
if !errors.As(err, &configFileNotFoundError) {
return nil, fmt.Errorf("error reading config file: %w", err)
}
}
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("unable to decode into struct: %w", err)
}
return &cfg, nil
}