-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcollectors.py
More file actions
606 lines (509 loc) · 22.6 KB
/
collectors.py
File metadata and controls
606 lines (509 loc) · 22.6 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
"""Module for providing interfaces to interact with https and websocket RPC endpoints."""
from interfaces import WebsocketInterface, HttpsInterface
from helpers import validate_dict_and_return_key_value, strip_url
class EvmCollector():
"""A collector to fetch information about evm compatible RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
sub_payload = {
"method": 'eth_subscribe',
"jsonrpc": "2.0",
"id": chain_id,
"params": ["newHeads"]
}
self.interface = WebsocketInterface(
url, sub_payload, **client_parameters)
self.interface.daemon = True
self.interface.start()
def alive(self):
"""Returns if the websocket subscription is healthy."""
return self.interface.healthy
def block_height(self):
"""Returns latest block height."""
return self.interface.get_message_property_to_hex('number')
def finalized_block_height(self):
"""Runs a query to return finalized block height"""
payload = {
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["finalized", False],
"id": self.chain_id
}
finalized_block = self.interface.query(payload)
if finalized_block is None:
return None
block_number_hex = finalized_block.get('number')
if block_number_hex is None:
return None
return int(block_number_hex, 16)
def heads_received(self):
"""Returns amount of received messages from the subscription."""
return self.interface.heads_received
def disconnects(self):
"""Returns number of disconnects on the subscription."""
return self.interface.disconnects
def latency(self):
"""Returns connection latency."""
return self.interface.subscription_ping_latency
def client_version(self):
"""Runs a cached query to return client version."""
payload = {
"jsonrpc": "2.0",
"method": "web3_clientVersion",
"params": [],
"id": self.chain_id
}
version = self.interface.cached_query(payload)
if version is None:
return None
client_version = {"client_version": version}
return client_version
class ConfluxCollector():
"""A collector to fetch information about conflux RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
sub_payload = {
"method": 'cfx_subscribe',
"jsonrpc": "2.0",
"id": chain_id,
"params": ["newHeads"]
}
self.interface = WebsocketInterface(
url, sub_payload, **client_parameters)
self.interface.daemon = True
self.interface.start()
def alive(self):
"""Returns if the websocket subscription is healthy."""
return self.interface.healthy
def block_height(self):
"""Returns latest block height."""
return self.interface.get_message_property_to_hex('height')
def heads_received(self):
"""Returns amount of received messages from the subscription."""
return self.interface.heads_received
def disconnects(self):
"""Returns number of disconnects on the subscription."""
return self.interface.disconnects
def latency(self):
"""Returns connection latency."""
return self.interface.subscription_ping_latency
def client_version(self):
"""Runs a cached query to return client version."""
payload = {
"jsonrpc": "2.0",
"method": "cfx_clientVersion",
"params": [],
"id": self.chain_id
}
version = self.interface.cached_query(payload)
if version is None:
return None
client_version = {"client_version": version}
return client_version
class CardanoCollector():
"""A collector to fetch information about cardano RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.block_height_payload = {
"id": "exporter",
"jsonrpc": "2.0",
"method": "queryNetwork/blockHeight"
}
self.interface = WebsocketInterface(
url, **client_parameters)
self.interface.daemon = None
def alive(self):
"""Returns true if endpoint is alive, false if not."""
return self.interface.cached_query(self.block_height_payload,
skip_checks=True) is not None
def block_height(self):
"""Returns latest block height."""
return self.interface.cached_query(self.block_height_payload, skip_checks=True)
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class BitcoinCollector():
"""A collector to fetch information about Bitcoin RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'BitcoinCollector',
'url': strip_url(url)
}
self.network_info_payload = {
"jsonrpc": "1.0",
"id": "exporter",
"method": "getnetworkinfo"
}
self.blockchain_info_payload = {
"jsonrpc": "1.0",
"id": "exporter",
"method": "getblockchaininfo",
"params": []
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch client version from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rpc_post(self.network_info_payload) is not None
def block_height(self):
"""Returns latest block height. Cache is cleared when total_difficulty is fetched.
In order for this collector to work, alive and block_height calls need to be
followed with total_difficulty and client_version calls so the cache is cleared."""
blockchain_info = self.interface.cached_json_rpc_post(
self.blockchain_info_payload)
return validate_dict_and_return_key_value(
blockchain_info, 'blocks', self._logger_metadata)
def total_difficulty(self):
"""Gets total difficulty from a previous call and clears the cache."""
blockchain_info = self.interface.cached_json_rpc_post(
self.blockchain_info_payload)
return validate_dict_and_return_key_value(
blockchain_info, 'difficulty', self._logger_metadata)
def client_version(self):
"""Runs a cached query to return client version."""
blockchain_info = self.interface.cached_json_rpc_post(
self.network_info_payload)
version = validate_dict_and_return_key_value(
blockchain_info, 'version', self._logger_metadata, stringify=True)
subversion = validate_dict_and_return_key_value(
blockchain_info, 'subversion', self._logger_metadata, stringify=True)
protocol_version = validate_dict_and_return_key_value(
blockchain_info, 'protocolversion', self._logger_metadata, stringify=True)
if version is None:
return None
client_version = {
"client_version":
f"version:{version} subversion:{subversion} protocolversion:{protocol_version}"}
return client_version
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class FilecoinCollector():
"""A collector to fetch information about filecoin RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'FilecoinCollector',
'url': strip_url(url)
}
self.client_version_payload = {
'jsonrpc': '2.0',
'method': "Filecoin.Version",
'id': 1
}
self.block_height_payload = {
'jsonrpc': '2.0',
'method': "Filecoin.ChainHead",
'id': 1
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch client version from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rpc_post(
self.client_version_payload) is not None
def block_height(self):
"""Returns latest block height. Cache is cleared when total_difficulty is fetched.
In order for this collector to work, alive and block_height calls need to be
followed with total_difficulty and client_version calls so the cache is cleared."""
blockchain_info = self.interface.cached_json_rpc_post(
self.block_height_payload)
return validate_dict_and_return_key_value(
blockchain_info, 'Height', self._logger_metadata)
def client_version(self):
"""Runs a cached query to return client version."""
blockchain_info = self.interface.cached_json_rpc_post(
self.client_version_payload)
version = validate_dict_and_return_key_value(
blockchain_info, 'Version', self._logger_metadata, stringify=True)
api_version = validate_dict_and_return_key_value(
blockchain_info, 'APIVersion', self._logger_metadata, stringify=True)
if version is None:
return None
client_version = {
"client_version": f"version:{version} APIversion:{api_version}"}
return client_version
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class SolanaCollector():
"""A collector to fetch information about solana RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'SolanaCollector',
'url': strip_url(url)
}
self.client_version_payload = {
'jsonrpc': '2.0',
'method': "getVersion",
'id': 1
}
self.block_height_payload = {
'jsonrpc': '2.0',
'method': "getBlockHeight",
'id': 1
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch client version from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rpc_post(
self.client_version_payload) is not None
def block_height(self):
"""Returns latest block height. Cache is cleared when total_difficulty is fetched.
In order for this collector to work, alive and block_height calls need to be
followed with total_difficulty and client_version calls so the cache is cleared."""
return self.interface.cached_json_rpc_post(self.block_height_payload)
def client_version(self):
"""Runs a cached query to return client version."""
blockchain_info = self.interface.cached_json_rpc_post(
self.client_version_payload)
version = validate_dict_and_return_key_value(
blockchain_info, 'solana-core', self._logger_metadata, stringify=True)
if version is None:
return None
client_version = {"client_version": version}
return client_version
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class StarknetCollector():
"""A collector to fetch information about starknet RPC endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self.block_height_payload = {
"method": "starknet_blockNumber",
"jsonrpc": "2.0",
"id": 1
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch client version from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rpc_post(self.block_height_payload) is not None
def block_height(self):
"""Returns latest block height. Cache is cleared when total_difficulty is fetched.
In order for this collector to work, alive and block_height calls need to be
followed with total_difficulty and client_version calls so the cache is cleared."""
block_height = self.interface.cached_json_rpc_post(
self.block_height_payload)
return block_height
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class AptosCollector():
"""A collector to fetch information about Aptos endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'AptosCollector',
'url': strip_url(url)
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch client version from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rest_api_get() is not None
def block_height(self):
"""Runs a cached query to return block height"""
blockchain_info = self.interface.cached_json_rest_api_get()
return validate_dict_and_return_key_value(
blockchain_info, 'block_height', self._logger_metadata, to_number=True)
def client_version(self):
"""Runs a cached query to return client version."""
blockchain_info = self.interface.cached_json_rest_api_get()
version = validate_dict_and_return_key_value(
blockchain_info, 'git_hash', self._logger_metadata, stringify=True)
if version is None:
return None
client_version = {"client_version": version}
return client_version
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class EvmHttpCollector():
"""A collector to fetch information from EVM HTTPS endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'EvmHttpCollector',
'url': strip_url(url)
}
self.client_version_payload = {
'jsonrpc': '2.0',
'method': "web3_clientVersion",
'id': 1
}
self.block_height_payload = {
'jsonrpc': '2.0',
'method': "eth_blockNumber",
'id': 1
}
self.finalized_block_height_payload = {
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["finalized", False],
"id": 1
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch client version from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rpc_post(
self.client_version_payload) is not None
def block_height(self):
"""Cached query and returns blockheight after converting hex string value to an int"""
result = self.interface.cached_json_rpc_post(self.block_height_payload)
if result and isinstance(result, str) and result.startswith('0x'):
return int(result, 16)
raise ValueError(f"Invalid block height result: {result}")
def finalized_block_height(self):
"""Returns finalized blockheight after converting hex string value to an int"""
finalized_block = self.interface.json_rpc_post(self.finalized_block_height_payload)
if finalized_block is None:
return None
block_number_hex = finalized_block.get('number')
if block_number_hex is None:
return None
return int(block_number_hex, 16)
def client_version(self):
"""Runs a cached query to return client version."""
version = self.interface.cached_json_rpc_post(
self.client_version_payload)
if version is None:
return None
client_version = {"client_version": version}
return client_version
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class XRPLCollector():
"""A collector to fetch information about XRP Ledger endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url, client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'XRPLCollector',
'url': strip_url(url)
}
self.ledger_closed_payload = {
'method': 'ledger_closed',
'params': [{}] # Required empty object in params array
}
self.server_info_payload = {
'method': 'server_info',
'params': [{}] # Required empty object in params array
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
return self.interface.cached_json_rpc_post(
self.ledger_closed_payload, non_rpc_response=True) is not None
def block_height(self):
"""Returns latest block height (ledger index)."""
response = self.interface.cached_json_rpc_post(
self.ledger_closed_payload, non_rpc_response=True)
if response is None:
return None
# For XRPL, the response will be the whole JSON object
if isinstance(response, dict) and 'result' in response:
result = response['result']
return validate_dict_and_return_key_value(
result, 'ledger_index', self._logger_metadata)
return None
def client_version(self):
"""Gets build version from server_info."""
response = self.interface.cached_json_rpc_post(
self.server_info_payload, non_rpc_response=True)
if response is None:
return None
# For XRPL, the response will be the whole JSON object
if isinstance(response, dict) and 'result' in response:
result = response['result']
if 'info' in result:
info = result['info']
version = validate_dict_and_return_key_value(
info, 'build_version', self._logger_metadata, stringify=True)
# If build_version is not found, try libxrpl_version
if version is None:
version = validate_dict_and_return_key_value(
info, 'libxrpl_version', self._logger_metadata, stringify=True)
if version is not None:
return {"client_version": version}
return None
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency
class TonCollector():
"""A collector to fetch information about Ton endpoints."""
def __init__(self, url, labels, chain_id, **client_parameters):
self.labels = labels
self.chain_id = chain_id
self.interface = HttpsInterface(url.rstrip("/") + "/jsonRPC",
client_parameters.get('open_timeout'),
client_parameters.get('ping_timeout'))
self._logger_metadata = {
'component': 'TonCollector',
'url': strip_url(url)
}
self.block_height_payload = {
'jsonrpc': '2.0',
'method': "getMasterchainInfo",
'id': 1
}
self.consensus_block_height_payload = {
'jsonrpc': '2.0',
'method': "getConsensusBlock",
'id': 1
}
def alive(self):
"""Returns true if endpoint is alive, false if not."""
# Run cached query because we can also fetch block height from this
# later on. This will save us an RPC call per run.
return self.interface.cached_json_rpc_post(
self.block_height_payload) is not None
def block_height(self):
"""Returns latest block height."""
result = self.interface.cached_json_rpc_post(self.block_height_payload)
if result is None:
raise ValueError("No response received from TON endpoint")
block_height = result.get('last', {}).get('seqno', None)
if block_height is not None:
return block_height
raise ValueError(f"Invalid block height result: {result}")
def finalized_block_height(self):
"""Runs a query to return consensus block height"""
result = self.interface.cached_json_rpc_post(self.consensus_block_height_payload)
if result is None:
raise ValueError("No response received from TON endpoint")
consensus_block = result.get('consensus_block', None)
if consensus_block is not None:
return consensus_block
raise ValueError(f"Invalid consensus block height result: {result}")
def latency(self):
"""Returns connection latency."""
return self.interface.latest_query_latency