-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathservice.zig
3532 lines (3013 loc) · 132 KB
/
service.zig
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const network = @import("zig-network");
const sig = @import("../sig.zig");
const bincode = sig.bincode;
const socket_utils = sig.net.socket_utils;
const pull_request = sig.gossip.pull_request;
const pull_response = sig.gossip.pull_response;
const ArrayList = std.ArrayList;
const Thread = std.Thread;
const Atomic = std.atomic.Value;
const KeyPair = std.crypto.sign.Ed25519.KeyPair;
const EndPoint = network.EndPoint;
const UdpSocket = network.Socket;
const Bloom = sig.bloom.Bloom;
const Pubkey = sig.core.Pubkey;
const Hash = sig.core.Hash;
const Logger = sig.trace.log.Logger;
const Packet = sig.net.Packet;
const EchoServer = sig.net.echo.Server;
const SocketAddr = sig.net.SocketAddr;
const Counter = sig.prometheus.Counter;
const Gauge = sig.prometheus.Gauge;
const Histogram = sig.prometheus.Histogram;
const GetMetricError = sig.prometheus.registry.GetMetricError;
const ThreadPoolTask = sig.utils.thread.ThreadPoolTask;
const ThreadPool = sig.sync.ThreadPool;
const Task = sig.sync.ThreadPool.Task;
const Batch = sig.sync.ThreadPool.Batch;
const Mux = sig.sync.Mux;
const RwMux = sig.sync.RwMux;
const Channel = sig.sync.Channel;
const ActiveSet = sig.gossip.active_set.ActiveSet;
const LegacyContactInfo = sig.gossip.data.LegacyContactInfo;
const ContactInfo = sig.gossip.data.ContactInfo;
const ThreadSafeContactInfo = sig.gossip.data.ThreadSafeContactInfo;
const GossipVersionedData = sig.gossip.data.GossipVersionedData;
const SignedGossipData = sig.gossip.data.SignedGossipData;
const GossipData = sig.gossip.data.GossipData;
const GossipDumpService = sig.gossip.dump_service.GossipDumpService;
const GossipMessage = sig.gossip.message.GossipMessage;
const PruneData = sig.gossip.PruneData;
const GossipTable = sig.gossip.table.GossipTable;
const HashTimeQueue = sig.gossip.table.HashTimeQueue;
const AutoArrayHashSet = sig.gossip.table.AutoArrayHashSet;
const GossipPullFilter = sig.gossip.pull_request.GossipPullFilter;
const Ping = sig.gossip.ping_pong.Ping;
const Pong = sig.gossip.ping_pong.Pong;
const PingCache = sig.gossip.ping_pong.PingCache;
const PingAndSocketAddr = sig.gossip.ping_pong.PingAndSocketAddr;
const ServiceManager = sig.utils.service_manager.ServiceManager;
const Duration = sig.time.Duration;
const ExitCondition = sig.sync.ExitCondition;
const SocketThread = sig.net.SocketThread;
const endpointToString = sig.net.endpointToString;
const globalRegistry = sig.prometheus.globalRegistry;
const getWallclockMs = sig.time.getWallclockMs;
const deinitMux = sig.sync.mux.deinitMux;
const PACKET_DATA_SIZE = sig.net.packet.PACKET_DATA_SIZE;
const UNIQUE_PUBKEY_CAPACITY = sig.gossip.table.UNIQUE_PUBKEY_CAPACITY;
const MAX_NUM_PULL_REQUESTS = sig.gossip.pull_request.MAX_NUM_PULL_REQUESTS;
const GossipMessageWithEndpoint = struct { from_endpoint: EndPoint, message: GossipMessage };
pub const PULL_REQUEST_RATE = Duration.fromSecs(5);
pub const PULL_RESPONSE_TIMEOUT = Duration.fromSecs(5);
pub const ACTIVE_SET_REFRESH_RATE = Duration.fromSecs(15);
pub const DATA_TIMEOUT = Duration.fromSecs(15);
pub const TABLE_TRIM_RATE = Duration.fromSecs(10);
pub const BUILD_MESSAGE_LOOP_MIN = Duration.fromSecs(1);
pub const PUBLISH_STATS_INTERVAL = Duration.fromSecs(2);
pub const PUSH_MSG_TIMEOUT = Duration.fromSecs(30);
pub const PRUNE_MSG_TIMEOUT = Duration.fromMillis(500);
pub const FAILED_INSERTS_RETENTION = Duration.fromSecs(20);
pub const PURGED_RETENTION = Duration.fromSecs(PULL_REQUEST_RATE.asSecs() * 5);
pub const MAX_PACKETS_PER_PUSH: usize = 64;
pub const MAX_BYTES_PER_PUSH: u64 = PACKET_DATA_SIZE * @as(u64, MAX_PACKETS_PER_PUSH);
// 4 (enum) + 32 (pubkey) + 8 (len) = 44
pub const MAX_PUSH_MESSAGE_PAYLOAD_SIZE: usize = PACKET_DATA_SIZE - 44;
pub const MAX_NUM_VALUES_PER_PULL_RESPONSE = 20; // TODO: this is approx the rust one -- should tune
pub const NUM_ACTIVE_SET_ENTRIES: usize = 25;
/// Maximum number of origin nodes that a PruneData may contain, such that the
/// serialized size of the PruneMessage stays below PACKET_DATA_SIZE.
pub const MAX_PRUNE_DATA_NODES: usize = 32;
pub const PING_CACHE_CAPACITY: usize = 65_536;
pub const PING_CACHE_TTL = Duration.fromSecs(1280);
pub const PING_CACHE_RATE_LIMIT_DELAY = Duration.fromSecs(1280 / 64);
// TODO: replace with get_epoch_duration when BankForks is supported
const DEFAULT_EPOCH_DURATION = Duration.fromMillis(172_800_000);
pub const VERIFY_PACKET_PARALLEL_TASKS = 4;
const THREAD_POOL_SIZE = 4;
const MAX_PROCESS_BATCH_SIZE = 64;
const GOSSIP_PRNG_SEED = 19;
/// The flow of data goes as follows:
///
/// `SocketThread.initReceiver` ->
/// - reads from the gossip socket
/// - puts the new packet onto `packet_incoming_channel`
/// - repeat until exit
///
/// `verifyPackets` ->
/// - receives from `packet_incoming_channel`
/// - starts queuing new parallel tasks with the new packets
/// - as a task verifies the incoming packet, it sends it into `verified_incoming_channel`
/// - repeat until exit *and* `packet_incoming_channel` is empty
///
/// `processMessages` ->
/// - receives from `verified_incoming_channel`
/// - processes the verified message it has received
/// - depending on the type of message received, it may put something onto `packet_outgoing_channel`
///
/// `SocketThread.initSender` ->
/// - receives from `packet_outgoing_channel`
/// - sends the outgoing packet onto the gossip socket
/// - repeats while `exit` is false and `packet_outgoing_channel`
/// - when `SocketThread` sees that `exit` has become `true`, it will begin waiting on
/// the previous thing in the chain to close, that usually being `processMessages`.
/// this ensures that `processMessages` doesn't add new items to `packet_outgoing_channel`
/// after the `SocketThread` exits.
///
pub const GossipService = struct {
/// used for general allocation purposes
allocator: std.mem.Allocator,
/// used specifically to allocate the gossip values
gossip_data_allocator: std.mem.Allocator,
gossip_socket: UdpSocket,
/// This contact info is mutated by the buildMessages thread (specifically, .shred_version and .wallclock),
/// so it must only be read by that thread, or it needs a synchronization mechanism.
my_contact_info: ContactInfo,
my_keypair: KeyPair,
my_pubkey: Pubkey,
my_shred_version: Atomic(u16),
/// An atomic counter for ensuring proper exit order of tasks.
exit_counter: *Atomic(u64),
/// Indicates if the gossip service is closed.
closed: bool,
/// Piping data between the gossip_socket and the channels.
/// Set to null until start() is called as they represent threads.
incoming_socket_thread: ?*SocketThread = null,
outgoing_socket_thread: ?*SocketThread = null,
/// communication between threads
packet_incoming_channel: *Channel(Packet),
packet_outgoing_channel: *Channel(Packet),
verified_incoming_channel: *Channel(GossipMessageWithEndpoint),
/// table to store gossip values
gossip_table_rw: RwMux(GossipTable),
/// manages push message peers
active_set_rw: RwMux(ActiveSet),
/// all gossip data pushed into this will have its wallclock overwritten during `drainPushQueueToGossipTable`.
/// NOTE: for all messages appended to this queue, the memory ownership is transfered to this struct.
push_msg_queue_mux: PushMessageQueue,
/// hashes of failed gossip values from pull responses
failed_pull_hashes_mux: Mux(HashTimeQueue),
/// entrypoint peers to start the process of discovering the network
entrypoints: ArrayList(Entrypoint),
/// manages ping/pong heartbeats for the network
ping_cache_rw: RwMux(PingCache),
thread_pool: ThreadPool,
// TODO: fix when http server is working
// echo_server: EchoServer,
logger: ScopedLogger,
metrics: GossipMetrics,
service_manager: ServiceManager,
const Self = @This();
pub const LOG_SCOPE = "gossip_service";
pub const ScopedLogger = sig.trace.log.ScopedLogger(LOG_SCOPE);
pub const PushMessageQueue = Mux(struct {
queue: ArrayList(GossipData),
data_allocator: std.mem.Allocator,
});
const Entrypoint = struct { addr: SocketAddr, info: ?ContactInfo = null };
pub fn create(
/// Must be thread-safe.
allocator: std.mem.Allocator,
/// Can be supplied as a different allocator in order to reduce contention.
/// Must be thread safe.
gossip_data_allocator: std.mem.Allocator,
my_contact_info: ContactInfo,
my_keypair: KeyPair,
maybe_entrypoints: ?[]const SocketAddr,
logger: Logger,
) !*Self {
const self = try allocator.create(Self);
self.* = try Self.init(
allocator,
gossip_data_allocator,
my_contact_info,
my_keypair,
maybe_entrypoints,
logger,
);
return self;
}
pub fn init(
/// Must be thread-safe.
allocator: std.mem.Allocator,
/// Can be supplied as a different allocator in order to reduce contention.
/// Must be thread safe.
gossip_data_allocator: std.mem.Allocator,
my_contact_info: ContactInfo,
my_keypair: KeyPair,
maybe_entrypoints: ?[]const SocketAddr,
logger: Logger,
) !Self {
const gossip_logger = logger.withScope(LOG_SCOPE);
// setup channels for communication between threads
var packet_incoming_channel = try Channel(Packet).create(allocator);
errdefer packet_incoming_channel.destroy();
var packet_outgoing_channel = try Channel(Packet).create(allocator);
errdefer packet_outgoing_channel.destroy();
var verified_incoming_channel = try Channel(GossipMessageWithEndpoint).create(allocator);
errdefer verified_incoming_channel.destroy();
// setup the socket (bind with read-timeout)
const gossip_address = my_contact_info.getSocket(.gossip) orelse return error.GossipAddrUnspecified;
var gossip_socket = UdpSocket.create(.ipv4, .udp) catch return error.SocketCreateFailed;
gossip_socket.bindToPort(gossip_address.port()) catch return error.SocketBindFailed;
gossip_socket.setReadTimeout(socket_utils.SOCKET_TIMEOUT_US) catch return error.SocketSetTimeoutFailed; // 1 second
// setup the threadpool for processing messages
const n_threads: usize = @min(std.Thread.getCpuCount() catch 1, THREAD_POOL_SIZE);
const thread_pool = ThreadPool.init(.{
.max_threads = @intCast(n_threads),
.stack_size = 2 * 1024 * 1024,
});
gossip_logger.info().logf("starting threadpool with {} threads", .{n_threads});
// setup the table
var gossip_table = try GossipTable.init(allocator, gossip_data_allocator);
errdefer gossip_table.deinit();
// setup the active set for push messages
const active_set = ActiveSet.init(allocator);
// setup entrypoints
var entrypoints = ArrayList(Entrypoint).init(allocator);
if (maybe_entrypoints) |entrypoint_addrs| {
try entrypoints.ensureTotalCapacityPrecise(entrypoint_addrs.len);
for (entrypoint_addrs) |entrypoint_addr| {
entrypoints.appendAssumeCapacity(.{ .addr = entrypoint_addr });
}
}
// setup ping/pong cache
const ping_cache = try PingCache.init(
allocator,
PING_CACHE_TTL,
PING_CACHE_RATE_LIMIT_DELAY,
PING_CACHE_CAPACITY,
);
const my_pubkey = Pubkey.fromPublicKey(&my_keypair.public_key);
const my_shred_version = my_contact_info.shred_version;
const failed_pull_hashes = HashTimeQueue.init(allocator);
const metrics = try GossipMetrics.init();
const exit_counter = try allocator.create(Atomic(u64));
exit_counter.* = Atomic(u64).init(0);
const exit = try allocator.create(Atomic(bool));
exit.* = Atomic(bool).init(false);
const service_manager = ServiceManager.init(
allocator,
logger,
exit,
"gossip",
.{},
.{},
);
return .{
.allocator = allocator,
.gossip_data_allocator = gossip_data_allocator,
.my_contact_info = my_contact_info,
.my_keypair = my_keypair,
.my_pubkey = my_pubkey,
.my_shred_version = Atomic(u16).init(my_shred_version),
.gossip_socket = gossip_socket,
.packet_incoming_channel = packet_incoming_channel,
.packet_outgoing_channel = packet_outgoing_channel,
.verified_incoming_channel = verified_incoming_channel,
.gossip_table_rw = RwMux(GossipTable).init(gossip_table),
.push_msg_queue_mux = PushMessageQueue.init(.{
.queue = ArrayList(GossipData).init(allocator),
.data_allocator = gossip_data_allocator,
}),
.active_set_rw = RwMux(ActiveSet).init(active_set),
.failed_pull_hashes_mux = Mux(HashTimeQueue).init(failed_pull_hashes),
.entrypoints = entrypoints,
.ping_cache_rw = RwMux(PingCache).init(ping_cache),
.logger = gossip_logger,
.thread_pool = thread_pool,
.metrics = metrics,
.exit_counter = exit_counter,
.service_manager = service_manager,
.closed = false,
};
}
/// Starts the shutdown chain for all services. Does *not* block until
/// the service manager is joined.
pub fn shutdown(self: *Self) void {
std.debug.assert(!self.closed);
defer self.closed = true;
// kick off the shutdown chain
self.exit_counter.store(1, .release);
// exit the service manager loops when methods return
self.service_manager.exit.store(true, .release);
}
pub fn deinit(self: *Self) void {
std.debug.assert(self.closed); // call `self.shutdown()` first
// wait for all threads to shutdown correctly
self.service_manager.deinit();
// Wait for pipes to shutdown if any
if (self.incoming_socket_thread) |thread| thread.join();
if (self.outgoing_socket_thread) |thread| thread.join();
// assert the channels are empty in order to make sure no data was lost.
// everything should be cleaned up when the thread-pool joins.
std.debug.assert(self.packet_incoming_channel.isEmpty());
self.packet_incoming_channel.destroy();
std.debug.assert(self.packet_outgoing_channel.isEmpty());
self.packet_outgoing_channel.destroy();
std.debug.assert(self.verified_incoming_channel.isEmpty());
self.verified_incoming_channel.destroy();
self.gossip_socket.close();
self.thread_pool.shutdown();
self.thread_pool.deinit();
self.allocator.destroy(self.exit_counter);
self.allocator.destroy(self.service_manager.exit);
self.entrypoints.deinit();
self.my_contact_info.deinit();
deinitMux(&self.gossip_table_rw);
deinitMux(&self.active_set_rw);
deinitMux(&self.ping_cache_rw);
deinitMux(&self.failed_pull_hashes_mux);
{
// clear and deinit the push quee
const push_msg_queue, var lock = self.push_msg_queue_mux.writeWithLock();
defer lock.unlock();
for (push_msg_queue.queue.items) |*v| v.deinit(push_msg_queue.data_allocator);
push_msg_queue.queue.deinit();
}
}
pub const RunThreadsParams = struct {
spy_node: bool = false,
dump: bool = false,
};
/// starts gossip and blocks until it exits (which can be signaled by calling `shutdown`)
pub fn run(self: *Self, params: RunThreadsParams) !void {
try self.start(params);
self.service_manager.join();
}
/// spawns required threads for the gossip service and returns immediately
/// including:
/// 1) socket reciever
/// 2) packet verifier
/// 3) packet processor
/// 4) build message loop (to send outgoing message) (if a spy node, not active)
/// 5) a socket responder (to send outgoing packets)
pub fn start(
self: *Self,
params: RunThreadsParams,
) !void {
// NOTE: this is stack copied on each spawn() call below so we can modify it without
// affecting other threads
var exit_condition = sig.sync.ExitCondition{
.ordered = .{
.exit_counter = self.exit_counter,
.exit_index = 1,
},
};
self.incoming_socket_thread = try SocketThread.spawnReceiver(
self.allocator,
self.logger.unscoped(),
self.gossip_socket,
self.packet_incoming_channel,
exit_condition,
);
exit_condition.ordered.exit_index += 1;
try self.service_manager.spawn("[gossip] verifyPackets", verifyPackets, .{
self,
exit_condition,
});
exit_condition.ordered.exit_index += 1;
try self.service_manager.spawn("[gossip] processMessages", processMessages, .{
self,
GOSSIP_PRNG_SEED,
exit_condition,
});
exit_condition.ordered.exit_index += 1;
if (!params.spy_node) {
try self.service_manager.spawn("[gossip] buildMessages", buildMessages, .{
self,
GOSSIP_PRNG_SEED,
exit_condition,
});
exit_condition.ordered.exit_index += 1;
}
self.outgoing_socket_thread = try SocketThread.spawnSender(
self.allocator,
self.logger.unscoped(),
self.gossip_socket,
self.packet_outgoing_channel,
exit_condition,
);
exit_condition.ordered.exit_index += 1;
if (params.dump) {
try self.service_manager.spawn("[gossip] dumpService", GossipDumpService.run, .{.{
.allocator = self.allocator,
.logger = self.logger.withScope(@typeName(GossipDumpService)),
.gossip_table_rw = &self.gossip_table_rw,
.exit_condition = exit_condition,
}});
exit_condition.ordered.exit_index += 1;
}
}
const VerifyMessageTask = ThreadPoolTask(VerifyMessageEntry);
const VerifyMessageEntry = struct {
gossip_data_allocator: std.mem.Allocator,
packet: Packet,
verified_incoming_channel: *Channel(GossipMessageWithEndpoint),
logger: ScopedLogger,
pub fn callback(self: *VerifyMessageEntry) !void {
const packet = self.packet;
var message = bincode.readFromSlice(
self.gossip_data_allocator,
GossipMessage,
packet.data[0..packet.size],
bincode.Params.standard,
) catch |e| {
self.logger.err().logf("packet_verify: failed to deserialize: {s}", .{@errorName(e)});
return;
};
message.sanitize() catch |e| {
self.logger.err().logf("packet_verify: failed to sanitize: {s}", .{@errorName(e)});
bincode.free(self.gossip_data_allocator, message);
return;
};
message.verifySignature() catch |e| {
self.logger.err().logf(
"packet_verify: failed to verify signature from {}: {s}",
.{ packet.addr, @errorName(e) },
);
bincode.free(self.gossip_data_allocator, message);
return;
};
const msg: GossipMessageWithEndpoint = .{
.from_endpoint = packet.addr,
.message = message,
};
try self.verified_incoming_channel.send(msg);
}
};
/// main logic for deserializing Packets into GossipMessage messages
/// and verifing they have valid values, and have valid signatures.
/// Verified GossipMessagemessages are then sent to the verified_channel.
fn verifyPackets(self: *Self, exit_condition: ExitCondition) !void {
defer {
// empty the channel
while (self.packet_incoming_channel.tryReceive()) |_| {}
// trigger the next service in the chain to close
exit_condition.afterExit();
self.logger.debug().log("verifyPackets loop closed");
}
const tasks = try VerifyMessageTask.init(self.allocator, VERIFY_PACKET_PARALLEL_TASKS);
defer self.allocator.free(tasks);
// pre-allocate all the tasks
for (tasks) |*task| {
task.entry = .{
.gossip_data_allocator = self.gossip_data_allocator,
.verified_incoming_channel = self.verified_incoming_channel,
.packet = undefined,
.logger = self.logger,
};
}
// loop until the previous service closes and triggers us to close
while (true) {
self.packet_incoming_channel.waitToReceive(exit_condition) catch break;
// verify in parallel using the threadpool
// PERF: investigate CPU pinning
var task_search_start_idx: usize = 0;
while (self.packet_incoming_channel.tryReceive()) |packet| {
defer self.metrics.gossip_packets_received_total.inc();
const acquired_task_idx = VerifyMessageTask.awaitAndAcquireFirstAvailableTask(tasks, task_search_start_idx);
task_search_start_idx = (acquired_task_idx + 1) % tasks.len;
const task_ptr = &tasks[acquired_task_idx];
task_ptr.entry.packet = packet;
task_ptr.result catch |err| self.logger.err().logf("VerifyMessageTask encountered error: {s}", .{@errorName(err)});
const batch = Batch.from(&task_ptr.task);
self.thread_pool.schedule(batch);
}
}
for (tasks) |*task| {
task.blockUntilCompletion();
task.result catch |err| self.logger.err().logf("VerifyMessageTask encountered error: {s}", .{@errorName(err)});
}
}
// structs used in process_messages loop
pub const PingMessage = struct {
ping: *const Ping,
from_endpoint: *const EndPoint,
};
pub const PongMessage = struct {
pong: *const Pong,
from_endpoint: *const EndPoint,
};
pub const PushMessage = struct {
gossip_values: []SignedGossipData,
from_pubkey: *const Pubkey,
from_endpoint: *const EndPoint,
};
pub const PullRequestMessage = struct {
filter: GossipPullFilter,
value: SignedGossipData,
from_endpoint: EndPoint,
};
pub const PullResponseMessage = struct {
gossip_values: []SignedGossipData,
from_pubkey: *const Pubkey,
};
/// main logic for recieving and processing gossip messages.
pub fn processMessages(self: *Self, seed: u64, exit_condition: ExitCondition) !void {
defer {
// empty the channel and release the memory
while (self.verified_incoming_channel.tryReceive()) |message| {
bincode.free(self.gossip_data_allocator, message.message);
}
// even if we fail, trigger the next thread to close
exit_condition.afterExit();
self.logger.debug().log("processMessages loop closed");
}
// we batch messages bc:
// 1) less lock contention
// 2) can use packetbatchs (ie, pre-allocated packets)
// 3) processing read-heavy messages in parallel (specifically pull-requests)
const init_capacity = socket_utils.PACKETS_PER_BATCH;
var ping_messages = try ArrayList(PingMessage).initCapacity(self.allocator, init_capacity);
defer ping_messages.deinit();
var pong_messages = try ArrayList(PongMessage).initCapacity(self.allocator, init_capacity);
defer pong_messages.deinit();
var push_messages = try ArrayList(PushMessage).initCapacity(self.allocator, init_capacity);
defer push_messages.deinit();
var pull_requests = try ArrayList(PullRequestMessage).initCapacity(self.allocator, init_capacity);
defer pull_requests.deinit();
var pull_responses = try ArrayList(PullResponseMessage).initCapacity(self.allocator, init_capacity);
defer pull_responses.deinit();
var prune_messages = try ArrayList(PruneData).initCapacity(self.allocator, init_capacity);
defer prune_messages.deinit();
var trim_table_timer = try sig.time.Timer.start();
// keep waiting for new data until,
// - `exit` isn't set,
// - there isn't any data to process in the input channel, in order to block the join until we've finished
while (true) {
self.verified_incoming_channel.waitToReceive(exit_condition) catch break;
var msg_count: usize = 0;
while (self.verified_incoming_channel.tryReceive()) |message| {
msg_count += 1;
switch (message.message) {
.PushMessage => |*push| {
try push_messages.append(.{
.gossip_values = push[1],
.from_pubkey = &push[0],
.from_endpoint = &message.from_endpoint,
});
},
.PullResponse => |*pull| {
try pull_responses.append(.{
.from_pubkey = &pull[0],
.gossip_values = pull[1],
});
},
.PullRequest => |*pull| {
const value: SignedGossipData = pull[1];
var should_drop = false;
switch (value.data) {
.ContactInfo => |*data| {
if (data.pubkey.equals(&self.my_pubkey)) {
// talking to myself == ignore
should_drop = true;
}
// Allow spy nodes with shred-verion == 0 to pull from other nodes.
if (data.shred_version != 0 and data.shred_version != self.my_shred_version.load(.monotonic)) {
// non-matching shred version
self.metrics.pull_requests_dropped.add(1);
should_drop = true;
}
},
.LegacyContactInfo => |*data| {
if (data.id.equals(&self.my_pubkey)) {
// talking to myself == ignore
should_drop = true;
}
// Allow spy nodes with shred-verion == 0 to pull from other nodes.
if (data.shred_version != 0 and data.shred_version != self.my_shred_version.load(.monotonic)) {
// non-matching shred version
self.metrics.pull_requests_dropped.add(1);
should_drop = true;
}
},
// only contact info supported
else => {
self.metrics.pull_requests_dropped.add(1);
should_drop = true;
},
}
const from_addr = SocketAddr.fromEndpoint(&message.from_endpoint);
if (from_addr.isUnspecified() or from_addr.port() == 0) {
// unable to respond to these messages
self.metrics.pull_requests_dropped.add(1);
should_drop = true;
}
if (should_drop) {
pull[0].deinit();
value.deinit(self.gossip_data_allocator);
} else {
try pull_requests.append(.{
.filter = pull[0],
.value = value,
.from_endpoint = message.from_endpoint,
});
}
},
.PruneMessage => |*prune| {
const prune_data = prune[1];
const now = getWallclockMs();
const prune_wallclock = prune_data.wallclock;
const too_old = prune_wallclock < now -| PRUNE_MSG_TIMEOUT.asMillis();
const incorrect_destination = !prune_data.destination.equals(&self.my_pubkey);
if (too_old or incorrect_destination) {
self.metrics.prune_messages_dropped.add(1);
prune_data.deinit(self.gossip_data_allocator);
continue;
}
try prune_messages.append(prune_data);
},
.PingMessage => |*ping| {
const from_addr = SocketAddr.fromEndpoint(&message.from_endpoint);
if (from_addr.isUnspecified() or from_addr.port() == 0) {
// unable to respond to these messages
self.metrics.ping_messages_dropped.add(1);
continue;
}
try ping_messages.append(PingMessage{
.ping = ping,
.from_endpoint = &message.from_endpoint,
});
},
.PongMessage => |*pong| {
try pong_messages.append(PongMessage{
.pong = pong,
.from_endpoint = &message.from_endpoint,
});
},
}
if (msg_count > MAX_PROCESS_BATCH_SIZE) break;
}
if (msg_count == 0) continue;
// track metrics
self.metrics.gossip_packets_verified_total.add(msg_count);
self.metrics.ping_messages_recv.add(ping_messages.items.len);
self.metrics.pong_messages_recv.add(pong_messages.items.len);
self.metrics.push_messages_recv.add(push_messages.items.len);
self.metrics.pull_requests_recv.add(pull_requests.items.len);
self.metrics.pull_responses_recv.add(pull_responses.items.len);
self.metrics.prune_messages_recv.add(prune_messages.items.len);
var gossip_packets_processed_total: usize = 0;
gossip_packets_processed_total += ping_messages.items.len;
gossip_packets_processed_total += pong_messages.items.len;
gossip_packets_processed_total += push_messages.items.len;
gossip_packets_processed_total += pull_requests.items.len;
gossip_packets_processed_total += pull_responses.items.len;
gossip_packets_processed_total += prune_messages.items.len;
// only add the count once we've finished processing
defer self.metrics.gossip_packets_processed_total.add(gossip_packets_processed_total);
// handle batch messages
if (push_messages.items.len > 0) {
var x_timer = try sig.time.Timer.start();
self.handleBatchPushMessages(&push_messages) catch |err| {
self.logger.err().logf("handleBatchPushMessages failed: {}", .{err});
};
const elapsed = x_timer.read().asMillis();
self.metrics.handle_batch_push_time.observe(elapsed);
for (push_messages.items) |push| {
// NOTE: this just frees the slice of values, not the values themselves
// (which were either inserted into the store, or freed)
self.gossip_data_allocator.free(push.gossip_values);
}
push_messages.clearRetainingCapacity();
}
if (prune_messages.items.len > 0) {
var x_timer = try sig.time.Timer.start();
self.handleBatchPruneMessages(&prune_messages);
const elapsed = x_timer.read().asMillis();
self.metrics.handle_batch_prune_time.observe(elapsed);
for (prune_messages.items) |prune| {
prune.deinit(self.gossip_data_allocator);
}
prune_messages.clearRetainingCapacity();
}
if (pull_requests.items.len > 0) {
var x_timer = try sig.time.Timer.start();
self.handleBatchPullRequest(seed + msg_count, pull_requests.items) catch |err| {
self.logger.err().logf("handleBatchPullRequest failed: {}", .{err});
};
const elapsed = x_timer.read().asMillis();
self.metrics.handle_batch_pull_req_time.observe(elapsed);
for (pull_requests.items) |*req| {
// NOTE: the contact info (req.value) is inserted into the gossip table
// so we only free the filter
req.filter.deinit();
}
pull_requests.clearRetainingCapacity();
}
if (pull_responses.items.len > 0) {
var x_timer = try sig.time.Timer.start();
self.handleBatchPullResponses(pull_responses.items) catch |err| {
self.logger.err().logf("handleBatchPullResponses failed: {}", .{err});
};
const elapsed = x_timer.read().asMillis();
self.metrics.handle_batch_pull_resp_time.observe(elapsed);
for (pull_responses.items) |*pull| {
// NOTE: this just frees the slice of values, not the values themselves
// (which were either inserted into the store, or freed)
self.gossip_data_allocator.free(pull.gossip_values);
}
pull_responses.clearRetainingCapacity();
}
if (ping_messages.items.len > 0) {
var x_timer = try sig.time.Timer.start();
self.handleBatchPingMessages(&ping_messages) catch |err| {
self.logger.err().logf("handleBatchPingMessages failed: {}", .{err});
};
const elapsed = x_timer.read().asMillis();
self.metrics.handle_batch_ping_time.observe(elapsed);
ping_messages.clearRetainingCapacity();
}
if (pong_messages.items.len > 0) {
var x_timer = try sig.time.Timer.start();
self.handleBatchPongMessages(&pong_messages);
const elapsed = x_timer.read().asMillis();
self.metrics.handle_batch_pong_time.observe(elapsed);
pong_messages.clearRetainingCapacity();
}
// TRIM gossip-table
if (trim_table_timer.read().asNanos() > TABLE_TRIM_RATE.asNanos()) {
defer trim_table_timer.reset();
try self.attemptGossipTableTrim();
}
}
}
/// uses a read lock to first check if the gossip table should be trimmed,
/// then acquires a write lock to perform the trim.
/// NOTE: in practice, trim is rare because the number of global validators is much <10k (the global constant
/// used is UNIQUE_PUBKEY_CAPACITY)
pub fn attemptGossipTableTrim(self: *Self) !void {
// first check with a read lock
const should_trim = blk: {
const gossip_table, var gossip_table_lock = self.gossip_table_rw.readWithLock();
defer gossip_table_lock.unlock();
const should_trim = gossip_table.shouldTrim(UNIQUE_PUBKEY_CAPACITY);
break :blk should_trim;
};
// then trim with write lock
const n_pubkeys_dropped: u64 = if (should_trim) blk: {
var gossip_table, var gossip_table_lock = self.gossip_table_rw.writeWithLock();
defer gossip_table_lock.unlock();
var x_timer = sig.time.Timer.start() catch unreachable;
const now = getWallclockMs();
const n_pubkeys_dropped = gossip_table.attemptTrim(now, UNIQUE_PUBKEY_CAPACITY) catch |err| err_blk: {
self.logger.err().logf("gossip_table.attemptTrim failed: {s}", .{@errorName(err)});
break :err_blk 0;
};
const elapsed = x_timer.read().asMillis();
self.metrics.handle_trim_table_time.observe(elapsed);
break :blk n_pubkeys_dropped;
} else 0;
self.metrics.table_pubkeys_dropped.add(n_pubkeys_dropped);
}
/// main gossip loop for periodically sending new GossipMessagemessages.
/// this includes sending push messages, pull requests, and triming old
/// gossip data (in the gossip_table, active_set, and failed_pull_hashes).
fn buildMessages(self: *Self, seed: u64, exit_condition: ExitCondition) !void {
defer {
exit_condition.afterExit();
self.logger.info().log("buildMessages loop closed");
}
var loop_timer = try sig.time.Timer.start();
var active_set_timer = try sig.time.Timer.start();
var pull_req_timer = try sig.time.Timer.start();
var stats_publish_timer = try sig.time.Timer.start();
var trim_memory_timer = try sig.time.Timer.start();
var prng = std.rand.DefaultPrng.init(seed);
const random = prng.random();
var push_cursor: u64 = 0;
var entrypoints_identified = false;
var shred_version_assigned = false;
while (exit_condition.shouldRun()) {
defer loop_timer.reset();
if (pull_req_timer.read().asNanos() > PULL_REQUEST_RATE.asNanos()) pull_blk: {
defer pull_req_timer.reset();
// this also includes sending ping messages to other peers
const now = getWallclockMs();
const pull_req_packets = self.buildPullRequests(
random,
pull_request.MAX_BLOOM_SIZE,
now,
) catch |e| {
self.logger.err().logf("failed to generate pull requests: {any}", .{e});
break :pull_blk;
};
defer pull_req_packets.deinit();
for (pull_req_packets.items) |packet| {
try self.packet_outgoing_channel.send(packet);
}
self.metrics.pull_requests_sent.add(pull_req_packets.items.len);
}
// new push msgs
try self.drainPushQueueToGossipTable(getWallclockMs());
const maybe_push_packets = self.buildPushMessages(&push_cursor) catch |e| blk: {
self.logger.err().logf("failed to generate push messages: {any}", .{e});
break :blk null;
};
if (maybe_push_packets) |push_packets| {
defer push_packets.deinit();
self.metrics.push_messages_sent.add(push_packets.items.len);
for (push_packets.items) |push_packet| {
try self.packet_outgoing_channel.send(push_packet);
}
}
// trim data
if (trim_memory_timer.read().asNanos() > TABLE_TRIM_RATE.asNanos()) {
defer trim_memory_timer.reset();
try self.trimMemory(getWallclockMs());
}
// initialize cluster data from gossip values
entrypoints_identified = entrypoints_identified or try self.populateEntrypointsFromGossipTable();
shred_version_assigned = shred_version_assigned or self.assignDefaultShredVersionFromEntrypoint();
// periodic things
if (active_set_timer.read().asNanos() > ACTIVE_SET_REFRESH_RATE.asNanos()) {
defer active_set_timer.reset();
// push contact info
{
var push_msg_queue, var push_msg_queue_lock = self.push_msg_queue_mux.writeWithLock();
defer push_msg_queue_lock.unlock();
const contact_info: ContactInfo = try self.my_contact_info.clone();
errdefer contact_info.deinit();
const legacy_contact_info = LegacyContactInfo.fromContactInfo(
&self.my_contact_info,
);
try push_msg_queue.queue.appendSlice(&.{
.{ .ContactInfo = contact_info },
.{ .LegacyContactInfo = legacy_contact_info },
});
}
try self.rotateActiveSet(random);
}
// publish metrics
if (stats_publish_timer.read().asNanos() > PUBLISH_STATS_INTERVAL.asNanos()) {
defer stats_publish_timer.reset();
try self.collectGossipTableMetrics();
}
// sleep
if (loop_timer.read().asNanos() < BUILD_MESSAGE_LOOP_MIN.asNanos()) {
const time_left_ms = BUILD_MESSAGE_LOOP_MIN.asMillis() -| loop_timer.read().asMillis();
std.time.sleep(time_left_ms * std.time.ns_per_ms);
}
}
}
// collect gossip table metrics and pushes them to stats
pub fn collectGossipTableMetrics(self: *Self) !void {
var gossip_table_lock = self.gossip_table_rw.read();
defer gossip_table_lock.unlock();
const gossip_table = gossip_table_lock.get();
const n_entries = gossip_table.store.count();
const n_pubkeys = gossip_table.pubkey_to_values.count();
self.metrics.table_n_values.set(n_entries);