13937: Refactors approach to pass volume metrics as curried vecs (WIP)
[arvados.git] / services / keepstore / stats_ticker.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "sync"
9         "sync/atomic"
10
11         "github.com/prometheus/client_golang/prometheus"
12 )
13
14 type statsTicker struct {
15         Errors   uint64
16         InBytes  uint64
17         OutBytes uint64
18
19         // Prometheus metrics
20         PromErrors     prometheus.Counter
21         PromInBytes    prometheus.Counter
22         PromOutBytes   prometheus.Counter
23         PromErrorCodes *prometheus.CounterVec
24
25         ErrorCodes map[string]uint64 `json:",omitempty"`
26         lock       sync.Mutex
27 }
28
29 // Tick increments each of the given counters by 1 using
30 // atomic.AddUint64.
31 func (s *statsTicker) Tick(counters ...*uint64) {
32         for _, counter := range counters {
33                 atomic.AddUint64(counter, 1)
34         }
35 }
36
37 // TickErr increments the overall error counter, as well as the
38 // ErrorCodes entry for the given errType. If err is nil, TickErr is a
39 // no-op.
40 func (s *statsTicker) TickErr(err error, errType string) {
41         if err == nil {
42                 return
43         }
44         s.PromErrors.Inc()
45         s.Tick(&s.Errors)
46
47         s.lock.Lock()
48         if s.ErrorCodes == nil {
49                 s.ErrorCodes = make(map[string]uint64)
50         }
51         s.ErrorCodes[errType]++
52         s.lock.Unlock()
53         s.PromErrorCodes.WithLabelValues(errType).Inc()
54 }
55
56 // TickInBytes increments the incoming byte counter by n.
57 func (s *statsTicker) TickInBytes(n uint64) {
58         s.PromInBytes.Add(float64(n))
59         atomic.AddUint64(&s.InBytes, n)
60 }
61
62 // TickOutBytes increments the outgoing byte counter by n.
63 func (s *statsTicker) TickOutBytes(n uint64) {
64         s.PromOutBytes.Add(float64(n))
65         atomic.AddUint64(&s.OutBytes, n)
66 }