forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
optional_gatherer.go
57 lines (44 loc) · 1.37 KB
/
optional_gatherer.go
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
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package metrics
import (
"fmt"
"sync"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
)
var _ OptionalGatherer = (*optionalGatherer)(nil)
// OptionalGatherer extends the Gatherer interface by allowing the optional
// registration of a single gatherer. If no gatherer is registered, Gather will
// return no metrics and no error. If a gatherer is registered, Gather will
// return the results of calling Gather on the provided gatherer.
type OptionalGatherer interface {
prometheus.Gatherer
// Register the provided gatherer. If a gatherer was previously registered,
// an error will be returned.
Register(gatherer prometheus.Gatherer) error
}
type optionalGatherer struct {
lock sync.RWMutex
gatherer prometheus.Gatherer
}
func NewOptionalGatherer() OptionalGatherer {
return &optionalGatherer{}
}
func (g *optionalGatherer) Gather() ([]*dto.MetricFamily, error) {
g.lock.RLock()
defer g.lock.RUnlock()
if g.gatherer == nil {
return nil, nil
}
return g.gatherer.Gather()
}
func (g *optionalGatherer) Register(gatherer prometheus.Gatherer) error {
g.lock.Lock()
defer g.lock.Unlock()
if g.gatherer != nil {
return fmt.Errorf("%w; %#v", errReregisterGatherer, g.gatherer)
}
g.gatherer = gatherer
return nil
}