Merge branch '8784-dir-listings'
[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
12 type statsTicker struct {
13         Errors   uint64
14         InBytes  uint64
15         OutBytes uint64
16
17         ErrorCodes map[string]uint64 `json:",omitempty"`
18         lock       sync.Mutex
19 }
20
21 // Tick increments each of the given counters by 1 using
22 // atomic.AddUint64.
23 func (s *statsTicker) Tick(counters ...*uint64) {
24         for _, counter := range counters {
25                 atomic.AddUint64(counter, 1)
26         }
27 }
28
29 // TickErr increments the overall error counter, as well as the
30 // ErrorCodes entry for the given errType. If err is nil, TickErr is a
31 // no-op.
32 func (s *statsTicker) TickErr(err error, errType string) {
33         if err == nil {
34                 return
35         }
36         s.Tick(&s.Errors)
37
38         s.lock.Lock()
39         if s.ErrorCodes == nil {
40                 s.ErrorCodes = make(map[string]uint64)
41         }
42         s.ErrorCodes[errType]++
43         s.lock.Unlock()
44 }
45
46 // TickInBytes increments the incoming byte counter by n.
47 func (s *statsTicker) TickInBytes(n uint64) {
48         atomic.AddUint64(&s.InBytes, n)
49 }
50
51 // TickOutBytes increments the outgoing byte counter by n.
52 func (s *statsTicker) TickOutBytes(n uint64) {
53         atomic.AddUint64(&s.OutBytes, n)
54 }