| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "os/exec" |
| 10 | "reflect" |
| 11 | "regexp" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | |
| 16 | "github.com/prometheus/client_golang/prometheus" |
| 17 | ) |
| 18 | |
| 19 | const ( |
| 20 | vbeReload = "VBE.reload_" |
| 21 | ) |
| 22 | |
| 23 | var ( |
| 24 | DescCache = &descCache{ |
| 25 | descs: make(map[string]*prometheus.Desc), |
| 26 | } |
| 27 | ) |
| 28 | |
| 29 | type descCache struct { |
| 30 | sync.RWMutex |
| 31 | |
| 32 | descs map[string]*prometheus.Desc |
| 33 | } |
| 34 | |
| 35 | func (dc *descCache) Desc(key string) *prometheus.Desc { |
| 36 | dc.RLock() |
| 37 | desc := dc.descs[key] |
| 38 | dc.RUnlock() |
| 39 | return desc |
| 40 | } |
| 41 | |
| 42 | func (dc *descCache) Set(key string, desc *prometheus.Desc) *prometheus.Desc { |
| 43 | dc.Lock() |
| 44 | dc.descs[key] = desc |
| 45 | dc.Unlock() |
| 46 | return desc |
| 47 | } |
| 48 | |
| 49 | func ScrapeVarnish(ch chan<- prometheus.Metric) ([]byte, error) { |
| 50 | params := []string{"-j"} |
| 51 | if VarnishVersion.EqualsOrGreater(4, 1) { |
| 52 | // 4.1 started to support timeout to exit immediately on connection errors. |
| 53 | // Before that varnishstat exits immediately on faulty params or connection errors. |
| 54 | params = append(params, "-t", "0") |
| 55 | } |
| 56 | if !StartParams.Params.isEmpty() { |
| 57 | params = append(params, StartParams.Params.make()...) |
| 58 | } |
| 59 | buf, errExec := executeVarnishstat(StartParams.VarnishstatExe, params...) |
| 60 | if errExec != nil { |
| 61 | return buf.Bytes(), fmt.Errorf("%s scrape failed: %s", StartParams.VarnishstatExe, errExec) |
| 62 | } |
| 63 | return ScrapeVarnishFrom(buf.Bytes(), ch) |
| 64 | } |
| 65 | |
| 66 | func ScrapeVarnishFrom(buf []byte, ch chan<- prometheus.Metric) ([]byte, error) { |
| 67 | // The output JSON annoyingly is not structured so that we could make a nice map[string]struct for it. |
| 68 | metricsJSON := make(map[string]any) |
| 69 | dec := json.NewDecoder(bytes.NewBuffer(buf)) |
| 70 | dec.UseNumber() |
| 71 | if err := dec.Decode(&metricsJSON); err != nil { |
| 72 | return buf, err |
| 73 | } |
| 74 | |
| 75 | countersJSON := make(map[string]any) |
| 76 | // From Varnish 6.5 https://varnish-cache.org/docs/6.5/whats-new/upgrading-6.5.html#varnishstat |
| 77 | if metricsJSON["version"] != nil { |
| 78 | version_raw, ok := metricsJSON["version"].(json.Number) |
| 79 | if !ok { |
| 80 | return nil, fmt.Errorf("Unhandled json stats version type: %T %#v", metricsJSON["version"], metricsJSON["version"]) |
| 81 | } |
| 82 | version, err := version_raw.Int64() |
| 83 | if err != nil { |
| 84 | return nil, fmt.Errorf("Unhandled json stats version type: %s", err) |
| 85 | } |
| 86 | switch version { |
| 87 | case 1: |
| 88 | countersJSON = metricsJSON["counters"].(map[string]any) |
| 89 | default: |
| 90 | return nil, fmt.Errorf("Unimplemented json stats version %d", version) |
| 91 | } |
| 92 | } else { |
| 93 | countersJSON = metricsJSON |
| 94 | } |
| 95 | |
| 96 | mostRecentVbeReloadPrefix := findMostRecentVbeReloadPrefix(countersJSON) |
| 97 | |
| 98 | for vName, raw := range countersJSON { |
| 99 | |
| 100 | if isOutdatedVbe(vName, mostRecentVbeReloadPrefix) { |
| 101 | continue |
| 102 | } |
| 103 | if vName == "timestamp" { |
| 104 | continue |
| 105 | } |
| 106 | if dt := reflect.TypeOf(raw); dt.Kind() != reflect.Map { |
| 107 | slog.Warn("Found unexpected data from json", "name", vName, "raw", raw) |
| 108 | continue |
| 109 | } |
| 110 | data, ok := raw.(map[string]any) |
| 111 | if !ok { |
| 112 | slog.Warn("Failed to cast to map[string]any", "name", vName, "raw", raw) |
| 113 | continue |
| 114 | } |
| 115 | var ( |
| 116 | vGroup = prometheusGroup(vName) |
| 117 | vDescription string |
| 118 | vIdentifier string |
| 119 | vValue float64 |
| 120 | iValue uint64 |
| 121 | vErr error |
| 122 | ) |
| 123 | flag, _ := stringProperty(data, "flag") |
| 124 | |
| 125 | if value, ok := data["description"]; ok { |
| 126 | if vDescription, ok = value.(string); !ok { |
| 127 | vErr = fmt.Errorf("%s description it not a string", vName) |
| 128 | } |
| 129 | } |
| 130 | if value, ok := data["ident"]; ok && vErr == nil { |
| 131 | if vIdentifier, ok = value.(string); !ok { |
| 132 | vErr = fmt.Errorf("%s ident it not a string", vName) |
| 133 | } |
| 134 | } |
| 135 | if value, ok := data["value"]; ok && vErr == nil { |
| 136 | if number, ok := value.(json.Number); ok { |
| 137 | if vValue, vErr = number.Float64(); vErr != nil { |
| 138 | vErr = fmt.Errorf("%s value float64 error: %s", vName, vErr) |
| 139 | } |
| 140 | if flag == "b" { |
| 141 | if iValue, vErr = strconv.ParseUint(number.String(), 10, 64); vErr != nil { |
| 142 | vErr = fmt.Errorf("%s value uint64 error: %s", vName, vErr) |
| 143 | } |
| 144 | } |
| 145 | } else { |
| 146 | vErr = fmt.Errorf("%s value it not a float64", vName) |
| 147 | } |
| 148 | } |
| 149 | if vErr != nil { |
| 150 | slog.Warn(vErr.Error()) |
| 151 | continue |
| 152 | } |
| 153 | |
| 154 | pName, pDescription, pLabelKeys, pLabelValues := computePrometheusInfo(vName, vGroup, vIdentifier, vDescription) |
| 155 | |
| 156 | descKey := pName + "_" + strings.Join(pLabelKeys, "_") |
| 157 | pDesc := DescCache.Desc(descKey) |
| 158 | if pDesc == nil { |
| 159 | pDesc = DescCache.Set(descKey, prometheus.NewDesc( |
| 160 | pName, |
| 161 | pDescription, |
| 162 | pLabelKeys, |
| 163 | nil, |
| 164 | )) |
| 165 | } |
| 166 | |
| 167 | var metricType prometheus.ValueType |
| 168 | switch flag { |
| 169 | case "c", "a": |
| 170 | metricType = prometheus.CounterValue |
| 171 | case "g": |
| 172 | metricType = prometheus.GaugeValue |
| 173 | default: |
| 174 | metricType = prometheus.GaugeValue |
| 175 | } |
| 176 | |
| 177 | ch <- prometheus.MustNewConstMetric(pDesc, metricType, vValue, pLabelValues...) |
| 178 | |
| 179 | // augment varnish_backend_up from _happy varnish bitmap value |
| 180 | // we are only interested in the latest happy value (up or down) on each scrape |
| 181 | // see draw_line_bitmap function from https://github.com/varnishcache/varnish-cache/blob/master/bin/varnishstat/varnishstat_curses.c |
| 182 | if pName == "varnish_backend_happy" { |
| 183 | upName := "varnish_backend_up" |
| 184 | upDesc := "Backend up as per the latest health probe" |
| 185 | upValue := 0.0 |
| 186 | if iValue > 0 && (iValue&uint64(1)) > 0 { |
| 187 | upValue = 1.0 |
| 188 | } |
| 189 | |
| 190 | descKey = upName + "_" + strings.Join(pLabelKeys, "_") |
| 191 | pDesc = DescCache.Desc(descKey) |
| 192 | if pDesc == nil { |
| 193 | pDesc = DescCache.Set(descKey, prometheus.NewDesc( |
| 194 | upName, |
| 195 | upDesc, |
| 196 | pLabelKeys, |
| 197 | nil, |
| 198 | )) |
| 199 | } |
| 200 | ch <- prometheus.MustNewConstMetric(pDesc, prometheus.GaugeValue, upValue, pLabelValues...) |
| 201 | } |
| 202 | } |
| 203 | return buf, nil |
| 204 | } |
| 205 | |
| 206 | // Returns the result of 'varnishtat' with optional command line params. |
| 207 | func executeVarnishstat(varnishstatExe string, params ...string) (*bytes.Buffer, error) { |
| 208 | buf := &bytes.Buffer{} |
| 209 | var cmd *exec.Cmd |
| 210 | if len(StartParams.VarnishDockerContainer) == 0 { |
| 211 | cmd = exec.Command(varnishstatExe, params...) |
| 212 | } else { |
| 213 | cmd = exec.Command("docker", append([]string{"exec", "-t", StartParams.VarnishDockerContainer, varnishstatExe}, params...)...) |
| 214 | } |
| 215 | cmd.Stdout = buf |
| 216 | cmd.Stderr = buf |
| 217 | return buf, cmd.Run() |
| 218 | } |
| 219 | |
| 220 | // Returns the most recent prefix for 'VBE.reload_' stats. Empty until first reload. |
| 221 | // 'VBE.reload_2019-08-29T100458' as by varnish_reload_vcl in 4.1+ |
| 222 | // 'VBE.reload_20191014_091124_78599' as by varnishreload in 6+ |
| 223 | func findMostRecentVbeReloadPrefix(countersJSON map[string]any) string { |
| 224 | var mostRecentVbeReloadPrefix string |
| 225 | for vName := range countersJSON { |
| 226 | // Checking only the required ".happy" stat |
| 227 | if strings.HasPrefix(vName, vbeReload) && strings.HasSuffix(vName, ".happy") { |
| 228 | dotAfterPrefixIndex := len(vbeReload) + strings.Index(vName[len(vbeReload):], ".") |
| 229 | vbeReloadPrefix := vName[:dotAfterPrefixIndex] |
| 230 | if strings.Compare(vbeReloadPrefix, mostRecentVbeReloadPrefix) > 0 { |
| 231 | mostRecentVbeReloadPrefix = vbeReloadPrefix |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | return mostRecentVbeReloadPrefix |
| 236 | } |
| 237 | |
| 238 | // Returns true if the given 'VBE.' statistic refers to an outdated VCL version |
| 239 | func isOutdatedVbe(vName string, mostRecentVbeReloadPrefix string) bool { |
| 240 | return len(mostRecentVbeReloadPrefix) > 0 && |
| 241 | strings.HasPrefix(vName, "VBE.") && |
| 242 | !strings.HasPrefix(vName, mostRecentVbeReloadPrefix) |
| 243 | } |
| 244 | |
| 245 | // varnishVersion |
| 246 | |
| 247 | type varnishVersion struct { |
| 248 | Major int |
| 249 | Minor int |
| 250 | Patch int |
| 251 | Revision string |
| 252 | } |
| 253 | |
| 254 | func NewVarnishVersion() *varnishVersion { |
| 255 | return &varnishVersion{ |
| 256 | Major: -1, Minor: -1, Patch: -1, |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | func (v *varnishVersion) EqualsOrGreater(major, minor int) bool { |
| 261 | if v.Major > major { |
| 262 | return true |
| 263 | } else if v.Major == major && v.Minor >= minor { |
| 264 | return true |
| 265 | } |
| 266 | return false |
| 267 | } |
| 268 | |
| 269 | func (v *varnishVersion) Valid() bool { |
| 270 | return v.Major != -1 |
| 271 | } |
| 272 | |
| 273 | func (v *varnishVersion) Initialize() error { |
| 274 | return v.queryVersion() |
| 275 | } |
| 276 | |
| 277 | func (v *varnishVersion) queryVersion() error { |
| 278 | buf, err := executeVarnishstat(StartParams.VarnishstatExe, "-V") |
| 279 | if err != nil { |
| 280 | return err |
| 281 | } |
| 282 | if scanner := bufio.NewScanner(buf); scanner.Scan() { |
| 283 | return v.parseVersion(scanner.Text()) |
| 284 | } |
| 285 | return fmt.Errorf("Failed to get varnishstat -V output") |
| 286 | } |
| 287 | |
| 288 | func (v *varnishVersion) parseVersion(version string) error { |
| 289 | r := regexp.MustCompile(`(?P<major>\d+)(\.(?P<minor>\d+))?(\.(?P<patch>\d+))?(.*revision\s(?P<revision>[0-9a-f]*)\))?`) |
| 290 | match := r.FindStringSubmatch(version) |
| 291 | |
| 292 | parts := make(map[string]string) |
| 293 | for i, name := range r.SubexpNames() { |
| 294 | if i != 0 && name != "" { |
| 295 | parts[name] = match[i] |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | if len(parts) > 1 { |
| 300 | if err := v.set(parts); err != nil { |
| 301 | return err |
| 302 | } |
| 303 | } |
| 304 | if !v.Valid() { |
| 305 | return fmt.Errorf("Failed to resolve version from %q", version) |
| 306 | } |
| 307 | return nil |
| 308 | } |
| 309 | |
| 310 | func (v *varnishVersion) Labels() map[string]string { |
| 311 | labels := make(map[string]string) |
| 312 | if v.Major != -1 { |
| 313 | labels["major"] = strconv.Itoa(v.Major) |
| 314 | } |
| 315 | if v.Minor != -1 { |
| 316 | labels["minor"] = strconv.Itoa(v.Minor) |
| 317 | } |
| 318 | if v.Patch != -1 { |
| 319 | labels["patch"] = strconv.Itoa(v.Patch) |
| 320 | } |
| 321 | if v.Revision != "" { |
| 322 | labels["revision"] = v.Revision |
| 323 | } |
| 324 | labels["version"] = v.VersionString() |
| 325 | return labels |
| 326 | } |
| 327 | |
| 328 | func (v *varnishVersion) set(parts map[string]string) error { |
| 329 | for name, value := range parts { |
| 330 | // skip empty value |
| 331 | if len(value) == 0 { |
| 332 | continue |
| 333 | } |
| 334 | |
| 335 | // save revision as-is (string) |
| 336 | if name == "revision" { |
| 337 | v.Revision = value |
| 338 | continue |
| 339 | } |
| 340 | |
| 341 | // convert semver parts to integer and save it |
| 342 | num, err := strconv.Atoi(value) |
| 343 | if err != nil { |
| 344 | return err |
| 345 | } |
| 346 | switch name { |
| 347 | case "major": |
| 348 | v.Major = num |
| 349 | case "minor": |
| 350 | v.Minor = num |
| 351 | case "patch": |
| 352 | v.Patch = num |
| 353 | } |
| 354 | } |
| 355 | return nil |
| 356 | } |
| 357 | |
| 358 | // Version string with numbers only, no revision. |
| 359 | func (v *varnishVersion) VersionString() string { |
| 360 | parts := []string{} |
| 361 | for _, num := range []int{v.Major, v.Minor, v.Patch} { |
| 362 | if num != -1 { |
| 363 | parts = append(parts, strconv.Itoa(num)) |
| 364 | } |
| 365 | } |
| 366 | return strings.Join(parts, ".") |
| 367 | } |
| 368 | |
| 369 | // Full version string, including revision. |
| 370 | func (v *varnishVersion) String() string { |
| 371 | version := v.VersionString() |
| 372 | if v.Revision != "" { |
| 373 | version += " " + v.Revision |
| 374 | } |
| 375 | return version |
| 376 | } |