-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
loop_registry.go
95 lines (78 loc) · 2.6 KB
/
loop_registry.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package plugins
import (
"errors"
"fmt"
"sort"
"sync"
"github.com/hashicorp/consul/sdk/freeport"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink-common/pkg/loop"
"github.com/smartcontractkit/chainlink/v2/core/config"
)
var ErrExists = errors.New("plugin already registered")
type RegisteredLoop struct {
Name string
EnvCfg loop.EnvConfig
}
// LoopRegistry is responsible for assigning ports to plugins that are to be used for the
// plugin's prometheus HTTP server, and for passing the tracing configuration to the plugin.
type LoopRegistry struct {
mu sync.Mutex
registry map[string]*RegisteredLoop
lggr logger.Logger
cfgTracing config.Tracing
}
func NewLoopRegistry(lggr logger.Logger, tracingConfig config.Tracing) *LoopRegistry {
return &LoopRegistry{
registry: map[string]*RegisteredLoop{},
lggr: logger.Named(lggr, "LoopRegistry"),
cfgTracing: tracingConfig,
}
}
// Register creates a port of the plugin. It is not idempotent. Duplicate calls to Register will return [ErrExists]
// Safe for concurrent use.
func (m *LoopRegistry) Register(id string) (*RegisteredLoop, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, exists := m.registry[id]; exists {
return nil, ErrExists
}
ports, err := freeport.Take(1)
if err != nil {
return nil, fmt.Errorf("failed to get free port: %v", err)
}
if len(ports) != 1 {
return nil, fmt.Errorf("failed to get free port: no ports returned")
}
envCfg := loop.EnvConfig{PrometheusPort: ports[0]}
if m.cfgTracing != nil {
envCfg.TracingEnabled = m.cfgTracing.Enabled()
envCfg.TracingCollectorTarget = m.cfgTracing.CollectorTarget()
envCfg.TracingSamplingRatio = m.cfgTracing.SamplingRatio()
envCfg.TracingTLSCertPath = m.cfgTracing.TLSCertPath()
envCfg.TracingAttributes = m.cfgTracing.Attributes()
}
m.registry[id] = &RegisteredLoop{Name: id, EnvCfg: envCfg}
m.lggr.Debugf("Registered loopp %q with config %v, port %d", id, envCfg, envCfg.PrometheusPort)
return m.registry[id], nil
}
// Return slice sorted by plugin name. Safe for concurrent use.
func (m *LoopRegistry) List() []*RegisteredLoop {
var registeredLoops []*RegisteredLoop
m.mu.Lock()
for _, known := range m.registry {
registeredLoops = append(registeredLoops, known)
}
m.mu.Unlock()
sort.Slice(registeredLoops, func(i, j int) bool {
return registeredLoops[i].Name < registeredLoops[j].Name
})
return registeredLoops
}
// Get plugin by id. Safe for concurrent use.
func (m *LoopRegistry) Get(id string) (*RegisteredLoop, bool) {
m.mu.Lock()
defer m.mu.Unlock()
p, exists := m.registry[id]
return p, exists
}