-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathclient_reactor.cpp
1184 lines (936 loc) · 42.6 KB
/
client_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 "client_common.h"
#ifdef HAVE_NETIO_THROTTLE
void TankClient::throttle_read(connection *c, const uint64_t expiration) {
static constexpr bool trace{false};
if (!c->throttler.read.ll.empty()) {
c->throttler.read.ll.detach_and_reset();
}
if (c->state.flags & (1u << static_cast<uint8_t>(connection::State::Flags::NeedOutAvail))) {
if (trace) {
SLog(ansifmt::color_blue, ansifmt::bgcolor_red, "Throttle read: EPOLLOUT", ansifmt::reset, "\n");
}
poller.set_data_events(c->fd, c, EPOLLOUT);
} else {
if (trace) {
SLog(ansifmt::color_blue, ansifmt::bgcolor_red, "Throttle read: 0 for ", expiration - now_ms, ansifmt::reset, "\n");
}
poller.set_data_events(c->fd, c, 0);
}
c->throttler.read.until = expiration;
throttled_connections_read_list_next = std::min(c->throttler.read.until, throttled_connections_read_list_next);
throttled_connections_read_list.push_back(&c->throttler.read.ll);
TANK_EXPECT(throttled_connections_read_list.empty() == false);
}
void TankClient::throttle_write(connection *c, const uint64_t expiration) {
static constexpr bool trace{false};
if (!c->throttler.write.ll.empty()) {
c->throttler.write.ll.detach_and_reset();
}
if (trace) {
SLog(ansifmt::color_blue, ansifmt::bgcolor_red, "Throttle write", ansifmt::reset, "\n");
}
stop_poll_outavail(c);
c->throttler.write.until = expiration;
throttled_connections_write_list_next = std::min(c->throttler.write.until, throttled_connections_write_list_next);
throttled_connections_write_list.push_back(&c->throttler.write.ll);
}
void TankClient::manage_throttled_connections() {
static constexpr bool trace{false};
if (trace) {
SLog(ansifmt::inverse, ansifmt::color_blue, "Managing:", throttled_connections_read_list.size(), " ", throttled_connections_write_list.size(), ansifmt::reset, "\n");
}
throttled_connections_read_list_next = std::numeric_limits<uint64_t>::max();
while (!throttled_connections_read_list.empty()) {
auto it = throttled_connections_read_list.prev;
auto c = switch_list_entry(connection, throttler.read.ll, it);
auto prev = it->prev;
if (const auto when = c->throttler.read.until; when > now_ms) {
throttled_connections_read_list_next = when;
goto l1;
}
if (c->state.flags & (1u << static_cast<uint8_t>(connection::State::Flags::NeedOutAvail))) {
if (trace) {
SLog("No longer throttling read (EPOLLIN|EPOLLOUT)\n");
}
poller.set_data_events(c->fd, c, EPOLLIN | EPOLLOUT);
} else {
if (trace) {
SLog("No longer throttling read (EPOLLIN)\n");
}
poller.set_data_events(c->fd, c, EPOLLIN);
}
c->throttler.read.ll.detach_and_reset();
rcv(c);
it = prev;
}
l1:
throttled_connections_write_list_next = std::numeric_limits<uint64_t>::max();
while (!throttled_connections_write_list.empty()) {
auto it = throttled_connections_write_list.prev;
auto c = switch_list_entry(connection, throttler.write.ll, it);
auto prev = it->prev;
if (const auto when = c->throttler.write.until; when > now_ms) {
throttled_connections_write_list_next = when;
return;
}
if (trace) {
SLog("No longer throttling write\n");
}
poll_outavail(c);
c->throttler.write.ll.detach_and_reset();
it = prev;
}
}
#endif
void TankClient::poll_outavail(connection *const c) {
const auto new_flags = c->state.flags | (1u << static_cast<uint8_t>(connection::State::Flags::NeedOutAvail));
if (c->state.flags != new_flags) {
c->state.flags = new_flags;
#ifdef HAVE_NETIO_THROTTLE
if (c->throttler.read.ll.empty()) {
poller.set_data_events(c->fd, c, EPOLLIN | EPOLLOUT);
} else {
poller.set_data_events(c->fd, c, EPOLLOUT);
}
#else
poller.set_data_events(c->fd, c, EPOLLIN | EPOLLOUT);
#endif
}
}
void TankClient::stop_poll_outavail(connection *const c) {
const auto new_flags = c->state.flags & ~(1u << static_cast<uint8_t>(connection::State::Flags::NeedOutAvail));
if (c->state.flags != new_flags) {
c->state.flags = new_flags;
#ifdef HAVE_NETIO_THROTTLE
if (c->throttler.read.ll.empty()) {
poller.set_data_events(c->fd, c, EPOLLIN);
} else {
poller.set_data_events(c->fd, c, 0);
}
#else
poller.set_data_events(c->fd, c, EPOLLIN);
#endif
}
}
bool TankClient::tx(connection *c) {
TANK_EXPECT(c);
TANK_EXPECT(c->fd != -1);
switch (c->type) {
case connection::Type::Tank:
return tx_tank(c);
default:
IMPLEMENT_ME();
}
}
bool TankClient::materialize_next_broker_req_payload([[maybe_unused]] broker *br) {
// we no longer lazilily materialize broker_api_request's
return false;
}
#ifdef HAVE_NETIO_THROTTLE
constexpr size_t throttle_write_size() {
return 8;
}
constexpr size_t throttle_read_size() {
return 256;
}
constexpr uint32_t throttle_span() {
return 500;
}
#endif
bool TankClient::tx_tank(connection *const c) {
enum {
trace = false,
};
auto fd = c->fd;
auto br = c->as.tank.br; // associated broker
// TODO: https://github.com/phaistos-networks/TANK/issues/76
// - fast-path for a single outgoing content payload
// - track payload size so that we can avoid iterating the iovecs
TANK_EXPECT(br);
TANK_EXPECT(c->fd != -1);
struct iovec iov[128], *const out_end = iov + sizeof_array(iov);
auto index = br->outgoing_content.front_payload_iovecs_index;
if (trace) {
SLog("Attempting to send, index = ", index,
", any:", br->outgoing_content.front() != nullptr, "\n");
}
for (;;) {
auto out = iov;
auto _i = index;
size_t sum{0};
for (auto it = br->outgoing_content.front(); out < out_end; it = it->next, _i = 0) {
if (!it) {
// we may still have requests pending materialization
// lazy materialization offers some important benefits
// also, notice how we use set_any_transferred(), so that
// even if a single byte of broker request payload has been scheduled for transmission
// we will know
if (!materialize_next_broker_req_payload(br)) {
if (trace) {
SLog("No more broker requests to materialize\n");
}
break;
}
if (trace) {
SLog("Materialized broker request\n");
}
it = br->outgoing_content.front();
}
TANK_EXPECT(it);
#ifdef HAVE_NETIO_THROTTLE
const auto n = std::min<size_t>(std::distance(out, out_end), it->iovecs.size - _i);
for (const auto *p = it->iovecs.data + _i, *const e = p + n; p < e; ++p) {
const auto l = p->iov_len;
if (sum + l <= throttle_write_size()) {
sum += l;
*out++ = *p;
} else {
*out++ = {p->iov_base, throttle_write_size() - sum};
break;
}
}
#else
const auto n = std::min<size_t>(std::distance(out, out_end), it->iovecs.size - _i);
if (trace) {
SLog("For payload size = ", it->iovecs.size, "\n");
}
for (const auto *p = it->iovecs.data + _i, *const e = p + n; p < e; ++p) {
sum += p->iov_len;
}
memcpy(out, it->iovecs.data + _i, n * sizeof(struct iovec));
out += n;
#endif
}
if (out == iov) {
if (trace) {
SLog("Nothing to send\n");
}
return true;
}
l10:
auto r = writev(fd, iov, std::distance(iov, out));
if (trace) {
SLog("writev() for ", std::distance(iov, out), " ", r, " c = ", ptr_repr(c), "\n");
}
if (-1 == r) {
if (EINTR == errno) {
goto l10;
} else if (EAGAIN == errno) {
br->outgoing_content.front_payload_iovecs_index = index;
poll_outavail(c);
return true;
} else {
switch (errno) {
case EIO:
break;
default:
Print("Unexpected, writev() failed with ", strerror(errno), "\n");
std::abort();
}
if (trace) {
SLog("Got:", strerror(errno), "\n");
}
return shutdown(c, __LINE__);
}
}
// if we wrote as much as we needed, then
// it's likely the socket buffer's not full, otherwise if it only
// could keep some of the data it's almost certainly going to be full
// if we writev() again
#ifdef HAVE_NETIO_THROTTLE
constexpr bool try_again = false;
#else
const auto try_again = r == sum;
#endif
auto it = br->outgoing_content.front();
iovec *ptr;
size_t len;
if (trace) {
SLog("Got r(", r, ") out of sum(", sum, ") try_again(", try_again, ")\n");
}
next_payload:
while (r >= (len = (ptr = it->iovecs.data + index)->iov_len)) {
r -= len;
if (++index == it->iovecs.size) {
const auto next = it->next;
auto broker_req = it->broker_req;
TANK_EXPECT(broker_req->have_payload);
broker_req->have_payload = false;
// we need to track the dispatched requests
// so that flush_broker() can deal with those requests as opposed
// to only relying on them to time out
br->pending_responses_list.push_back(&broker_req->pending_responses_list_ll);
TANK_EXPECT(false == br->pending_responses_list.empty());
if (trace) {
SLog(ansifmt::color_brown, ansifmt::bgcolor_blue,
"Payload dispatched for ID:", broker_req->id, ")", ansifmt::reset, "\n");
}
br->outgoing_content.pop_front();
// we used to retain payloads in case we wanted to retry
// a request. We no longer do that for simplicity reasons.
// it's cheap to rebuild a payload anyway
put_payload(it, __LINE__);
br->outgoing_content.first_payload_partially_transferred = false;
if (next) {
it = next;
index = 0;
goto next_payload;
} else {
// done
if (trace) {
SLog("Done for fd ", fd, " for connection ", ptr_repr(c), "\n");
}
br->outgoing_content.front_payload_iovecs_index = 0;
stop_poll_outavail(c);
return true;
}
}
}
TANK_EXPECT(it->broker_req->have_payload);
br->outgoing_content.first_payload_partially_transferred = true;
ptr->iov_len -= r;
ptr->iov_base = static_cast<char *>(ptr->iov_base) + r;
if (try_again) {
TANK_EXPECT(false == br->outgoing_content.empty());
continue;
} else {
br->outgoing_content.front_payload_iovecs_index = index;
#ifdef HAVE_NETIO_THROTTLE
throttle_write(c, now_ms + throttle_span());
#else
poll_outavail(c);
#endif
return true;
}
}
}
bool TankClient::any_requests_pending_delivery() const noexcept {
// XXX: this is not optimal, but given how and when it's meant to be used, that's OK
for (auto &it : brokers) {
auto br = it.second.get();
if (!br->outgoing_content.empty()) {
return true;
}
}
#if 0 // turns out, this is not necessary
for (auto it = all_conns_list.next; it != &all_conns_list; it = it->next) {
const auto c = containerof(connection, all_conns_list_ll, it);
if (c->state.flags & (1u << unsigned(connection::State::Flags::ConnectionAttempt))) {
return true;
}
}
#endif
return false;
}
bool TankClient::process_srv_in(connection *const c) {
static constexpr bool trace{false};
TANK_EXPECT(c);
TANK_EXPECT(c->type == connection::Type::Tank);
auto b = c->in.b;
TANK_EXPECT(b);
TANK_EXPECT(b->use_count());
#ifdef TANK_CLIENT_FAST_CONSUME
if (c->as.tank.flags & (1u << unsigned(connection::As::Tank::Flags::InterleavedRespAssembly))) {
if (!process_consume_content(c)) {
return false;
} else if (c->as.tank.cur_resp.state == connection::As::Tank::Response::State::Ready) {
c->as.tank.flags &= ~(1u << unsigned(connection::As::Tank::Flags::InterleavedRespAssembly));
} else {
return true;
}
}
#endif
auto base = reinterpret_cast<const uint8_t *>(b->data());
const auto b_size = b->size();
const auto *p = base + b->offset();
const auto *e = base + b_size;
for (;;) {
TANK_EXPECT(p <= e);
if (unlikely(p + sizeof(uint8_t) + sizeof(uint32_t) > e)) {
break;
}
const auto msg = decode_pod<uint8_t>(p);
const auto len = decode_pod<uint32_t>(p);
if (trace) {
SLog(ansifmt::color_brown, ansifmt::inverse, "msg = ", msg, ", len = ", len, ansifmt::reset, "\n");
}
if (0 == (c->as.tank.flags & (1u << static_cast<uint8_t>(connection::As::Tank::Flags::ConsideredReqHeader)))) {
// haven't considered the request header yet
TANK_EXPECT(p <= e);
const auto offset = std::distance(base, p);
if (trace) {
SLog("Not Considered Req Yet\n");
}
if (!b->is_locked()) {
// well, we can't do jack shit here
b->reserve(len + offset + 16);
base = reinterpret_cast<const uint8_t *>(b->data());
p = base + offset;
e = base + b_size;
TANK_EXPECT(p <= e);
}
c->as.tank.flags |= (1u << static_cast<uint8_t>(connection::As::Tank::Flags::ConsideredReqHeader));
}
#ifdef TANK_CLIENT_FAST_CONSUME
// we 'll try to
if (msg == uint8_t(TankAPIMsgType::Consume)) {
static constexpr bool trace{false};
const auto cur_offset = std::distance(const_cast<const char *>(b->data()), reinterpret_cast<const char *>(p));
b->set_offset(cur_offset);
c->as.tank.cur_resp.reset();
c->as.tank.cur_resp.resp_end_offset = cur_offset + len;
c->as.tank.flags |= 1u << unsigned(connection::As::Tank::Flags::InterleavedRespAssembly);
if (trace) {
SLog("************ CONSUME *******************:", c->as.tank.cur_resp.resp_end_offset, " (cur_offset = ", cur_offset, ", b->size() = ", b->size(), ")\n");
}
if (!process_consume_content(c)) {
return false;
} else if (c->as.tank.cur_resp.state == connection::As::Tank::Response::State::Ready) {
// we are done, see if we have more responses we can process
p = base + b->offset();
e = base + b->size();
c->as.tank.flags &= ~(1u << unsigned(connection::As::Tank::Flags::InterleavedRespAssembly));
if (trace) {
SLog("We are done (READY) remaining ", std::distance(p, e), "\n");
}
continue;
} else {
if (trace) {
SLog("Need more content\n");
}
return true;
}
}
#endif
TANK_EXPECT(p <= e);
if (p + len > e) {
if (trace) {
SLog("Need more content, msg.size = ", len, ", have now ", std::distance(p, e), "\n");
if (c->type == connection::Type::Tank && c->as.tank.br) {
SLog("Broker ", ptr_repr(c->as.tank.br), " ", c->as.tank.br->ep, " pending_responses ", c->as.tank.br->pending_responses_list.size(), "\n");
}
}
return true;
}
c->as.tank.flags &= ~(1u << static_cast<uint8_t>(connection::As::Tank::Flags::ConsideredReqHeader));
if (trace) {
SLog(ansifmt::bold, ansifmt::color_red, "PROCESSING ", len, ansifmt::reset, "\n");
}
if (!process_msg(c, msg, p, len)) {
return false;
}
p += len;
TANK_EXPECT(p <= e);
b->set_offset(reinterpret_cast<const char *>(p));
}
if (auto b = c->in.b) {
const auto offset = b->offset();
const auto size = b->size();
if (offset == size) {
if (trace) {
SLog("Can release b (", ptr_repr(p), ", rc = ", b->use_count(), ")\n");
}
release_mb(b);
c->in.b = nullptr;
} else if (!b->is_locked()) {
if (trace) {
SLog("Not Locked, will delete prefix of length ", offset, "\n");
}
b->erase_chunk(0, offset);
b->set_offset(static_cast<uint32_t>(0));
} else if (trace) {
SLog("Locked\n");
}
}
return true;
}
bool TankClient::rcv(connection *const c) {
enum {
trace = false,
};
TANK_EXPECT(c);
int fd = c->fd, n;
managed_buf *b;
TANK_EXPECT(fd != -1);
if (unlikely(-1 == ioctl(fd, FIONREAD, &n))) {
Print("ioctl() failed:", strerror(errno), " for ", fd, " c ", ptr_repr(c), "\n");
std::abort();
}
if ((b = c->in.b)) {
if (const auto available = b->capacity() - b->size(); available < n && b->is_locked()) {
// we can't modfy this because other users depend on it
// so geta new managed buffer and copy whatever extra we had
// in the previous buffer to it, and then
// assign that new buffer to this connection
auto nb = get_managed_buffer();
TANK_EXPECT(nb);
if (const auto rem = b->size() - b->offset()) {
TANK_EXPECT(b->data());
nb->serialize(reinterpret_cast<int8_t *>(b->data() + b->offset()), rem);
b->length -= rem;
}
release_mb(b);
b = c->in.b = nb;
TANK_EXPECT(b->is_locked() == false);
TANK_EXPECT(b->use_count() == 1);
}
} else {
b = c->in.b = get_managed_buffer();
}
#ifdef HAVE_NETIO_THROTTLE
n = std::min<int>(n, throttle_read_size());
#endif
// this is really mostly about HAVE_NETIO_THROTTLE
// but regardless, we don't want to pass 0 to read()
const auto actual = n + 1;
b->reserve(b->size() + actual);
if (const auto r = read(fd, b->data() + b->size(), actual); - 1 == r) {
if (EINTR == errno or EAGAIN == errno) {
return true;
} else {
return shutdown(c, __LINE__);
}
} else if (0 == r) {
// peer went away
return shutdown(c, __LINE__);
} else {
if (trace) {
SLog("Read:", r, " from ", fd, "\n");
}
b->length += r;
}
#ifdef HAVE_NETIO_THROTTLE
throttle_read(c, throttle_span() + now_ms);
#endif
switch (c->type) {
case connection::Type::Tank:
return process_srv_in(c);
default:
IMPLEMENT_ME();
}
}
void TankClient::begin_reactor_loop_iteration() {
// Reset state / buffers used for tracking collected content and responses in last poll() call
[[maybe_unused]] static constexpr bool trace{false};
gc_ready_responses();
all_captured_faults.clear();
all_discovered_partitions.clear();
_discovered_topologies.clear();
all_discovered_topics.clear();
reload_conf_results_v.clear();
consumed_content.clear();
produce_acks_v.clear();
created_topics_v.clear();
collected_cluster_status_v.clear();
}
void TankClient::drain_pipe(int fd) {
int n;
char buf[512];
if (unlikely(ioctl(fd, FIONREAD, &n) == -1)) {
throw Switch::system_error("ioctl() failed:", strerror(errno));
} else if (unlikely(!n)) {
// Just in case we get 0; if we do, read() will fail with EAGAIN anyway
// We shouldn't get n == 0 but let's be on the safe side
n = sizeof(buf);
}
do {
const auto r = read(fd, buf, sizeof(buf));
if (r == -1) {
if (errno != EAGAIN && errno != EINTR) {
throw Switch::system_error("Unable to drain pipe:", strerror(errno));
} else {
break;
}
} else if (!r) {
break;
} else {
n -= r;
}
} while (n);
}
bool TankClient::process_io(const size_t events_count) {
enum {
trace = false,
};
bool interrupted = false;
if (trace) {
SLog("Events ", events_count, "\n");
}
for (const auto it : poller.new_events(events_count)) {
const auto events = it->events;
auto *const c = static_cast<connection *>(it->data.ptr);
if (c->fd == interrupt_fd) {
// someone woke us up
uint64_t one;
read(c->fd, &one, sizeof(one));
interrupted = true;
continue;
}
// POLLHUP: no longer connected; in TCP, FIN has been received
// POLLERR: socket got an async. error. In TCP, typically means an RST has been received or sent.
if (events & (EPOLLERR | EPOLLHUP)) {
shutdown(c, __LINE__);
continue;
}
if (events & EPOLLOUT) {
if (c->state.flags & (1u << unsigned(connection::State::Flags::ConnectionAttempt))) {
if (trace) {
SLog("Connection was established\n");
}
if (c->type == connection::Type::Tank) {
// whenever we manage to connect, we
// decrement the tracked consequtive connection failures by 2(as opposed to resetting it to 0)
auto br = c->as.tank.br;
TANK_EXPECT(br);
br->set_reachability(broker::Reachability::LikelyReachable, __LINE__);
br->consequtive_connection_failures -= std::min<size_t>(2, br->consequtive_connection_failures);
if (br->unreachable_brokers_tree_node.node.leaf_p) {
eb64_delete(&br->unreachable_brokers_tree_node);
unreachable_brokers_tree_next = eb_is_empty(&unreachable_brokers_tree)
? std::numeric_limits<uint64_t>::max()
: eb64_first(&unreachable_brokers_tree)->key;
TANK_EXPECT(br->unreachable_brokers_tree_node.node.leaf_p == nullptr);
}
}
c->list.detach_and_reset();
conns_pend_est_next_expiration = conns_pend_est_list.empty()
? std::numeric_limits<uint64_t>::max()
: switch_list_entry(connection, list, conns_pend_est_list.prev)->expiration;
c->state.flags &= ~((1u << uint8_t(connection::State::Flags::ConnectionAttempt)) | (1u << uint8_t(connection::State::Flags::NeedOutAvail)));
poller.set_data_events(c->fd, c, EPOLLIN);
}
if (!tx(c)) {
continue;
}
}
// it's important that we check for EPOLLOUT before we check for EPOLLIN
// see Service::process_io()
if (events & EPOLLIN) {
rcv(c);
}
}
return interrupted;
}
void TankClient::check_conns_pending_est() {
static constexpr bool trace{false};
while (!conns_pend_est_list.empty()) {
auto c = switch_list_entry(connection, list, conns_pend_est_list.prev);
const auto exp = c->expiration;
if (exp > now_ms) {
conns_pend_est_next_expiration = exp;
break;
}
if (trace) {
SLog("Too long to establish connection\n");
}
shutdown(c, __LINE__);
}
conns_pend_est_next_expiration = std::numeric_limits<uint64_t>::max();
}
void TankClient::wakeup_unreachable_broker(broker *br) {
static constexpr bool trace{false};
TANK_EXPECT(br);
TANK_EXPECT(br->unreachable_brokers_tree_node.node.leaf_p == nullptr);
br->consequtive_connection_failures =
std::min<uint8_t>(br->consequtive_connection_failures,
broker::max_consequtive_connection_failures - 1);
if (trace) {
SLog("Waking up unreachable broker ", br->ep, "\n");
}
if (br->outgoing_content.empty()) {
// this could happen e.g if
// all requests were timed out by the time we got to wake this up
if (trace) {
SLog("No outgoing content\n");
}
return;
}
if (!try_transmit(br)) {
// XXX: it's OK
}
}
void TankClient::check_unreachable_brokers() {
eb64_node *it;
goto l1;
for (;;) {
if (!it) {
l1:
it = eb64_first(&unreachable_brokers_tree);
if (!it) {
unreachable_brokers_tree_next = std::numeric_limits<uint64_t>::max();
return;
}
}
if (const auto key = it->key; key > now_ms) {
unreachable_brokers_tree_next = key;
return;
}
auto br = eb64_entry(it, broker, unreachable_brokers_tree_node);
auto next = eb64_next(it);
eb64_delete(it);
wakeup_unreachable_broker(br);
it = next;
}
}
uint64_t TankClient::reactor_next_wakeup() const noexcept {
enum {
trace = false,
};
uint64_t until = TANKUtil::minimum(
unreachable_brokers_tree_next,
retry_bundles_next,
conns_pend_est_next_expiration,
api_reqs_expirations_tree_next);
#ifdef HAVE_NETIO_THROTTLE
until = TANKUtil::minimum(until,
throttled_connections_read_list_next,
throttled_connections_write_list_next);
#endif
return until;
}
void TankClient::reactor_step(uint32_t timeout_ms) {
now_ms = Timings::Milliseconds::Tick();
begin_reactor_loop_iteration();
const auto step_end = now_ms + timeout_ms;
// instead of polling once, we are now going
// to poll (and thus, consume incoming packets)
// until we either timeout or we have any_responses()
//
// this makes a lot of sense, and also avoid excessive calls to
// TankClient::poll()
for (;;) {
const auto until = std::min(step_end, reactor_next_wakeup());
sleeping.store(true, std::memory_order_relaxed);
const auto r = poller.poll(likely(until >= now_ms) ? until - now_ms : 0);
const auto saved_erro = errno;
bool interrupted = false;
sleeping.store(false, std::memory_order_relaxed);
now_ms = Timings::Milliseconds::Tick();
if (now_ms > next_curtime_update) {
const auto _now = time(nullptr);
if (unlikely(_now == ((time_t)-1))) {
IMPLEMENT_ME();
}
cur_time = _now;
next_curtime_update = now_ms + 500;
}
if (unlikely(-1 == r)) {
if (saved_erro == EINTR) {
interrupted = true;
} else if (saved_erro != EAGAIN) {
throw Switch::system_error("epoll_wait()");
}
} else if (r) {
interrupted = process_io(r);
}
if (now_ms >= conns_pend_est_next_expiration) {
check_conns_pending_est();
}
if (now_ms >= api_reqs_expirations_tree_next) {
check_pending_api_responses();
}
if (now_ms >= retry_bundles_next) {
check_pending_retries();
}
if (now_ms >= unreachable_brokers_tree_next) {
check_unreachable_brokers();
}
#ifdef HAVE_NETIO_THROTTLE
if (now_ms >= throttled_connections_read_list_next ||
now_ms >= throttled_connections_write_list_next) {
manage_throttled_connections();
}
#endif
if (interrupted) {
break;
}
if (0 == r) {
if (now_ms >= step_end) {
// OK, waited too long
break;
} else {
// no I/O, but likely a timer fired
// we haven't exceeded our allowed time to poll for I/O though so we 'll poll again
}
} else if (any_responses()) {
// we got something
break;
} else if (-1 == r and errno == EINTR) {
// interrupted
break;
}
}
end_reactor_loop_iteration();
}
void TankClient::check_pending_retries() {
eb64_node *it;
goto l1;
for (;;) {
if (!it) {
l1:
it = eb64_first(&retry_bundles_ebt_root);
if (!it) {
retry_bundles_next = std::numeric_limits<uint64_t>::max();
return;
}
}
if (const auto key = it->key; key > now_ms) {
retry_bundles_next = key;
return;
}
auto rb = eb64_entry(it, retry_bundle, node);
auto next = eb64_next(it);
eb64_delete(it);
retry_bundle_impl(rb);
it = next;
}
}
void TankClient::end_reactor_loop_iteration() {
// for now, no-op
}