-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
telemetry_ingress_client.go
223 lines (187 loc) · 6.06 KB
/
telemetry_ingress_client.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package synchronization
import (
"context"
"errors"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/smartcontractkit/wsrpc"
"github.com/smartcontractkit/wsrpc/examples/simple/keys"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services"
"github.com/smartcontractkit/chainlink/v2/core/services/keystore"
telemPb "github.com/smartcontractkit/chainlink/v2/core/services/synchronization/telem"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)
//go:generate mockery --quiet --dir ./telem --name TelemClient --output ./mocks/ --case=underscore
//go:generate mockery --quiet --name TelemetryIngressClient --output ./mocks --case=underscore
// TelemetryIngressClient encapsulates all the functionality needed to
// send telemetry to the ingress server using wsrpc
type TelemetryIngressClient interface {
services.ServiceCtx
Send(TelemPayload)
}
type NoopTelemetryIngressClient struct{}
// Start is a no-op
func (NoopTelemetryIngressClient) Start(context.Context) error { return nil }
// Close is a no-op
func (NoopTelemetryIngressClient) Close() error { return nil }
// Send is a no-op
func (NoopTelemetryIngressClient) Send(TelemPayload) {}
func (NoopTelemetryIngressClient) HealthReport() map[string]error { return map[string]error{} }
func (NoopTelemetryIngressClient) Name() string { return "NoopTelemetryIngressClient" }
// Ready is a no-op
func (NoopTelemetryIngressClient) Ready() error { return nil }
type telemetryIngressClient struct {
utils.StartStopOnce
url *url.URL
ks keystore.CSA
serverPubKeyHex string
telemClient telemPb.TelemClient
logging bool
lggr logger.Logger
wgDone sync.WaitGroup
chDone chan struct{}
dropMessageCount atomic.Uint32
chTelemetry chan TelemPayload
}
type TelemPayload struct {
Ctx context.Context
Telemetry []byte
TelemType TelemetryType
ContractID string
}
// NewTelemetryIngressClient returns a client backed by wsrpc that
// can send telemetry to the telemetry ingress server
func NewTelemetryIngressClient(url *url.URL, serverPubKeyHex string, ks keystore.CSA, logging bool, lggr logger.Logger, telemBufferSize uint) TelemetryIngressClient {
return &telemetryIngressClient{
url: url,
ks: ks,
serverPubKeyHex: serverPubKeyHex,
logging: logging,
lggr: lggr.Named("TelemetryIngressClient"),
chTelemetry: make(chan TelemPayload, telemBufferSize),
chDone: make(chan struct{}),
}
}
// Start connects the wsrpc client to the telemetry ingress server
func (tc *telemetryIngressClient) Start(ctx context.Context) error {
return tc.StartOnce("TelemetryIngressClient", func() error {
privkey, err := tc.getCSAPrivateKey()
if err != nil {
return err
}
tc.connect(ctx, privkey)
return nil
})
}
// Close disconnects the wsrpc client from the ingress server
func (tc *telemetryIngressClient) Close() error {
return tc.StopOnce("TelemetryIngressClient", func() error {
close(tc.chDone)
tc.wgDone.Wait()
return nil
})
}
func (tc *telemetryIngressClient) Name() string {
return tc.lggr.Name()
}
func (tc *telemetryIngressClient) HealthReport() map[string]error {
return map[string]error{tc.Name(): tc.StartStopOnce.Healthy()}
}
func (tc *telemetryIngressClient) connect(ctx context.Context, clientPrivKey []byte) {
tc.wgDone.Add(1)
go func() {
defer tc.wgDone.Done()
serverPubKey := keys.FromHex(tc.serverPubKeyHex)
conn, err := wsrpc.DialWithContext(ctx, tc.url.String(), wsrpc.WithTransportCreds(clientPrivKey, serverPubKey), wsrpc.WithLogger(tc.lggr))
if err != nil {
if ctx.Err() != nil {
tc.lggr.Warnw("gave up connecting to telemetry endpoint", "err", err)
} else {
tc.lggr.Criticalw("telemetry endpoint dial errored unexpectedly", "err", err)
tc.SvcErrBuffer.Append(err)
}
}
defer conn.Close()
// Initialize a new wsrpc client caller
// This is used to call RPC methods on the server
if tc.telemClient == nil { // only preset for tests
tc.telemClient = telemPb.NewTelemClient(conn)
}
// Start handler for telemetry
tc.handleTelemetry()
// Wait for close
<-tc.chDone
}()
}
func (tc *telemetryIngressClient) handleTelemetry() {
go func() {
for {
select {
case p := <-tc.chTelemetry:
// Send telemetry to the ingress server, log any errors
telemReq := &telemPb.TelemRequest{
Telemetry: p.Telemetry,
Address: p.ContractID,
TelemetryType: string(p.TelemType),
SentAt: time.Now().UnixNano(),
}
_, err := tc.telemClient.Telem(p.Ctx, telemReq)
if err != nil {
tc.lggr.Errorf("Could not send telemetry: %v", err)
continue
}
if tc.logging {
tc.lggr.Debugw("successfully sent telemetry to ingress server", "contractID", p.ContractID, "telemetry", p.Telemetry)
}
case <-tc.chDone:
return
}
}
}()
}
// logBufferFullWithExpBackoff logs messages at
// 1
// 2
// 4
// 8
// 16
// 32
// 64
// 100
// 200
// 300
// etc...
func (tc *telemetryIngressClient) logBufferFullWithExpBackoff(payload TelemPayload) {
count := tc.dropMessageCount.Add(1)
if count > 0 && (count%100 == 0 || count&(count-1) == 0) {
tc.lggr.Warnw("telemetry ingress client buffer full, dropping message", "telemetry", payload.Telemetry, "droppedCount", count)
}
}
// getCSAPrivateKey gets the client's CSA private key
func (tc *telemetryIngressClient) getCSAPrivateKey() (privkey []byte, err error) {
// Fetch the client's public key
keys, err := tc.ks.GetAll()
if err != nil {
return privkey, err
}
if len(keys) < 1 {
return privkey, errors.New("CSA key does not exist")
}
return keys[0].Raw(), nil
}
// Send sends telemetry to the ingress server using wsrpc if the client is ready.
// Also stores telemetry in a small buffer in case of backpressure from wsrpc,
// throwing away messages once buffer is full
func (tc *telemetryIngressClient) Send(payload TelemPayload) {
select {
case tc.chTelemetry <- payload:
tc.dropMessageCount.Store(0)
case <-payload.Ctx.Done():
return
default:
tc.logBufferFullWithExpBackoff(payload)
}
}