-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathservice_reactor.cpp
2686 lines (2134 loc) · 109 KB
/
service_reactor.cpp
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
#include "service_common.h"
#include <sched.h>
static constexpr bool trace_idle{false};
static constexpr bool trace_timers{false};
static constexpr bool trace_classification{false};
// From SENDFILE(2): The original Linux sendfile() system call was not designed to handle large file offsets.
// Consequently, Linux 2.4 added sendfile64(), with a wider type for the offset argument.
// The glibc sendfile() wrapper function transparently deals with the kernel differences.
#define HAVE_SENDFILE64 1
void Service::wakeup_reactor() {
uint64_t one{1};
::write(_interrupt_efd, &one, sizeof(one));
}
void Service::maybe_wakeup_reactor() {
std::atomic_signal_fence(std::memory_order_seq_cst);
if (sleeping.load(std::memory_order_relaxed)) {
sleeping.store(false, std::memory_order_relaxed);
wakeup_reactor();
}
}
// it is important that we defer work by marking a resource as dirty and placing it in a queue if it was just marked as dirty
// as opposed to imediately processing the resource op. so that we can avoid doing this more than once in the same reactor loop iteration
// because it doesn't make much sense to do so, and because batching may provide us with other benefits
void Service::begin_reactor_loop_iteration() {
reusable_conns.insert(reusable_conns.end(), pending_reusable_conns.begin(), pending_reusable_conns.end());
pending_reusable_conns.clear();
gc_waitctx_deferred();
if (next_cluster_state_apply == std::numeric_limits<uint64_t>::max()) {
// only if not postponed
apply_deferred_updates();
}
while (auto req = consul_state.deferred_reqs_head) {
auto n = req->next;
req->flags &= ~unsigned(consul_request::Flags::Deferred);
schedule_consul_req_impl(req, req->flags & unsigned(consul_request::Flags::Urgent));
consul_state.deferred_reqs_head = n;
}
// it is important that we drain the queue
// and that we process any pending signals here before
// we block in epoll_pwait()
// see progADMANatic/service_reactor::begin_loop_iteration() for rational
drain_pubsub_queue();
if (const auto mask = pending_signals.load(std::memory_order_relaxed)) {
pending_signals.fetch_and(~mask, std::memory_order_relaxed);
if (!process_pending_signals(mask)) {
initiate_tear_down();
}
}
}
void Service::initiate_tear_down() {
static constexpr bool trace{false};
if (reactor_state == ReactorState::Active) {
if constexpr (trace) {
SLog("Switching to TearDown\n");
}
reactor_state = ReactorState::TearDown;
} else {
if constexpr (trace) {
SLog("Already tearing down reactor\n");
}
return;
}
disable_listener();
// we don't want to wait too long for that
set_reactor_state_idle_timer.node.key = now_ms + 2 * 1000;
register_timer(&set_reactor_state_idle_timer.node);
if (cluster_aware()) {
if (consul_state._session_id_len) {
// we need to release it first, _then_ we will switch to ReactorState::WaitAllConnsIdle
if constexpr (trace) {
SLog("Will need to release session\n");
}
reactor_state = ReactorState::ReleaseSess;
if (cluster_state.leader_self()) {
// XXX:
// this appears to be a consul bug. If we destroy a session, then other nodes
// long-polling for /TANK/clusters/<cluster/leaders/ will be provided with a response, where e.g
// key CLUSTER will not be associated with a "Session"(which is what we expect to happen)
// If howevwe we try_become_cluster_leader() the consul HTTP request fail with 200 "false".
//
// If we keep trying(see try_become_cluster_leader_timer), it will eventually succeed after about 4 seconds
//
// If we release the session lock for that key, before we destroy the session, then one
// of the other nodes will succeed in try_become_cluster_leader()
//
// I don't know why this is so, but it is definitely not ideal.
// This is also affecting node locks, where if we don't release the lock of an acquired cluster node on shutdown,
// if we immediately restart the service where it attempts to re-acquire its node ID, it fails
//
// As of 1.4.0 it's not resolved.
// Tracking issue here: https://github.com/hashicorp/consul/issues/5205
//
// UPDATE: apparently, this is the expected behavior (I still maintain this is a bug)
// so we need to work around it, which means we need to release the node lock as well in addition to the cluster lock
auto first = consul_state.get_req(consul_request::Type::ReleaseClusterLeadership);
auto req = first;
if constexpr (trace) {
SLog("Self is the cluster leader, will ReleaseClusterLeadership before DestroySession\n");
}
req = (req->then = consul_state.get_req(consul_request::Type::ReleaseNodeLock));
req = (req->then = consul_state.get_req(consul_request::Type::DestroySession));
schedule_consul_req(first, true);
} else {
// Destroying the session will also release all locks or leases assoc. with it
if constexpr (trace) {
SLog("Self is not cluster leader, will DestroySession\n");
}
auto req = consul_state.get_req(consul_request::Type::ReleaseNodeLock);
req->then = consul_state.get_req(consul_request::Type::DestroySession);
schedule_consul_req(req, true);
}
return;
}
}
if (all_conns_idle()) {
if constexpr (trace) {
SLog("All connections idle already\n");
}
reactor_state = ReactorState::Idle;
} else {
if constexpr (trace) {
SLog("Waill wait for all connections to become idle\n");
}
reactor_state = ReactorState::WaitAllConnsIdle;
}
}
void Service::consider_deferred_produce_responses() {
static constexpr bool trace{false};
while (!deferred_produce_responses_expiration_list.empty()) {
auto dpr = switch_list_entry(produce_response, deferred.expiration.ll, deferred_produce_responses_expiration_list.prev);
// how can that possibly be?
TANK_EXPECT(false == dpr->deferred.expiration.ll.empty());
if (const auto when = dpr->deferred.expiration.ts; when > now_ms) {
deferred_produce_responses_next_expiration = when;
return;
}
if (trace) {
SLog("Timing out DPR\n");
}
// this is really a trampoline to try_generate_produce_response()
complete_deferred_produce_response(dpr);
}
}
int Service::reactor_main() {
unsigned iterations{0};
#define _TRACE_EXPENSIVE 1
now_ms = Timings::Milliseconds::Tick();
#ifdef _TRACE_EXPENSIVE
uint64_t _start;
#endif
reactor_state = ReactorState::Active;
curTime = time(nullptr);
for (uint64_t next_curtime_update{0}; reactor_state != ReactorState::Idle;) {
if (now_ms > next_cluster_state_apply) {
next_cluster_state_apply = std::numeric_limits<uint64_t>::max();
}
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
begin_reactor_loop_iteration();
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
// determine how long to wait, account for the next timer/event timestamp
const auto wait_until = TANKUtil::minimum(
scheduled_consume_retries_list_next,
deferred_produce_responses_next_expiration,
isr_pending_ack_list_next,
consul_state.active_conns_next_process_ts,
next_idle_check_ts,
timers_ebtree_next,
consul_state.active_conns_next_process_ts,
next_cluster_state_apply,
next_active_partitions_check,
now_ms + 30 * 1000);
sleeping.store(true, std::memory_order_relaxed);
const auto max_conngen_process = next_connection_generation;
const auto r = poller.poll(wait_until - now_ms);
const auto saved_errno = errno; // in case it's updated before we use it
sleeping.store(false, std::memory_order_relaxed);
// CPU relax -- this is not a spin-lock wait loop
// but we may as well be kind to the CPU
asm volatile("pause\n"
:
:
: "memory");
now_ms = Timings::Milliseconds::Tick();
if (++iterations == 10) {
// be kind
sched_yield();
iterations = 0;
}
if (now_ms > next_curtime_update) {
// we can avoid excessive time() calls by
// checking updating every 500ms. The chance that we 'll get the time wrong (by 1 second) is an acceptable tradeoff
const auto _now = time(nullptr);
if (unlikely(_now == ((time_t)-1))) {
Print("time() failed:", strerror(errno), "\n");
std::abort();
}
curTime = _now;
next_curtime_update = now_ms + 500;
}
if (unlikely(-1 == r)) {
if (saved_errno != EINTR && saved_errno != EAGAIN) {
IMPLEMENT_ME();
}
} else if (r) {
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
if (const auto res = process_io(r, max_conngen_process)) {
return res;
}
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
}
if (now_ms >= timers_ebtree_next) {
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
process_timers();
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
}
if (now_ms >= next_idle_check_ts) {
consider_idle_conns();
}
if (now_ms >= next_active_partitions_check) {
consider_active_partitions();
}
if (now_ms >= consul_state.active_conns_next_process_ts) {
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
consider_long_running_active_consul_requests();
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
}
if (now_ms >= isr_pending_ack_list_next) {
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
consider_isr_pending_ack();
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
}
if (now_ms >= deferred_produce_responses_next_expiration) {
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
consider_deferred_produce_responses();
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
}
if (now_ms >= scheduled_consume_retries_list_next) {
#ifdef _TRACE_EXPENSIVE
_start = Timings::Microseconds::Tick();
#endif
consider_scheduled_consume_retries();
#ifdef _TRACE_EXPENSIVE
if (const auto delta = Timings::Microseconds::Since(_start); delta > Timings::Seconds::ToMicros(1)) {
SLog("Took ", duration_repr(delta), " for op\n");
}
#endif
}
}
tear_down();
#ifdef _TRACE_EXPENSIVE
#undef _TRACE_EXPENSIVE
#endif
Print("TANK terminated\n");
return 0;
}
void Service::put_connection(connection *const c) {
TANK_EXPECT(c->connectionsList.empty());
TANK_EXPECT(c->classification.ll.empty());
TANK_EXPECT(-1 == c->fd);
if (c->inB) {
put_buf(c->inB);
c->inB = nullptr;
}
pending_reusable_conns.emplace_back(c);
}
connection *Service::get_connection() {
connection *c;
if (!reusable_conns.empty()) {
c = reusable_conns.back();
reusable_conns.pop_back();
} else {
c = static_cast<connection *>(connections_allocators.Alloc(sizeof(connection)));
c->sentinel = reinterpret_cast<uintptr_t>(c);
}
c->gen = ++next_connection_generation; // it is important to pre-incement, NOT post-increment
c->fd = -1;
c->state.flags = 0;
c->type = connection::Type::UNKNOWN;
c->state.set_classsification(connection::ClassificationTracker::Type::NotClassified);
c->outQ = nullptr;
c->inB = nullptr;
c->classification.ll.reset();
c->connectionsList.reset();
allConnections.push_back(&c->connectionsList);
return c;
}
bool Service::expected_connest(connection *c) {
static constexpr bool trace{false};
if (c->is_consul() && c->as.consul.state == connection::As::Consul::State::Connecting) {
if (trace) {
SLog("Established new consul connnection\n");
}
c->state.flags &= ~(1u << unsigned(connection::State::Flags::NeedOutAvail)); // in case.
consul_state.srv.state = ConsulState::Srv::State::Available;
poller.set_data_events(c->fd, c, EPOLLIN);
cancel_timer(&c->as.consul.attached_timer.node);
consider_idle_consul_connection(c);
return true;
} else if (c->type == connection::Type::Consumer && c->as.consumer.state == connection::As::Consumer::State::Connecting) {
if (trace) {
SLog("Established new connection with a peer\n");
}
c->state.flags &= ~(1u << unsigned(connection::State::Flags::NeedOutAvail));
c->as.consumer.state = connection::As::Consumer::State::Idle;
poller.set_data_events(c->fd, c, EPOLLIN);
cancel_timer(&c->as.consumer.attached_timer.node);
consider_connected_consumer(c);
return true;
} else {
// Likely polling for socket send buffer availability
if (c->state.flags & (1u << unsigned(connection::State::Flags::NeedOutAvail))) {
if (trace) {
SLog("Got EPOLLOUT, was waiting for socket send buffer availability\n");
}
c->state.flags ^= (1u << unsigned(connection::State::Flags::NeedOutAvail));
} else {
if (trace) {
SLog("ODD: why are we here?\n");
}
}
poller.set_data_events(c->fd, c, EPOLLIN);
return false;
}
}
int Service::process_io(const int r, const uint64_t max_conn_gen) {
for (const auto it : poller.new_events(r)) {
auto ptr = it->data.ptr;
int fd = *reinterpret_cast<int *>(ptr);
if (ptr == &_interrupt_efd) {
uint64_t _c;
read(fd, &_c, sizeof(_c));
continue;
}
if (unlikely(-1 == fd)) {
continue;
}
if (ptr == &listenFd) {
if (const auto res = try_accept(fd)) {
return r;
}
continue;
}
if (ptr == &prom_listen_fd) {
if (const auto res = try_accept_prom(fd)) {
return r;
}
continue;
}
auto *const c = static_cast<connection *>(ptr);
if (unlikely(c->gen > max_conn_gen)) {
// this connection was created after epoll_wait() was invoked
// so the fact that we are processing I/O events about it here means that
// the connection was shut down after epoll_wait() (and possibly that
// this struct connection has been reused for another connection).
// Whatever the case, we must ignore whatever epoll events here for that connection
// because it's not the same connection as the one that was registered with epoll
continue;
}
if (unlikely(c->fd <= 2)) {
SLog("Unexpected fd ", c->fd, " for ", ptr_repr(c), "\n");
std::abort();
}
const auto events = it->events;
if (events & (EPOLLHUP | EPOLLERR)) {
shutdown(c);
continue;
}
c->verify();
// we are checking for EPOLLOUT first as opposed to checking events for
// EPOLLIN first, because this helps with connection::Type::Consumer connections
// where we need to check if the connection is established, and we do that in
// our impl. of expected_connest(), where we check if as.consumer.state == connection::As::Consumer::State::Connecting
// The problem with that is that expected_connest() checks state == connection::As::Consumer::State::Connecting, however
// once we connect to the peer it immediately pings us, so most of the time we get
// a EPOLLIN(because that ping arrived together with the handshake packets) and EPOLLOUT
// and when we check for EPOLLIN first, and wind up processing the peer response (ping)
// we then set the state to State::Idle because we have drained the input buffer
// so when, after processing EPOLLIN in the same loop iteration, we check for EPOLLOUT, the state
// is not Conecting so we don't ever think we connected.
if (events & EPOLLOUT) {
if (false == expected_connest(c)) {
if (!tx(c)) {
continue;
}
}
}
if (events & EPOLLIN) {
TANK_EXPECT(c->fd > 2);
try_recv(c);
}
}
return 0;
}
void Service::consider_connected_consumer(connection *c) {
static constexpr bool trace{false};
TANK_EXPECT(c);
TANK_EXPECT(c->type == connection::Type::Consumer);
auto peer = c->as.consumer.node;
std::unordered_set<cluster_node *> set{peer};
TANK_EXPECT(peer);
TANK_EXPECT(peer->consume_conn.ch.get() == c);
if (trace) {
SLog("Connection to peer ", peer->id, "@", peer->ep, " for replication has been established\n");
}
try_replicate_from(set);
}
void Service::consider_scheduled_consume_retries() {
static constexpr bool trace{false};
if (trace) {
SLog("Scheduled:", scheduled_consume_retries_list.size(), "\n");
}
while (!scheduled_consume_retries_list.empty()) {
auto n = switch_list_entry(cluster_node, consume_retry_ctx.ll, scheduled_consume_retries_list.prev);
if (const auto when = n->consume_retry_ctx.when; now_ms < when) {
scheduled_consume_retries_list_next = when;
return;
}
n->consume_retry_ctx.ll.detach_and_reset();
if (trace) {
SLog("Can now attempt to replicate from ", n->ep, ", remaining:", scheduled_consume_retries_list.size(), "\n");
}
try_replicate_from(n);
}
scheduled_consume_retries_list_next = std::numeric_limits<uint64_t>::max();
}
void Service::consider_idle_conns() {
// in reverse so that we consider the oldest idle connections before we consider the most recent ones
if (trace_idle) {
SLog("Considering ", idle_connections_count, " idle connections\n");
}
while (!idle_connections.empty()) {
auto c = switch_list_entry(connection, classification.ll, idle_connections.prev);
TANK_EXPECT(c->state.classification() == connection::ClassificationTracker::Type::Idle);
if (trace_idle) {
SLog("Connection ", ptr_repr(c), " idle for ", now_ms - c->classification.since, "\n");
}
if (now_ms - c->classification.since < idle_connection_ttl) {
// this and all other idle connections haven't been idle long enough
break;
}
shutdown(c);
}
}
bool Service::try_make_idle(connection *const c) {
if (c->outQ || c->inB) {
// pending data to transmit or data to process
// TODO: what do we do here? maybe we need to shutdown()
// otherwise, if we return false what will happen?
return false;
}
switch (c->type) {
case connection::Type::ConsulClient: {
switch (c->as.consul.state) {
case connection::As::Consul::State::Idle:
return true;
default:
return false;
}
} break;
default:
return true;
}
}
void Service::classify_active(connection *const c) {
TANK_EXPECT(c);
c->verify();
if (trace_classification) {
SLog(ansifmt::bold, ansifmt::color_blue, "ACTIVE:", ptr_repr(c), ansifmt::reset, "\n");
}
if (c->is_consul()) {
TANK_EXPECT(c->as.consul.conns_ll.empty());
c->classification.since = now_ms & (-128);
if (consul_state.active_conns.empty()) {
consul_state.active_conns_next_process_ts = c->classification.since + active_consul_connection_ttl;
}
consul_state.active_conns.push_back(&c->as.consul.conns_ll);
}
}
void Service::declassify_active(connection *const c) {
TANK_EXPECT(c);
c->verify();
TANK_EXPECT(c->state.classification() == connection::ClassificationTracker::Type::Active);
if (trace_classification) {
SLog(ansifmt::bold, ansifmt::color_blue, "-ACTIVE:", ptr_repr(c), ansifmt::reset, "\n");
}
if (c->is_consul()) {
TANK_EXPECT(!c->as.consul.conns_ll.empty());
c->as.consul.conns_ll.detach_and_reset();
if (consul_state.active_conns.empty()) {
consul_state.active_conns_next_process_ts = std::numeric_limits<uint64_t>::max();
} else {
auto c = switch_list_entry(connection, as.consul.conns_ll, consul_state.active_conns.prev);
const auto idle_time = now_ms - c->classification.since;
consul_state.active_conns_next_process_ts = now_ms + (active_consul_connection_ttl - idle_time);
}
}
}
bool Service::all_conns_idle() const {
if (false == consul_state.active_conns.empty()) {
// TODO: need a simple counter for all active tank client connections
return false;
}
return true;
}
void Service::declassify_long_polling(connection *const c) {
TANK_EXPECT(c);
TANK_EXPECT(c->is_consul());
c->verify();
TANK_EXPECT(false == c->classification.ll.empty());
TANK_EXPECT(c->state.classification() == connection::ClassificationTracker::Type::LongPolling);
if (trace_classification) {
SLog(ansifmt::bold, ansifmt::color_blue, "-LONG_POLLING:", ptr_repr(c), ansifmt::reset, "\n");
}
c->classification.ll.detach_and_reset();
}
void Service::classify_long_polling(connection *const c) {
TANK_EXPECT(c);
TANK_EXPECT(c->is_consul());
TANK_EXPECT(c->classification.ll.empty());
c->verify();
if (trace_classification) {
SLog(ansifmt::bold, ansifmt::color_blue, "-+LONG_POLLING:", ptr_repr(c), ansifmt::reset, "\n");
}
long_polling_conns.push_back(&c->classification.ll);
}
void Service::classify_idle(connection *const c, const size_t ref) {
TANK_EXPECT(c);
c->verify();
TANK_EXPECT(c->state.classification() != connection::ClassificationTracker::Type::Idle);
if (trace_classification) {
SLog(ansifmt::bold, ansifmt::color_blue, "IDLE:", ptr_repr(c), ansifmt::reset, " ", ref, "\n");
}
if (c->is_consul()) {
TANK_EXPECT(c->as.consul.conns_ll.empty());
consul_state.idle_conns.push_back(&c->as.consul.conns_ll);
}
// we will align down to 128ms
// so that we be checking for idle connections less frequently, even if we potentially
// need to shutdown a connection ~100ms earlier
c->classification.since = now_ms & (-128);
if (idle_connections.empty()) {
// first idle connection
next_idle_check_ts = c->classification.since + idle_connection_ttl;
if (trace_idle) {
SLog("Set next_idle_check_ts to ", next_idle_check_ts, "\n");
}
}
++idle_connections_count;
idle_connections.push_back(&c->classification.ll);
while (idle_connections_count > 64) {
auto c = switch_list_entry(connection, classification.ll, idle_connections.prev);
shutdown(c, __LINE__);
}
if (reactor_state == ReactorState::WaitAllConnsIdle && all_conns_idle()) {
reactor_state = ReactorState::Idle;
}
}
void Service::declassify_idle(connection *const c) {
TANK_EXPECT(c);
c->verify();
TANK_EXPECT(c->state.classification() == connection::ClassificationTracker::Type::Idle);
if (trace_classification) {
SLog(ansifmt::bold, ansifmt::color_blue, "-IDLE:", ptr_repr(c), ansifmt::reset, "\n");
}
if (c->is_consul()) {
// should have been tracked in consul_state.idle_conns
TANK_EXPECT(false == c->as.consul.conns_ll.empty());
c->as.consul.conns_ll.detach_and_reset();
}
TANK_EXPECT(false == c->classification.ll.empty());
TANK_EXPECT(idle_connections_count);
c->classification.ll.detach_and_reset();
--idle_connections_count;
if (idle_connections.empty()) {
next_idle_check_ts = std::numeric_limits<uint64_t>::max();
} else {
auto c = switch_list_entry(connection, classification.ll, idle_connections.prev);
const auto idle_time = now_ms - c->classification.since;
next_idle_check_ts = now_ms + (idle_connection_ttl - idle_time);
}
}
void Service::make_idle(connection *const c, const size_t ref) {
c->verify();
if (const auto cl = c->state.classification(); cl == connection::ClassificationTracker::Type::Idle) {
return;
} else if (cl == connection::ClassificationTracker::Type::LongPolling) {
declassify_long_polling(c);
} else if (cl == connection::ClassificationTracker::Type::Active) {
declassify_active(c);
}
classify_idle(c, ref);
c->state.set_classsification(connection::ClassificationTracker::Type::Idle);
}
void Service::make_active(connection *const c) {
c->verify();
if (const auto cl = c->state.classification(); cl == connection::ClassificationTracker::Type::Active) {
return;
} else if (cl == connection::ClassificationTracker::Type::LongPolling) {
declassify_long_polling(c);
} else if (cl == connection::ClassificationTracker::Type::Idle) {
declassify_idle(c);
}
classify_active(c);
c->state.set_classsification(connection::ClassificationTracker::Type::Active);
}
void Service::make_long_polling(connection *const c) {
TANK_EXPECT(c);
TANK_EXPECT(c->is_consul());
c->verify();
if (const auto cl = c->state.classification(); cl == connection::ClassificationTracker::Type::LongPolling) {
return;
} else if (cl == connection::ClassificationTracker::Type::Active) {
declassify_active(c);
} else if (cl == connection::ClassificationTracker::Type::Idle) {
declassify_idle(c);
}
classify_long_polling(c);
c->state.set_classsification(connection::ClassificationTracker::Type::LongPolling);
}
// attempt to shutdown upto `n` connections in order
// to reclaim resources, especially FDs
size_t Service::try_shutdown_idle(size_t n) {
static constexpr const bool trace{false};
const auto b = n;
if (trace) {
SLog("Require at least ", n, " more FDs, will try to shutdown among ", idle_connections.size(), " idle connections\n");
}
while (n && !idle_connections.empty()) {
auto c = switch_list_entry(connection, classification.ll, idle_connections.prev);
TANK_EXPECT(c->state.classification() == connection::ClassificationTracker::Type::Idle);
shutdown(c);
--n;
}
return b - n;
}
void Service::disable_listener() {
if (-1 == listenFd) {
return;
}
poller.erase(listenFd);
TANKUtil::safe_close(listenFd);
listenFd = -1;
}
bool Service::enable_listener() {
static constexpr bool trace{false};
struct sockaddr_in sa;
if (listenFd != -1) {
return true;
}
for (;;) {
listenFd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (-1 == listenFd) {
if ((ENFILE == errno || EMFILE == errno) && try_shutdown_idle(1)) {
continue;
} else {
if (trace) {
SLog("Unable to enable listener:", strerror(errno), "\n");
}
return false;
}
} else {
break;
}
}
memset(&sa, 0, sizeof(sa));
sa.sin_addr.s_addr = tank_listen_ep.addr4;
sa.sin_port = htons(tank_listen_ep.port);
sa.sin_family = AF_INET;
if (Switch::SetReuseAddr(listenFd, 1) == -1) {
Print("SO_REUSEADDR: ", strerror(errno), "\n");
TANKUtil::safe_close(listenFd);
listenFd = -1;
return false;
} else if (bind(listenFd, reinterpret_cast<sockaddr *>(&sa), sizeof(sa))) {
Print("bind() failed:", strerror(errno), "\n");
Print("Is there another TANK instance already running?\n");
TANKUtil::safe_close(listenFd);
listenFd = -1;
return false;
} else if (listen(listenFd, 512)) {
Print("listen() failed:", strerror(errno), "\n");
TANKUtil::safe_close(listenFd);
listenFd = -1;
return false;
}
// 2022-08-18
if (tank_listen_ep.addr4 != INADDR_ANY) {
listen_ep = tank_listen_ep;
} else {
struct sockaddr_in sa;
socklen_t sl = sizeof(sa);
if (-1 == getsockname(listenFd, reinterpret_cast<sockaddr *>(&sa), &sl)) {
IMPLEMENT_ME();
} else {
listen_ep.addr4 = *reinterpret_cast<const uint32_t *>(&sa.sin_addr.s_addr);
listen_ep.port = ntohs(sa.sin_port);
}
}
if (trace) {
SLog("Enabled listener\n");
}
poller.insert(listenFd, EPOLLIN, &listenFd);
return true;
}
bool Service::process_pending_signals(uint64_t mask) {
do {
const auto bit = mask & -mask;
if (bit == (1ull << SIGINT)) {
return false;
}
mask ^= bit;
} while (mask);
return true;
}
void Service::drain_pubsub_queue() {
if (auto it = mainThreadClosures.drain()) {
// we don't care about the order those closures are executed
// but we may as well reverse the list anyway
mainthread_closure *rh{nullptr};
while (it) {
auto t{it};
it = t->next;
t->next = rh;
rh = t;
}
do {
auto next = rh->next;
(*rh)();
delete rh;
rh = next;
} while (rh);
}
}
void Service::fire_timer(timer_node *const ctx) {
static constexpr bool trace = trace_timers;
//static constexpr bool trace = false;
if (trace) {
SLog(ansifmt::color_brown, "firing timer ", ptr_repr(&ctx->node), " ", unsigned(ctx->type), ansifmt::reset, "\n");
}
switch (ctx->type) {
case timer_node::ContainerType::TryBecomeClusterLeader: {
try_become_cluster_leader(__LINE__);
} break;
case timer_node::ContainerType::ShutdownConsumerConn: {
auto c = containerof(connection, as.consumer.attached_timer, ctx);
TANK_EXPECT(c);
TANK_EXPECT(c->type == connection::Type::Consumer);
c->verify();
SLog("Shutting down consumer connection\n");
shutdown(c);
} break;
case timer_node::ContainerType::ForceSetReactorStateIdle: {
reactor_state = ReactorState::Idle;
} break;
case timer_node::ContainerType::SchedConsulReq: {
auto req = containerof(consul_request, tn, ctx);
enqueue_consul_req(req);