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
|
#pragma once
#include "asio.h"
#include "poll_interrupter.h"
#include <library/cpp/neh/lfqueue.h>
#include <library/cpp/neh/pipequeue.h>
#include <library/cpp/dns/cache.h>
#include <util/generic/hash_set.h>
#include <util/network/iovec.h>
#include <util/network/pollerimpl.h>
#include <util/thread/lfqueue.h>
#include <util/thread/factory.h>
#ifdef DEBUG_ASIO
#define DBGOUT(args) Cout << args << Endl;
#else
#define DBGOUT(args)
#endif
namespace NAsio {
#if defined(_arm_)
template <typename T>
struct TLockFreeSequence {
Y_NO_INLINE T& Get(size_t n) {
with_lock (M) {
return H[n];
}
}
TMutex M;
THashMap<size_t, T> H;
};
#else
//TODO: copypaste from neh, - need fix
template <class T>
class TLockFreeSequence {
public:
inline TLockFreeSequence() {
memset((void*)T_, 0, sizeof(T_));
}
inline ~TLockFreeSequence() {
for (size_t i = 0; i < Y_ARRAY_SIZE(T_); ++i) {
delete[] T_[i];
}
}
inline T& Get(size_t n) {
const size_t i = GetValueBitCount(n + 1) - 1;
return GetList(i)[n + 1 - (((size_t)1) << i)];
}
private:
inline T* GetList(size_t n) {
T* volatile* t = T_ + n;
while (!*t) {
TArrayHolder<T> nt(new T[((size_t)1) << n]);
if (AtomicCas(t, nt.Get(), nullptr)) {
return nt.Release();
}
}
return *t;
}
private:
T* volatile T_[sizeof(size_t) * 8];
};
#endif
struct TOperationCompare {
template <class T>
static inline bool Compare(const T& l, const T& r) noexcept {
return l.DeadLine() < r.DeadLine() || (l.DeadLine() == r.DeadLine() && &l < &r);
}
};
//async operation, execute in contex TIOService()::Run() thread-executor
//usualy used for call functors/callbacks
class TOperation: public TRbTreeItem<TOperation, TOperationCompare>, public IHandlingContext {
public:
TOperation(TInstant deadline = TInstant::Max())
: D_(deadline)
, Speculative_(false)
, RequiredRepeatExecution_(false)
, ND_(deadline)
{
}
//register this operation in svc.impl.
virtual void AddOp(TIOService::TImpl&) = 0;
//return false, if operation not completed
virtual bool Execute(int errorCode = 0) = 0;
void ContinueUseHandler(TDeadline deadline) override {
RequiredRepeatExecution_ = true;
ND_ = deadline;
}
virtual void Finalize() = 0;
inline TInstant Deadline() const noexcept {
return D_;
}
inline TInstant DeadLine() const noexcept {
return D_;
}
inline bool Speculative() const noexcept {
return Speculative_;
}
inline bool IsRequiredRepeat() const noexcept {
return RequiredRepeatExecution_;
}
inline void PrepareReExecution() noexcept {
RequiredRepeatExecution_ = false;
D_ = ND_;
}
protected:
TInstant D_;
bool Speculative_; //if true, operation will be runned immediately after dequeue (even without wating any event)
//as sample used for optimisation writing, - obviously in buffers exist space for write
bool RequiredRepeatExecution_; //set to true, if required re-exec operation
TInstant ND_; //new deadline (for re-exec operation)
};
typedef TAutoPtr<TOperation> TOperationPtr;
class TNoneOperation: public TOperation {
public:
TNoneOperation(TInstant deadline = TInstant::Max())
: TOperation(deadline)
{
}
void AddOp(TIOService::TImpl&) override {
Y_ASSERT(0);
}
void Finalize() override {
}
};
class TPollFdEventHandler;
//descriptor use operation
class TFdOperation: public TOperation {
public:
enum TPollType {
PollRead,
PollWrite
};
TFdOperation(SOCKET fd, TPollType pt, TInstant deadline = TInstant::Max())
: TOperation(deadline)
, Fd_(fd)
, PT_(pt)
, PH_(nullptr)
{
Y_ASSERT(Fd() != INVALID_SOCKET);
}
inline SOCKET Fd() const noexcept {
return Fd_;
}
inline bool IsPollRead() const noexcept {
return PT_ == PollRead;
}
void AddOp(TIOService::TImpl& srv) override;
void Finalize() override;
protected:
SOCKET Fd_;
TPollType PT_;
public:
TAutoPtr<TPollFdEventHandler>* PH_;
};
typedef TAutoPtr<TFdOperation> TFdOperationPtr;
class TPollFdEventHandler {
public:
TPollFdEventHandler(SOCKET fd, TIOService::TImpl& srv)
: Fd_(fd)
, HandledEvents_(0)
, Srv_(srv)
{
}
virtual ~TPollFdEventHandler() {
Y_ASSERT(ReadOperations_.size() == 0);
Y_ASSERT(WriteOperations_.size() == 0);
}
inline void AddReadOp(TFdOperationPtr op) {
ReadOperations_.push_back(op);
}
inline void AddWriteOp(TFdOperationPtr op) {
WriteOperations_.push_back(op);
}
virtual void OnFdEvent(int status, ui16 filter) {
DBGOUT("PollEvent(fd=" << Fd_ << ", " << status << ", " << filter << ")");
if (status) {
ExecuteOperations(ReadOperations_, status);
ExecuteOperations(WriteOperations_, status);
} else {
if (filter & CONT_POLL_READ) {
ExecuteOperations(ReadOperations_, status);
}
if (filter & CONT_POLL_WRITE) {
ExecuteOperations(WriteOperations_, status);
}
}
}
typedef TVector<TFdOperationPtr> TFdOperations;
void ExecuteOperations(TFdOperations& oprs, int errorCode);
//return true if filter handled events changed and require re-configure events poller
virtual bool FixHandledEvents() noexcept {
DBGOUT("TPollFdEventHandler::FixHandledEvents()");
ui16 filter = 0;
if (WriteOperations_.size()) {
filter |= CONT_POLL_WRITE;
}
if (ReadOperations_.size()) {
filter |= CONT_POLL_READ;
}
if (Y_LIKELY(HandledEvents_ == filter)) {
return false;
}
HandledEvents_ = filter;
return true;
}
inline bool FinishOp(TFdOperations& oprs, TFdOperation* op) noexcept {
for (TFdOperations::iterator it = oprs.begin(); it != oprs.end(); ++it) {
if (it->Get() == op) {
FinishedOperations_.push_back(*it);
oprs.erase(it);
return true;
}
}
return false;
}
void DelOp(TFdOperation* op);
inline SOCKET Fd() const noexcept {
return Fd_;
}
inline ui16 HandledEvents() const noexcept {
return HandledEvents_;
}
inline void AddHandlingEvent(ui16 ev) noexcept {
HandledEvents_ |= ev;
}
inline void DestroyFinishedOperations() {
FinishedOperations_.clear();
}
TIOService::TImpl& GetServiceImpl() const noexcept {
return Srv_;
}
protected:
SOCKET Fd_;
ui16 HandledEvents_;
TIOService::TImpl& Srv_;
private:
TVector<TFdOperationPtr> ReadOperations_;
TVector<TFdOperationPtr> WriteOperations_;
// we can't immediatly destroy finished operations, this can cause closing used socket descriptor Fd_
// (on cascade deletion operation object-handler), but later we use Fd_ for modify handled events at poller,
// so we collect here finished operations and destroy it only after update poller, -
// call FixHandledEvents(TPollFdEventHandlerPtr&)
TVector<TFdOperationPtr> FinishedOperations_;
};
//additional descriptor for poller, used for interrupt current poll wait
class TInterrupterHandler: public TPollFdEventHandler {
public:
TInterrupterHandler(TIOService::TImpl& srv, TPollInterrupter& pi)
: TPollFdEventHandler(pi.Fd(), srv)
, PI_(pi)
{
HandledEvents_ = CONT_POLL_READ;
}
~TInterrupterHandler() override {
DBGOUT("~TInterrupterHandler");
}
void OnFdEvent(int status, ui16 filter) override;
bool FixHandledEvents() noexcept override {
DBGOUT("TInterrupterHandler::FixHandledEvents()");
return false;
}
private:
TPollInterrupter& PI_;
};
namespace {
inline TAutoPtr<IPollerFace> CreatePoller() {
try {
#if defined(_linux_)
return IPollerFace::Construct(TStringBuf("epoll"));
#endif
#if defined(_freebsd_) || defined(_darwin_)
return IPollerFace::Construct(TStringBuf("kqueue"));
#endif
} catch (...) {
Cdbg << CurrentExceptionMessage() << Endl;
}
return IPollerFace::Default();
}
}
//some equivalent TContExecutor
class TIOService::TImpl: public TNonCopyable {
public:
typedef TAutoPtr<TPollFdEventHandler> TEvh;
typedef TLockFreeSequence<TEvh> TEventHandlers;
class TTimer {
public:
typedef THashSet<TOperation*> TOperations;
TTimer(TIOService::TImpl& srv)
: Srv_(srv)
{
}
virtual ~TTimer() {
FailOperations(ECANCELED);
}
void AddOp(TOperation* op) {
THolder<TOperation> tmp(op);
Operations_.insert(op);
Y_UNUSED(tmp.Release());
Srv_.RegisterOpDeadline(op);
Srv_.IncTimersOp();
}
void DelOp(TOperation* op) {
TOperations::iterator it = Operations_.find(op);
if (it != Operations_.end()) {
Srv_.DecTimersOp();
delete op;
Operations_.erase(it);
}
}
inline void FailOperations(int ec) {
for (auto operation : Operations_) {
try {
operation->Execute(ec); //throw ?
} catch (...) {
}
Srv_.DecTimersOp();
delete operation;
}
Operations_.clear();
}
TIOService::TImpl& GetIOServiceImpl() const noexcept {
return Srv_;
}
protected:
TIOService::TImpl& Srv_;
THashSet<TOperation*> Operations_;
};
class TTimers: public THashSet<TTimer*> {
public:
~TTimers() {
for (auto it : *this) {
delete it;
}
}
};
TImpl()
: P_(CreatePoller())
, DeadlinesQueue_(*this)
{
}
~TImpl() {
TOperationPtr op;
while (OpQueue_.Dequeue(&op)) { //cancel all enqueued operations
try {
op->Execute(ECANCELED);
} catch (...) {
}
op.Destroy();
}
}
//similar TContExecutor::Execute() or io_service::run()
//process event loop (exit if none to do (no timers or event handlers))
void Run();
//enqueue functor fo call in Run() eventloop (thread safing)
inline void Post(TCompletionHandler h) {
class TFuncOperation: public TNoneOperation {
public:
TFuncOperation(TCompletionHandler completionHandler)
: TNoneOperation()
, H_(std::move(completionHandler))
{
Speculative_ = true;
}
private:
//return false, if operation not completed
bool Execute(int errorCode) override {
Y_UNUSED(errorCode);
H_();
return true;
}
TCompletionHandler H_;
};
ScheduleOp(new TFuncOperation(std::move(h)));
}
//cancel all current operations (handlers be called with errorCode == ECANCELED)
void Abort();
bool HasAbort() {
return AtomicGet(HasAbort_);
}
inline void ScheduleOp(TOperationPtr op) { //throw std::bad_alloc
Y_ASSERT(!Aborted_);
Y_ASSERT(!!op);
OpQueue_.Enqueue(op);
Interrupt();
}
inline void Interrupt() noexcept {
AtomicSet(NeedCheckOpQueue_, 1);
if (AtomicAdd(IsWaiting_, 0) == 1) {
I_.Interrupt();
}
}
inline void UpdateOpDeadline(TOperation* op) {
TInstant oldDeadline = op->Deadline();
op->PrepareReExecution();
if (oldDeadline == op->Deadline()) {
return;
}
if (oldDeadline != TInstant::Max()) {
op->UnLink();
}
if (op->Deadline() != TInstant::Max()) {
DeadlinesQueue_.Register(op);
}
}
inline size_t GetOpQueueSize() noexcept {
return OpQueue_.Size();
}
void SyncRegisterTimer(TTimer* t) {
Timers_.insert(t);
}
inline void SyncUnregisterAndDestroyTimer(TTimer* t) {
Timers_.erase(t);
delete t;
}
inline void IncTimersOp() noexcept {
++TimersOpCnt_;
}
inline void DecTimersOp() noexcept {
--TimersOpCnt_;
}
inline void WorkStarted() {
AtomicIncrement(OutstandingWork_);
}
inline void WorkFinished() {
if (AtomicDecrement(OutstandingWork_) == 0) {
Interrupt();
}
}
private:
void ProcessAbort();
inline TEvh& EnsureGetEvh(SOCKET fd) {
TEvh& evh = Evh_.Get(fd);
if (!evh) {
evh.Reset(new TPollFdEventHandler(fd, *this));
}
return evh;
}
inline void OnTimeoutOp(TOperation* op) {
DBGOUT("OnTimeoutOp");
try {
op->Execute(ETIMEDOUT); //throw ?
} catch (...) {
op->Finalize();
throw;
}
if (op->IsRequiredRepeat()) {
//operation not completed
UpdateOpDeadline(op);
} else {
//destroy operation structure
op->Finalize();
}
}
public:
inline void FixHandledEvents(TEvh& evh) {
if (!!evh) {
if (evh->FixHandledEvents()) {
if (!evh->HandledEvents()) {
DelEventHandler(evh);
evh.Destroy();
} else {
ModEventHandler(evh);
evh->DestroyFinishedOperations();
}
} else {
evh->DestroyFinishedOperations();
}
}
}
private:
inline TEvh& GetHandlerForOp(TFdOperation* op) {
TEvh& evh = EnsureGetEvh(op->Fd());
op->PH_ = &evh;
return evh;
}
void ProcessOpQueue() {
if (!AtomicGet(NeedCheckOpQueue_)) {
return;
}
AtomicSet(NeedCheckOpQueue_, 0);
TOperationPtr op;
while (OpQueue_.Dequeue(&op)) {
if (op->Speculative()) {
if (op->Execute(Y_UNLIKELY(Aborted_) ? ECANCELED : 0)) {
op.Destroy();
continue; //operation completed
}
if (!op->IsRequiredRepeat()) {
op->PrepareReExecution();
}
}
RegisterOpDeadline(op.Get());
op.Get()->AddOp(*this); // ... -> AddOp()
Y_UNUSED(op.Release());
}
}
inline void RegisterOpDeadline(TOperation* op) {
if (op->DeadLine() != TInstant::Max()) {
DeadlinesQueue_.Register(op);
}
}
public:
inline void AddOp(TFdOperation* op) {
DBGOUT("AddOp<Fd>(" << op->Fd() << ")");
TEvh& evh = GetHandlerForOp(op);
if (op->IsPollRead()) {
evh->AddReadOp(op);
EnsureEventHandled(evh, CONT_POLL_READ);
} else {
evh->AddWriteOp(op);
EnsureEventHandled(evh, CONT_POLL_WRITE);
}
}
private:
inline void EnsureEventHandled(TEvh& evh, ui16 ev) {
if (!evh->HandledEvents()) {
evh->AddHandlingEvent(ev);
AddEventHandler(evh);
} else {
if ((evh->HandledEvents() & ev) == 0) {
evh->AddHandlingEvent(ev);
ModEventHandler(evh);
}
}
}
public:
//cancel all current operations for socket
//method MUST be called from Run() thread-executor
void CancelFdOp(SOCKET fd) {
TEvh& evh = Evh_.Get(fd);
if (!evh) {
return;
}
OnFdEvent(evh, ECANCELED, CONT_POLL_READ | CONT_POLL_WRITE);
}
private:
//helper for fixing handled events even in case exception
struct TExceptionProofFixerHandledEvents {
TExceptionProofFixerHandledEvents(TIOService::TImpl& srv, TEvh& iEvh)
: Srv_(srv)
, Evh_(iEvh)
{
}
~TExceptionProofFixerHandledEvents() {
Srv_.FixHandledEvents(Evh_);
}
TIOService::TImpl& Srv_;
TEvh& Evh_;
};
inline void OnFdEvent(TEvh& evh, int status, ui16 filter) {
TExceptionProofFixerHandledEvents fixer(*this, evh);
Y_UNUSED(fixer);
evh->OnFdEvent(status, filter);
}
inline void AddEventHandler(TEvh& evh) {
if (evh->Fd() > MaxFd_) {
MaxFd_ = evh->Fd();
}
SetEventHandler(&evh, evh->Fd(), evh->HandledEvents());
++FdEventHandlersCnt_;
}
inline void ModEventHandler(TEvh& evh) {
SetEventHandler(&evh, evh->Fd(), evh->HandledEvents());
}
inline void DelEventHandler(TEvh& evh) {
SetEventHandler(&evh, evh->Fd(), 0);
--FdEventHandlersCnt_;
}
inline void SetEventHandler(void* h, int fd, ui16 flags) {
DBGOUT("SetEventHandler(" << fd << ", " << flags << ")");
P_->Set(h, fd, flags);
}
//exception safe call DelEventHandler
struct TInterrupterKeeper {
TInterrupterKeeper(TImpl& srv, TEvh& iEvh)
: Srv_(srv)
, Evh_(iEvh)
{
Srv_.AddEventHandler(Evh_);
}
~TInterrupterKeeper() {
Srv_.DelEventHandler(Evh_);
}
TImpl& Srv_;
TEvh& Evh_;
};
TAutoPtr<IPollerFace> P_;
TPollInterrupter I_;
TAtomic IsWaiting_ = 0;
TAtomic NeedCheckOpQueue_ = 0;
TAtomic OutstandingWork_ = 0;
NNeh::TAutoLockFreeQueue<TOperation> OpQueue_;
TEventHandlers Evh_; //i/o event handlers
TTimers Timers_; //timeout event handlers
size_t FdEventHandlersCnt_ = 0; //i/o event handlers counter
size_t TimersOpCnt_ = 0; //timers op counter
SOCKET MaxFd_ = 0; //max used descriptor num
TAtomic HasAbort_ = 0;
bool Aborted_ = false;
class TDeadlinesQueue {
public:
TDeadlinesQueue(TIOService::TImpl& srv)
: Srv_(srv)
{
}
inline void Register(TOperation* op) {
Deadlines_.Insert(op);
}
TInstant NextDeadline() {
TDeadlines::TIterator it = Deadlines_.Begin();
while (it != Deadlines_.End()) {
if (it->DeadLine() > TInstant::Now()) {
DBGOUT("TDeadlinesQueue::NewDeadline:" << (it->DeadLine().GetValue() - TInstant::Now().GetValue()));
return it->DeadLine();
}
TOperation* op = &*(it++);
Srv_.OnTimeoutOp(op);
}
return Deadlines_.Empty() ? TInstant::Max() : Deadlines_.Begin()->DeadLine();
}
private:
typedef TRbTree<TOperation, TOperationCompare> TDeadlines;
TDeadlines Deadlines_;
TIOService::TImpl& Srv_;
};
TDeadlinesQueue DeadlinesQueue_;
};
}
|