/
monitor.go
204 lines (168 loc) · 5.25 KB
/
monitor.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package monitoring
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/O1MaGnUmO1/chainlink-common/pkg/logger"
"github.com/O1MaGnUmO1/chainlink-common/pkg/monitoring/config"
"github.com/O1MaGnUmO1/chainlink-common/pkg/utils"
)
// Monitor is the entrypoint for an on-chain monitor integration.
// Monitors should only be created via NewMonitor()
type Monitor struct {
RootContext context.Context
ChainConfig ChainConfig
Config config.Config
Log Logger
Producer Producer
Metrics Metrics
ChainMetrics ChainMetrics
SchemaRegistry SchemaRegistry
SourceFactories []SourceFactory
ExporterFactories []ExporterFactory
RDDSource Source
RDDPoller Poller
Manager Manager
HTTPServer HTTPServer
}
// NewMonitor builds a new Monitor instance using dependency injection.
// If advanced configurations of the Monitor are required - for instance,
// adding a custom third party service to send data to - this method
// should provide a good starting template to do that.
func NewMonitor(
rootCtx context.Context,
log Logger,
chainConfig ChainConfig,
envelopeSourceFactory SourceFactory,
txResultsSourceFactory SourceFactory,
feedsParser FeedsParser,
nodesParser NodesParser,
) (*Monitor, error) {
cfg, err := config.Parse()
if err != nil {
return nil, fmt.Errorf("failed to parse generic configuration: %w", err)
}
metrics := NewMetrics(logger.With(log, "component", "metrics"))
chainMetrics := NewChainMetrics(chainConfig)
sourceFactories := []SourceFactory{envelopeSourceFactory, txResultsSourceFactory}
producer, err := NewProducer(rootCtx, logger.With(log, "component", "producer"), cfg.Kafka)
if err != nil {
return nil, fmt.Errorf("failed to create kafka producer: %w", err)
}
producer = NewInstrumentedProducer(producer, chainMetrics)
schemaRegistry := NewSchemaRegistry(cfg.SchemaRegistry, log)
transmissionSchema, err := schemaRegistry.EnsureSchema(
SubjectFromTopic(cfg.Kafka.TransmissionTopic), TransmissionAvroSchema)
if err != nil {
return nil, fmt.Errorf("failed to prepare transmission schema: %w", err)
}
configSetSimplifiedSchema, err := schemaRegistry.EnsureSchema(
SubjectFromTopic(cfg.Kafka.ConfigSetSimplifiedTopic), ConfigSetSimplifiedAvroSchema)
if err != nil {
return nil, fmt.Errorf("failed to prepare config_set_simplified schema: %w", err)
}
prometheusExporterFactory := NewPrometheusExporterFactory(
logger.With(log, "component", "prometheus-exporter"),
metrics,
)
kafkaExporterFactory, err := NewKafkaExporterFactory(
logger.With(log, "component", "kafka-exporter"),
producer,
[]Pipeline{
{cfg.Kafka.TransmissionTopic, MakeTransmissionMapping, transmissionSchema},
{cfg.Kafka.ConfigSetSimplifiedTopic, MakeConfigSetSimplifiedMapping, configSetSimplifiedSchema},
},
)
if err != nil {
return nil, fmt.Errorf("failed to create kafka exporter: %w", err)
}
exporterFactories := []ExporterFactory{prometheusExporterFactory, kafkaExporterFactory}
rddSource := NewRDDSource(
cfg.Feeds.URL, feedsParser, cfg.Feeds.IgnoreIDs,
cfg.Nodes.URL, nodesParser,
logger.With(log, "component", "rdd-source"),
)
rddPoller := NewSourcePoller(
rddSource,
logger.With(log, "component", "rdd-poller"),
cfg.Feeds.RDDPollInterval,
cfg.Feeds.RDDReadTimeout,
0, // no buffering!
)
manager := NewManager(
logger.With(log, "component", "manager"),
rddPoller,
)
// Configure HTTP server
httpServer := NewHTTPServer(rootCtx, cfg.HTTP.Address, logger.With(log, "component", "http-server"))
httpServer.Handle("/metrics", metrics.HTTPHandler())
httpServer.Handle("/debug", manager.HTTPHandler())
// Required for k8s.
httpServer.Handle("/health", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
return &Monitor{
rootCtx,
chainConfig,
cfg,
log,
producer,
metrics,
chainMetrics,
schemaRegistry,
sourceFactories,
exporterFactories,
rddSource,
rddPoller,
manager,
httpServer,
}, nil
}
// Run() starts all the goroutines needed by a Monitor. The lifecycle of these routines
// is controlled by the context passed to the NewMonitor constructor.
func (m Monitor) Run() {
rootCtx, cancel := context.WithCancel(m.RootContext)
defer cancel()
var subs utils.Subprocesses
subs.Go(func() {
m.RDDPoller.Run(rootCtx)
})
// Instrument all source factories
instrumentedSourceFactories := []SourceFactory{}
for _, factory := range m.SourceFactories {
instrumentedSourceFactories = append(instrumentedSourceFactories,
NewInstrumentedSourceFactory(factory, m.ChainMetrics))
}
monitor := NewMultiFeedMonitor(
m.ChainConfig,
m.Log,
instrumentedSourceFactories,
m.ExporterFactories,
100, // bufferCapacity for source pollers
)
subs.Go(func() {
m.Manager.Run(rootCtx, func(localCtx context.Context, data RDDData) {
m.ChainMetrics.SetNewFeedConfigsDetected(float64(len(data.Feeds)))
monitor.Run(localCtx, data)
})
})
subs.Go(func() {
m.HTTPServer.Run(rootCtx)
})
// Handle signals from the OS
subs.Go(func() {
osSignalsCh := make(chan os.Signal, 1)
signal.Notify(osSignalsCh, syscall.SIGINT, syscall.SIGTERM)
var sig os.Signal
select {
case sig = <-osSignalsCh:
m.Log.Infow("received signal. Stopping", "signal", sig)
cancel()
case <-rootCtx.Done():
}
})
subs.Wait()
}