| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/prometheus/client_golang/prometheus" |
| 13 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 14 | ) |
| 15 | |
| 16 | var ( |
| 17 | ApplicationName = "prometheus_varnish_exporter" |
| 18 | Version string |
| 19 | VersionHash string |
| 20 | VersionDate string |
| 21 | |
| 22 | PrometheusExporter = NewPrometheusExporter() |
| 23 | VarnishVersion = NewVarnishVersion() |
| 24 | ExitHandler = &exitHandler{} |
| 25 | |
| 26 | StartParams = &startParams{ |
| 27 | ListenAddress: ":9131", // Reserved and publicly announced at https://github.com/prometheus/prometheus/wiki/Default-port-allocations |
| 28 | Path: "/metrics", |
| 29 | VarnishstatExe: "varnishstat", |
| 30 | Params: &varnishstatParams{}, |
| 31 | LogLevel: "info", |
| 32 | } |
| 33 | ) |
| 34 | |
| 35 | type startParams struct { |
| 36 | ListenAddress string |
| 37 | Path string |
| 38 | HealthPath string |
| 39 | VarnishstatExe string |
| 40 | VarnishDockerContainer string |
| 41 | Params *varnishstatParams |
| 42 | |
| 43 | Verbose bool // deprecated |
| 44 | ExitOnErrors bool |
| 45 | Test bool |
| 46 | Raw bool // deprecated |
| 47 | WithGoMetrics bool |
| 48 | |
| 49 | // logging |
| 50 | LogLevel string |
| 51 | LogJSON bool |
| 52 | |
| 53 | noExit bool // deprecated |
| 54 | } |
| 55 | |
| 56 | type varnishstatParams struct { |
| 57 | Instance string |
| 58 | VSM string |
| 59 | } |
| 60 | |
| 61 | func (p *varnishstatParams) isEmpty() bool { |
| 62 | return p.Instance == "" && p.VSM == "" |
| 63 | } |
| 64 | |
| 65 | func (p *varnishstatParams) make() (params []string) { |
| 66 | // -n |
| 67 | if p.Instance != "" { |
| 68 | params = append(params, "-n", p.Instance) |
| 69 | } |
| 70 | // -N is not supported by 3.x |
| 71 | if p.VSM != "" && VarnishVersion.EqualsOrGreater(4, 0) { |
| 72 | params = append(params, "-N", p.VSM) |
| 73 | } |
| 74 | return params |
| 75 | } |
| 76 | |
| 77 | func main() { |
| 78 | // prometheus conventions |
| 79 | flag.StringVar(&StartParams.ListenAddress, "web.listen-address", StartParams.ListenAddress, "Address on which to expose metrics and web interface.") |
| 80 | flag.StringVar(&StartParams.Path, "web.telemetry-path", StartParams.Path, "Path under which to expose metrics.") |
| 81 | flag.StringVar(&StartParams.HealthPath, "web.health-path", StartParams.HealthPath, "Path under which to expose healthcheck. Disabled unless configured.") |
| 82 | |
| 83 | // varnish |
| 84 | flag.StringVar(&StartParams.VarnishstatExe, "varnishstat-path", StartParams.VarnishstatExe, "Path to varnishstat.") |
| 85 | flag.StringVar(&StartParams.Params.Instance, "n", StartParams.Params.Instance, "varnishstat -n value.") |
| 86 | flag.StringVar(&StartParams.Params.VSM, "N", StartParams.Params.VSM, "varnishstat -N value.") |
| 87 | |
| 88 | // docker |
| 89 | flag.StringVar(&StartParams.VarnishDockerContainer, "docker-container-name", StartParams.VarnishDockerContainer, "Docker container name to exec varnishstat in.") |
| 90 | |
| 91 | // logging |
| 92 | flag.StringVar(&StartParams.LogLevel, "log-level", StartParams.LogLevel, "Log level: debug, info, warn, error") |
| 93 | flag.BoolVar(&StartParams.LogJSON, "log-json", StartParams.LogJSON, "Log in JSON format") |
| 94 | |
| 95 | // modes |
| 96 | version := false |
| 97 | flag.BoolVar(&version, "version", version, "Print version and exit") |
| 98 | flag.BoolVar(&StartParams.ExitOnErrors, "exit-on-errors", StartParams.ExitOnErrors, "Exit process on scrape errors.") |
| 99 | flag.BoolVar(&StartParams.Test, "test", StartParams.Test, "Test varnishstat availability, prints available metrics and exits.") |
| 100 | flag.BoolVar(&StartParams.WithGoMetrics, "with-go-metrics", StartParams.WithGoMetrics, "Export go runtime and http handler metrics") |
| 101 | |
| 102 | // deprecated |
| 103 | flag.BoolVar(&StartParams.Raw, "raw", StartParams.Test, "Deprecated: Raw stdout logging without timestamps.") |
| 104 | flag.BoolVar(&StartParams.Verbose, "verbose", StartParams.Verbose, "Deprecated: Verbose logging.") |
| 105 | flag.BoolVar(&StartParams.noExit, "no-exit", StartParams.noExit, "Deprecated: see -exit-on-errors") |
| 106 | |
| 107 | flag.Parse() |
| 108 | |
| 109 | if version { |
| 110 | fmt.Printf("%s %s\n", ApplicationName, getVersion(true)) |
| 111 | os.Exit(0) |
| 112 | } |
| 113 | |
| 114 | if StartParams.Verbose || StartParams.Raw { |
| 115 | slog.Warn("-verbose and -raw are deprecated and have no effect. These flags will be removed in a future release. Use -log-level=debug and -log-json=false instead.") |
| 116 | } |
| 117 | |
| 118 | initSlogger(StartParams.LogLevel, StartParams.LogJSON) |
| 119 | |
| 120 | if len(StartParams.Path) == 0 || StartParams.Path[0] != '/' { |
| 121 | logFatal("-web.telemetry-path cannot be empty and must start with a slash '/'", "path", StartParams.Path) |
| 122 | } |
| 123 | if len(StartParams.HealthPath) != 0 && StartParams.HealthPath[0] != '/' { |
| 124 | logFatal("-web.health-path must start with a slash '/' if configured", "path", StartParams.HealthPath) |
| 125 | } |
| 126 | if StartParams.Path == StartParams.HealthPath { |
| 127 | logFatal("-web.telemetry-path and -web.health-path cannot have same value") |
| 128 | } |
| 129 | |
| 130 | // Don't log warning on !noExit as that would spam for the formed default value. |
| 131 | if StartParams.noExit { |
| 132 | slog.Warn("-no-exit is deprecated. As of v1.5 it is the default behavior not to exit process on scrape errors. You can remove this parameter.") |
| 133 | } |
| 134 | |
| 135 | // Test run or user explicitly wants to exit on any scrape errors during runtime. |
| 136 | ExitHandler.exitOnError = StartParams.Test == true || StartParams.ExitOnErrors == true |
| 137 | |
| 138 | slog.Info("Initializing application", "applicationName", ApplicationName, "applicationVersion", getVersion(false), "parameters", StartParams) |
| 139 | |
| 140 | // Initialize |
| 141 | if err := VarnishVersion.Initialize(); err != nil { |
| 142 | ExitHandler.Errorf("Varnish version initialize failed: %s", err.Error()) |
| 143 | } |
| 144 | if VarnishVersion.Valid() { |
| 145 | slog.Info("Found varnishstat.", "varnishVersion", VarnishVersion) |
| 146 | if err := PrometheusExporter.Initialize(); err != nil { |
| 147 | logFatal("Prometheus exporter initialize failed", "error", err.Error()) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | // Test to verify everything is ok before starting the server |
| 152 | { |
| 153 | done := make(chan bool) |
| 154 | metrics := make(chan prometheus.Metric) |
| 155 | go func() { |
| 156 | for m := range metrics { |
| 157 | if StartParams.Test { |
| 158 | slog.Info(m.Desc().String()) |
| 159 | } |
| 160 | } |
| 161 | done <- true |
| 162 | }() |
| 163 | tStart := time.Now() |
| 164 | buf, err := ScrapeVarnish(metrics) |
| 165 | close(metrics) |
| 166 | <-done |
| 167 | |
| 168 | if err == nil { |
| 169 | slog.Info("Test scrape done", "duration", time.Since(tStart)) |
| 170 | } else { |
| 171 | if len(buf) > 0 { |
| 172 | slog.Debug("Scrape output", "output", string(buf)) |
| 173 | } |
| 174 | ExitHandler.Errorf("Startup test: %s", err.Error()) |
| 175 | } |
| 176 | } |
| 177 | if StartParams.Test { |
| 178 | return |
| 179 | } |
| 180 | |
| 181 | // Start serving |
| 182 | slog.Info("Server starting", "listenAddress", StartParams.ListenAddress, "metricsPath", StartParams.Path) |
| 183 | |
| 184 | if !StartParams.WithGoMetrics { |
| 185 | registry := prometheus.NewRegistry() |
| 186 | if err := registry.Register(PrometheusExporter); err != nil { |
| 187 | logFatal("registry.Register failed: %s", err.Error()) |
| 188 | } |
| 189 | handler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{ |
| 190 | ErrorLog: &SlogErrorLogger{slog.Default()}, |
| 191 | }) |
| 192 | http.Handle(StartParams.Path, handler) |
| 193 | } else { |
| 194 | prometheus.MustRegister(PrometheusExporter) |
| 195 | http.Handle(StartParams.Path, promhttp.Handler()) |
| 196 | } |
| 197 | |
| 198 | if StartParams.Path != "/" { |
| 199 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 200 | w.Write([]byte(`<html> |
| 201 | <head><title>Varnish Exporter</title></head> |
| 202 | <body> |
| 203 | <h1>Varnish Exporter</h1> |
| 204 | <p><a href="` + StartParams.Path + `">Metrics</a></p> |
| 205 | </body> |
| 206 | </html>`)) |
| 207 | }) |
| 208 | } |
| 209 | if StartParams.HealthPath != "" { |
| 210 | http.HandleFunc(StartParams.HealthPath, func(w http.ResponseWriter, r *http.Request) { |
| 211 | // As noted in the "up" metric, needs some way to determine if everything is actually Ok. |
| 212 | // For now, this just lets us check that we're accepting connections |
| 213 | w.WriteHeader(http.StatusOK) |
| 214 | fmt.Fprintln(w, "Ok") |
| 215 | }) |
| 216 | } |
| 217 | logFatalError(http.ListenAndServe(StartParams.ListenAddress, nil)) |
| 218 | } |
| 219 | |
| 220 | type exitHandler struct { |
| 221 | sync.RWMutex |
| 222 | exitOnError bool |
| 223 | err error |
| 224 | } |
| 225 | |
| 226 | func (ex *exitHandler) Errorf(format string, a ...any) error { |
| 227 | return ex.Set(fmt.Errorf(format, a...)) |
| 228 | } |
| 229 | |
| 230 | func (ex *exitHandler) HasError() bool { |
| 231 | ex.RLock() |
| 232 | hasError := ex.err != nil |
| 233 | ex.RUnlock() |
| 234 | return hasError |
| 235 | } |
| 236 | |
| 237 | func (ex *exitHandler) Set(err error) error { |
| 238 | ex.Lock() |
| 239 | defer ex.Unlock() |
| 240 | |
| 241 | if err == nil { |
| 242 | ex.err = nil |
| 243 | return nil |
| 244 | } |
| 245 | |
| 246 | errDiffers := ex.err == nil || ex.err.Error() != err.Error() |
| 247 | ex.err = err |
| 248 | |
| 249 | if ex.exitOnError { |
| 250 | logFatal("%s", err.Error()) |
| 251 | } else if errDiffers { |
| 252 | slog.Error(err.Error()) |
| 253 | } |
| 254 | return err |
| 255 | } |
| 256 | |
| 257 | func getVersion(date bool) (version string) { |
| 258 | if Version == "" { |
| 259 | return "dev" |
| 260 | } |
| 261 | version = fmt.Sprintf("v%s (%s)", Version, VersionHash) |
| 262 | if date { |
| 263 | version += " " + VersionDate |
| 264 | } |
| 265 | return version |
| 266 | } |