-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mainloop.cpp
1755 lines (1498 loc) · 51.8 KB
/
mainloop.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
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2013-2023 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <[email protected]>
//
// This file is part of p44utils.
//
// p44utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44utils. If not, see <http://www.gnu.org/licenses/>.
//
// File scope debugging options
// - Set ALWAYS_DEBUG to 1 to enable DBGLOG output even in non-DEBUG builds of this file
#define ALWAYS_DEBUG 0
// - set FOCUSLOGLEVEL to non-zero log level (usually, 5,6, or 7==LOG_DEBUG) to get focus (extensive logging) for this file
// Note: must be before including "logger.hpp" (or anything that includes "logger.hpp")
#define FOCUSLOGLEVEL 0
#include "mainloop.hpp"
#ifdef __APPLE__
#include <mach/mach_time.h>
#endif
#include <unistd.h>
#include <sys/param.h>
#include <sys/wait.h>
#include <math.h>
#ifdef ESP_PLATFORM
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_system.h"
#include "esp_timer.h"
#include "esp_vfs.h"
#endif
#include "fdcomm.hpp"
// MARK: - MainLoop default parameters
#define MAINLOOP_DEFAULT_MAXSLEEP Infinite // if really nothing to do, we can sleep
#define MAINLOOP_DEFAULT_MAXRUN (100*MilliSecond) // noticeable reaction time
#define MAINLOOP_DEFAULT_THROTTLE_SLEEP (20*MilliSecond) // limits CPU usage to about 85%
#define MAINLOOP_DEFAULT_WAIT_CHECK_INTERVAL (100*MilliSecond) // assuming no really tight timing when using external processes
#define MAINLOOP_DEFAULT_MAX_COALESCING (1*Second) // keep timing within second precision by default
using namespace p44;
#ifdef BOOST_NO_EXCEPTIONS
// boost calls this when throwing C++ exceptions is disabled, e.g. ESP32 builds
void boost::throw_exception(std::exception const & e){
// log and exit
LOG(LOG_ERR, "Exception thrown -> exit");
exit(EXIT_FAILURE);
}
#endif
// MARK: - MLTicket
MLTicket::MLTicket() :
mTicketNo(0)
{
}
MLTicket::MLTicket(MLTicket &aTicket) : mTicketNo(0)
{
// should not happen!
// But if it does, we do not copy the ticket number
}
MLTicketNo MLTicket::defuse()
{
MLTicketNo tn = mTicketNo;
mTicketNo = 0; // cancel() or destruction will no longer end the timer
return tn;
}
MLTicket::~MLTicket()
{
cancel();
}
MLTicket::operator MLTicketNo() const
{
return mTicketNo;
}
MLTicket::operator bool() const
{
return mTicketNo!=0;
}
bool MLTicket::cancel()
{
if (mTicketNo!=0) {
bool cancelled = MainLoop::currentMainLoop().cancelExecutionTicket(mTicketNo);
mTicketNo = 0;
return cancelled;
}
return false; // no ticket
}
void MLTicket::executeOnceAt(TimerCB aTimerCallback, MLMicroSeconds aExecutionTime, MLMicroSeconds aTolerance)
{
MainLoop::currentMainLoop().executeTicketOnceAt(*this, aTimerCallback, aExecutionTime, aTolerance);
}
void MLTicket::executeOnce(TimerCB aTimerCallback, MLMicroSeconds aDelay, MLMicroSeconds aTolerance)
{
MainLoop::currentMainLoop().executeTicketOnce(*this, aTimerCallback, aDelay, aTolerance);
}
MLTicketNo MLTicket::operator=(MLTicketNo aTicketNo)
{
cancel();
mTicketNo = aTicketNo;
return mTicketNo;
}
bool MLTicket::reschedule(MLMicroSeconds aDelay, MLMicroSeconds aTolerance)
{
MLMicroSeconds executionTime = MainLoop::currentMainLoop().now()+aDelay;
return rescheduleAt(executionTime, aTolerance);
}
bool MLTicket::rescheduleAt(MLMicroSeconds aExecutionTime, MLMicroSeconds aTolerance)
{
if (mTicketNo==0) return false; // no ticket, no reschedule
return MainLoop::currentMainLoop().rescheduleExecutionTicketAt(mTicketNo, aExecutionTime, aTolerance);
}
// MARK: - Time base
long long _p44_now()
{
#if defined(__APPLE__) && __DARWIN_C_LEVEL < 199309L
// pre-10.12 MacOS does not yet have clock_gettime
static bool timeInfoKnown = false;
static mach_timebase_info_data_t tb;
if (!timeInfoKnown) {
mach_timebase_info(&tb);
}
double t = mach_absolute_time();
return t * (double)tb.numer / (double)tb.denom / 1e3; // uS
#elif defined(ESP_PLATFORM)
return esp_timer_get_time(); // just fits, is high precision timer in uS since boot
#else
// platform has clock_gettime
struct timespec tsp;
clock_gettime(CLOCK_MONOTONIC, &tsp);
// return microseconds
return ((long long)(tsp.tv_sec))*1000000ll + (long long)(tsp.tv_nsec/1000); // uS
#endif
}
unsigned long _p44_millis()
{
return (unsigned long)(_p44_now()/1000); // mS
}
// MARK: - MainLoop static utilities
// time reference in microseconds
MLMicroSeconds MainLoop::now()
{
return _p44_now();
}
MLMicroSeconds MainLoop::unixtime()
{
#if defined(__APPLE__) && __DARWIN_C_LEVEL < 199309L
// pre-10.12 MacOS does not yet have clock_gettime
// FIXME: Q&D approximation with seconds resolution only
return ((MLMicroSeconds)time(NULL))*Second;
#elif defined(ESP_PLATFORM)
// TODO: implement getting actual time from RTC
#warning "Fake unixtime() on ESP_PLATFORM for now"
return 2222*365*Day+now();
#else
struct timespec tsp;
clock_gettime(CLOCK_REALTIME, &tsp);
// return unix epoch microseconds
return ((long long)(tsp.tv_sec))*1000000ll + (long long)(tsp.tv_nsec/1000); // uS
#endif
}
MLMicroSeconds MainLoop::mainLoopTimeToUnixTime(MLMicroSeconds aMLTime)
{
return aMLTime-now()+unixtime();
}
MLMicroSeconds MainLoop::unixTimeToMainLoopTime(const MLMicroSeconds aUnixTime)
{
return aUnixTime-unixtime()+now();
}
MLMicroSeconds MainLoop::timeValToMainLoopTime(struct timeval *aTimeValP)
{
if (!aTimeValP) return Never;
return aTimeValP->tv_sec*Second + aTimeValP->tv_usec;
}
void MainLoop::mainLoopTimeTolocalTime(MLMicroSeconds aMLTime, struct tm& aLocalTime, double* aFractionalSecondsP)
{
MLMicroSeconds ut = mainLoopTimeToUnixTime(aMLTime);
time_t t = ut/Second;
if (aFractionalSecondsP) {
*aFractionalSecondsP = (double)ut/Second-(double)t;
}
localtime_r(&t, &aLocalTime);
}
MLMicroSeconds MainLoop::localTimeToMainLoopTime(const struct tm& aLocalTime)
{
time_t u = mktime((struct tm*) &aLocalTime);
return unixTimeToMainLoopTime(u*Second);
}
void MainLoop::getLocalTime(struct tm& aLocalTime, double* aFractionalSecondsP, MLMicroSeconds aUnixTime, bool aGMT)
{
double unixsecs = (double)aUnixTime/Second;
time_t t = (time_t)unixsecs;
if (aGMT) gmtime_r(&t, &aLocalTime);
else localtime_r(&t, &aLocalTime);
if (aFractionalSecondsP) {
*aFractionalSecondsP = unixsecs-floor(unixsecs);
}
}
string MainLoop::string_mltime(MLMicroSeconds aTime, int aFractionals)
{
if (aTime==Infinite) return "Infinite";
if (aTime==Never) return "Never";
return string_fmltime("%Y-%m-%d %H:%M:%S", aTime, aFractionals);
}
string MainLoop::string_fmltime(const char *aFormat, MLMicroSeconds aTime, int aFractionals)
{
struct tm tim;
string ts;
if (aFractionals==0) {
mainLoopTimeTolocalTime(aTime, tim);
string_ftime_append(ts, aFormat, &tim);
}
else {
double fracSecs;
mainLoopTimeTolocalTime(aTime, tim, &fracSecs);
string_ftime_append(ts, aFormat, &tim);
int f = (int)(fracSecs*pow(10, aFractionals));
string_format_append(ts, ".%0*d", aFractionals, f);
}
return ts;
}
void MainLoop::sleep(MLMicroSeconds aSleepTime)
{
#ifdef ESP_PLATFORM
vTaskDelay(aSleepTime/MilliSecond/portTICK_PERIOD_MS);
#else
// Linux/MacOS has nanosleep in nanoseconds
timespec sleeptime;
sleeptime.tv_sec=aSleepTime/Second;
sleeptime.tv_nsec=(long)((aSleepTime % Second)*1000ll); // nS = 1000 uS
nanosleep(&sleeptime,NULL);
#endif
}
// the current thread's main looop
#if BOOST_DISABLE_THREADS
static MainLoop *currentMainLoopP = NULL;
#else
static __thread MainLoop *currentMainLoopP = NULL;
#endif
// get the per-thread singleton mainloop
MainLoop &MainLoop::currentMainLoop()
{
if (currentMainLoopP==NULL) {
// need to create it
currentMainLoopP = new MainLoop();
}
return *currentMainLoopP;
}
#if MAINLOOP_STATISTICS
#define ML_STAT_START_AT(nw) MLMicroSeconds t = (nw);
#define ML_STAT_ADD_AT(tmr, nw) tmr += (nw)-t;
#define ML_STAT_START ML_STAT_START_AT(now());
#define ML_STAT_ADD(tmr) ML_STAT_ADD_AT(tmr, now());
#else
#define ML_STAT_START_AT(now)
#define ML_STAT_ADD_AT(tmr, nw);
#define ML_STAT_START
#define ML_STAT_ADD(tmr)
#endif
// MARK: - ExecError
ErrorPtr ExecError::exitStatus(int aExitStatus, const char *aContextMessage)
{
if (aExitStatus==0)
return ErrorPtr(); // empty, no error
return Error::err_cstr<ExecError>(aExitStatus, aContextMessage);
}
// MARK: - MainLoop ESP32 specific utilities
#ifdef ESP_PLATFORM
#define P44UTILS_MAINLOOP_EVFS_PATH "/p44EvFs"
static bool evFsInstalled = false;
static bool foreignTaskTimersWaiting = false;
static int evFs_open(const char *path, int flags, int mode)
{
// is a singleton, local FD is always 0
DBGFOCUSLOG("evFs_open");
return 0; // FD
}
static int evFs_close(int fd)
{
// nop
DBGFOCUSLOG("evFs_close");
return 0; // ok
}
static SemaphoreHandle_t evFsSemaphore = NULL;
esp_err_t evFs_start_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, esp_vfs_select_sem_t sem, void **end_select_args)
{
// remember the semaphore we need to trigger
DBGFOCUSLOG("evFs_start_select");
// from esp_vfs.h: type of "sem" is SemaphoreHandle_t when true, defined by socket driver otherwise
assert(sem.is_sem_local);
evFsSemaphore = (SemaphoreHandle_t)sem.sem;
if (foreignTaskTimersWaiting) {
// new timers were waiting before select has started -> immediately terminate select()
foreignTaskTimersWaiting = false;
DBGFOCUSLOG("evFs_start_select with foreignTaskTimersPending immediately frees evFsSemaphore");
xSemaphoreGive(evFsSemaphore);
}
*end_select_args = NULL;
return ESP_OK;
}
static esp_err_t evFs_end_select(void *end_select_args)
{
DBGFOCUSLOG("evFs_end_select");
evFsSemaphore = NULL; // forget semaphore again
return ESP_OK;
}
static esp_vfs_t evFs = {
.flags = ESP_VFS_FLAG_DEFAULT,
.open = &evFs_open,
.close = &evFs_close,
.start_select = &evFs_start_select,
.end_select = &evFs_end_select,
};
#endif // ESP_PLATFORM
// MARK: - MainLoop
#if MAINLOOP_LIBEV_BASED
namespace p44 {
void libev_io_poll_handler(EV_P_ struct ev_io *i, int revents); // declaration to silence warning
void libev_sleep_timer_done(EV_P_ struct ev_timer *t, int revents); // declaration to silence warning
}
void p44::libev_sleep_timer_done(EV_P_ struct ev_timer *t, int revents)
{
MainLoop* mlP = static_cast<MainLoop*>(t->data);
ev_timer_stop(mlP->mLibEvLoopP, t);
// NOP, just needed to exit IO polling
DBGFOCUSLOG(LOG_DEBUG, "libev IO polling timeout");
}
#endif // MAINLOOP_LIBEV_BASED
#if MAINLOOP_LIBEV_BASED
static bool gDefaultMainloopInUse = false;
#endif
MainLoop::MainLoop() :
mTimersChanged(false),
mTicketNo(0),
mStartedAt(Never),
mTerminated(false),
mExitCode(EXIT_SUCCESS)
{
#ifdef ESP_PLATFORM
FOCUSLOG("mainloop: ESP32 specific initialisation of mainloop@%p", this);
// capture the task handle
mTaskHandle = xTaskGetCurrentTaskHandle();
// create locked semaphore to protect from untimely calls to executeNowFromForeignTask
mTimersLock = xSemaphoreCreateBinary();
evFsFD = -1;
if (!evFsInstalled) {
DBGFOCUSLOG("- installing pseudo VFS");
// create a pseudo VFS driver for the only purpose to be able to post a event that interrupts a select()
ErrorPtr err = EspError::err(esp_vfs_register(P44UTILS_MAINLOOP_EVFS_PATH, &evFs, NULL));
if (Error::notOK(err)) {
FOCUSLOG("mainloop: esp_vfs_register failed: %s", err->text());
}
evFsInstalled = true;
// now open a FD we can later use in handleIoPoll with select()
DBGFOCUSLOG("- opening select trigger event pseudo file");
evFsFD = open(P44UTILS_MAINLOOP_EVFS_PATH, O_RDONLY);
if (evFsFD<0) {
FOCUSLOG("mainloop: cannot open " P44UTILS_MAINLOOP_EVFS_PATH);
}
DBGFOCUSLOG("- select trigger event pseudo file, FD=%d", evFsFD);
}
#elif MAINLOOP_LIBEV_BASED
if (gDefaultMainloopInUse) {
// this must be a subthread's mainloop, must create a new libev mainloop for it
mLibEvLoopP = ev_loop_new();
}
else {
// this is the main main loop
gDefaultMainloopInUse = true; // all further mainloops must create a new ev_loop
mLibEvLoopP = EV_DEFAULT;
}
// init timer we need when we allow libev to "sleep"
ev_timer_init(&mLibEvTimer, &libev_sleep_timer_done, 1, 0);
mLibEvTimer.data = this;
#endif
// default configuration
mMaxSleep = MAINLOOP_DEFAULT_MAXSLEEP;
mMaxRun = MAINLOOP_DEFAULT_MAXRUN;
mThrottleSleep = MAINLOOP_DEFAULT_THROTTLE_SLEEP;
mWaitCheckInterval = MAINLOOP_DEFAULT_WAIT_CHECK_INTERVAL;
mMaxCoalescing = MAINLOOP_DEFAULT_MAX_COALESCING;
#if MAINLOOP_STATISTICS
statistics_reset();
#endif
}
// MARK: timer setup
// private implementation
MLTicketNo MainLoop::executeOnce(TimerCB aTimerCallback, MLMicroSeconds aDelay, MLMicroSeconds aTolerance)
{
MLMicroSeconds executionTime = now()+aDelay;
return executeOnceAt(aTimerCallback, executionTime, aTolerance);
}
// private implementation
MLTicketNo MainLoop::executeOnceAt(TimerCB aTimerCallback, MLMicroSeconds aExecutionTime, MLMicroSeconds aTolerance)
{
MLTimer tmr;
tmr.mReinsert = false;
tmr.mTicketNo = ++mTicketNo;
tmr.mExecutionTime = aExecutionTime;
tmr.mTolerance = aTolerance;
tmr.mCallback = aTimerCallback;
scheduleTimer(tmr);
return tmr.mTicketNo;
}
void MainLoop::executeTicketOnceAt(MLTicket &aTicket, TimerCB aTimerCallback, MLMicroSeconds aExecutionTime, MLMicroSeconds aTolerance)
{
aTicket.cancel();
aTicket = (MLTicketNo)executeOnceAt(aTimerCallback, aExecutionTime, aTolerance);
}
void MainLoop::executeTicketOnce(MLTicket &aTicket, TimerCB aTimerCallback, MLMicroSeconds aDelay, MLMicroSeconds aTolerance)
{
aTicket.cancel();
aTicket = executeOnce(aTimerCallback, aDelay, aTolerance);
}
void MainLoop::executeNow(TimerCB aTimerCallback)
{
executeOnce(aTimerCallback, 0, 0);
}
#ifdef ESP_PLATFORM
void MainLoop::executeNowFromForeignTask(TimerCB aTimerCallback)
{
// - safely insert in timer queue
DBGFOCUSLOG("executeNowFromForeignTask: evFsFD=%d in mainloop@%p", evFsFD, this);
xSemaphoreTake(mTimersLock, portMAX_DELAY);
DBGFOCUSLOG("- executeNowFromForeignTask lock taken in mainloop@%p", this);
executeNow(aTimerCallback);
if (evFsFD>=0) {
// signal select to exit immediately when not yet running
foreignTaskTimersWaiting = true;
// make select() exit if already running
if (evFsSemaphore) {
// we are currently in select, release it
DBGFOCUSLOG("- executeNowFromForeignTask frees evFsSemaphore");
xSemaphoreGive(evFsSemaphore);
}
}
xSemaphoreGive(mTimersLock);
}
#endif
void MainLoop::scheduleTimer(MLTimer &aTimer)
{
#if MAINLOOP_STATISTICS
size_t n = mTimers.size()+1;
if (n>mMaxTimers) mMaxTimers = n;
#endif
// insert in queue before first item that has a higher execution time
TimerList::iterator pos = mTimers.begin();
// optimization: if no timers, just append
if (pos!=mTimers.end()) {
// optimization: if new timer is later than all others, just append
if (aTimer.mExecutionTime<mTimers.back().mExecutionTime) {
// is somewhere between current timers, need to find position
do {
if (pos->mExecutionTime>aTimer.mExecutionTime) {
mTimers.insert(pos, aTimer);
mTimersChanged = true;
return;
}
++pos;
} while (pos!=mTimers.end());
}
}
// none executes later than this one, just append
mTimersChanged = true; // when processing timers now, the list must be re-checked! Processing iterator might be at end of list already!
mTimers.push_back(aTimer);
}
void MainLoop::cancelExecutionTicket(MLTicket &aTicket)
{
aTicket.cancel();
}
// private implementation
bool MainLoop::cancelExecutionTicket(MLTicketNo aTicketNo)
{
if (aTicketNo==0) return false; // no ticket, NOP
for (TimerList::iterator pos = mTimers.begin(); pos!=mTimers.end(); ++pos) {
if (pos->mTicketNo==aTicketNo) {
pos = mTimers.erase(pos);
mTimersChanged = true;
return true; // ticket found and cancelled
}
}
return false; // no such ticket
}
bool MainLoop::rescheduleExecutionTicket(MLTicketNo aTicketNo, MLMicroSeconds aDelay, MLMicroSeconds aTolerance)
{
MLMicroSeconds executionTime = now()+aDelay;
return rescheduleExecutionTicketAt(aTicketNo, executionTime, aTolerance);
}
bool MainLoop::rescheduleExecutionTicketAt(MLTicketNo aTicketNo, MLMicroSeconds aExecutionTime, MLMicroSeconds aTolerance)
{
if (aTicketNo==0) return false; // no ticket, no reschedule
for (TimerList::iterator pos = mTimers.begin(); pos!=mTimers.end(); ++pos) {
if (pos->mTicketNo==aTicketNo) {
MLTimer h = *pos;
// remove from queue
pos = mTimers.erase(pos);
// reschedule
h.mExecutionTime = aExecutionTime;
scheduleTimer(h);
// reschedule was possible
return true;
}
}
// no ticket found, could not reschedule
return false;
}
int MainLoop::retriggerTimer(MLTimer &aTimer, MLMicroSeconds aInterval, MLMicroSeconds aTolerance, int aSkip)
{
MLMicroSeconds now = MainLoop::now();
int skipped = 0;
aTimer.mTolerance = aTolerance;
if (aSkip==absolute) {
if (aInterval<now+aTimer.mTolerance) {
skipped = 1; // signal we skipped some time
aTimer.mExecutionTime = now; // ASAP
}
else {
aTimer.mExecutionTime = aInterval; // aInterval is absolute time to fire timer next
}
aTimer.mReinsert = true;
return skipped;
}
else if (aSkip==from_now_if_late) {
aTimer.mExecutionTime += aInterval;
if (aTimer.mExecutionTime+aTimer.mTolerance < now) {
// too late (even taking allowed tolerance into account)
aTimer.mExecutionTime = now+aInterval;
skipped = 1; // signal we skipped some time
}
// we're not yet too late to let this timer run within its tolerance -> re-insert it
aTimer.mReinsert = true;
return skipped;
}
else if (aSkip==from_now) {
// unconditionally relative to now
aTimer.mExecutionTime = now+aInterval;
aTimer.mReinsert = true;
return skipped;
}
else {
do {
aTimer.mExecutionTime += aInterval;
if (aTimer.mExecutionTime >= now) {
// success
aTimer.mReinsert = true;
return skipped;
}
skipped++;
} while (skipped<=aSkip);
// could not advance the timer enough
return -1; // signal failure to retrigger within the specified limits
}
}
// MARK: subprocesses
#ifndef ESP_PLATFORM
void MainLoop::waitForPid(WaitCB aCallback, pid_t aPid)
{
LOG(LOG_DEBUG, "waitForPid: requested wait for pid=%d", aPid);
if (aCallback) {
// install new callback
WaitHandler h;
h.callback = aCallback;
h.pid = aPid;
mWaitHandlers[aPid] = h;
}
else {
WaitHandlerMap::iterator pos = mWaitHandlers.find(aPid);
if (pos!=mWaitHandlers.end()) {
// remove it from list
mWaitHandlers.erase(pos);
}
}
}
extern char **environ;
pid_t MainLoop::fork_and_execve(ExecCB aCallback, const char *aPath, char *const aArgv[], char *const aEnvp[], bool aPipeBackStdOut, int* aPipeBackFdP, int aStdErrFd, int aStdInFd)
{
LOG(LOG_DEBUG, "fork_and_execve: preparing to fork for executing '%s' now", aPath);
pid_t child_pid;
int answerPipe[2]; /* Child to parent pipe */
// prepare environment
if (aEnvp==NULL) {
aEnvp = environ; // use my own environment
}
// prepare pipe in case we want answer collected
if (aPipeBackStdOut) {
if(pipe(answerPipe)<0) {
// pipe could not be created
aCallback(SysError::errNo(),"");
return -1;
}
}
// fork child process
child_pid = fork();
if (child_pid>=0) {
// fork successful
if (child_pid==0) {
// this is the child process (fork() returns 0 for the child process)
//setpgid(0, 0); // Linux: set group PID to this process' PID, allows killing the entire group
LOG(LOG_DEBUG, "forked child process: preparing for execve");
if (aPipeBackStdOut) {
dup2(answerPipe[1],STDOUT_FILENO); // replace STDOUT by writing end of pipe
close(answerPipe[1]); // release the original descriptor (does NOT really close the file)
close(answerPipe[0]); // close child's reading end of pipe (parent uses it!)
}
if (aStdErrFd>=0) {
if (aStdErrFd==0) aStdErrFd = open("/dev/null", O_WRONLY);
dup2(aStdErrFd, STDERR_FILENO); // replace STDERR by provided fd
close(aStdErrFd);
}
if (aStdInFd>=0) {
if (aStdInFd==0) aStdErrFd = open("/dev/null", O_RDONLY);
dup2(aStdInFd, STDIN_FILENO); // replace STDIN by provided fd
close(aStdInFd);
}
// close all non-std file descriptors
int fd = getdtablesize();
while (fd>STDERR_FILENO) close(fd--);
// change to the requested child process
execve(aPath, aArgv, aEnvp); // replace process with new binary/script
// execv returns only in case of error
exit(127);
}
else {
// this is the parent process, wait for the child to terminate
LOG(LOG_DEBUG, "fork_and_execve: parent: child pid=%d", child_pid);
FdStringCollectorPtr ans;
if (aPipeBackStdOut) {
LOG(LOG_DEBUG, "fork_and_execve: parent will now set up pipe string collector");
close(answerPipe[1]); // close parent's writing end (child uses it!)
// set up collector for data returned from child process
if (aPipeBackFdP) {
// caller wants to handle the pipe end, return file descriptor
*aPipeBackFdP = answerPipe[0];
}
else {
// collect output in a string
ans = FdStringCollectorPtr(new FdStringCollector(MainLoop::currentMainLoop()));
ans->setFd(answerPipe[0]);
}
}
LOG(LOG_DEBUG, "fork_and_execve: now calling waitForPid(%d)", child_pid);
waitForPid(boost::bind(&MainLoop::execChildTerminated, this, aCallback, ans, _1, _2), child_pid);
return child_pid;
}
}
else {
if (aCallback) {
// fork failed, call back with error
aCallback(SysError::errNo(),"");
}
}
return -1;
}
pid_t MainLoop::fork_and_system(ExecCB aCallback, const char *aCommandLine, bool aPipeBackStdOut, int* aPipeBackFdP, int aStdErrFd, int aStdInFd)
{
char * args[4];
args[0] = (char *)"sh";
args[1] = (char *)"-c";
args[2] = (char *)aCommandLine;
args[3] = NULL;
return fork_and_execve(aCallback, "/bin/sh", args, NULL, aPipeBackStdOut, aPipeBackFdP, aStdErrFd, aStdInFd);
}
void MainLoop::execChildTerminated(ExecCB aCallback, FdStringCollectorPtr aAnswerCollector, pid_t aPid, int aStatus)
{
LOG(LOG_DEBUG, "execChildTerminated: pid=%d, aStatus=%d", aPid, aStatus);
if (aCallback) {
LOG(LOG_DEBUG, "- callback set, execute it");
ErrorPtr err = ExecError::exitStatus(WEXITSTATUS(aStatus));
if (aAnswerCollector) {
LOG(LOG_DEBUG, "- aAnswerCollector: starting collectToEnd");
aAnswerCollector->collectToEnd(boost::bind(&MainLoop::childAnswerCollected, this, aCallback, aAnswerCollector, err));
}
else {
// call back directly
LOG(LOG_DEBUG, "- no aAnswerCollector: callback immediately");
aCallback(err, "");
}
}
}
void MainLoop::childAnswerCollected(ExecCB aCallback, FdStringCollectorPtr aAnswerCollector, ErrorPtr aError)
{
LOG(LOG_DEBUG, "childAnswerCollected: error = %s", Error::text(aError));
// close my end of the pipe
aAnswerCollector->stopMonitoringAndClose();
// now get answer
string answer = aAnswerCollector->mCollectedData;
LOG(LOG_DEBUG, "- Answer = %s", answer.c_str());
// call back directly
aCallback(aError, answer);
}
#endif // !ESP_PLATFORM
// MARK: mainloop core
void MainLoop::registerCleanupHandler(SimpleCB aCleanupHandler)
{
cleanupHandlers.push_back(aCleanupHandler);
}
void MainLoop::terminate(int aExitCode)
{
mExitCode = aExitCode;
mTerminated = true;
}
MLMicroSeconds MainLoop::checkTimers(MLMicroSeconds aTimeout)
{
ML_STAT_START
MLMicroSeconds nextTimer = Never;
MLMicroSeconds runUntilMax = MainLoop::now() + aTimeout;
do {
nextTimer = Never;
TimerList::iterator pos = mTimers.begin();
mTimersChanged = false; // detect changes happening from callbacks
// Note: it is essential to check timersChanged in the while loop condition, because when the loop
// is actually taken, the runningTimer object can go out of scope and cause a
// chain of destruction which in turn can cause timer changes AFTER the timer callback
// has already returned.
while (!mTimersChanged && pos!=mTimers.end()) {
nextTimer = pos->mExecutionTime;
MLMicroSeconds now = MainLoop::now();
// check for executing next timer
MLMicroSeconds tl = pos->mTolerance;
if (tl>mMaxCoalescing) tl=mMaxCoalescing;
if (nextTimer-tl>now) {
// next timer not ready to run
goto done;
} else if (now>runUntilMax) {
// we are running too long already
#if MAINLOOP_STATISTICS
mTimesTimersRanToLong++;
#endif
goto done;
}
else {
// earliest allowed execution time for this timer is reached, execute it
if (mTerminated) {
nextTimer = Never; // no more timers to run if terminated
goto done;
}
#if MAINLOOP_STATISTICS
// update max delay from intented execution time
MLMicroSeconds late = now-nextTimer-pos->mTolerance;
if (late>mMaxTimerExecutionDelay) mMaxTimerExecutionDelay = late;
#endif
// run this timer
MLTimer runningTimer = *pos; // copy the timer object
runningTimer.mReinsert = false; // not re-inserting by default
pos = mTimers.erase(pos); // remove timer from queue
runningTimer.mCallback(runningTimer, now); // call handler
if (runningTimer.mReinsert) {
// retriggering requested, do it now
scheduleTimer(runningTimer);
}
}
}
// we get here when list was processed
} while (mTimersChanged);
done:
ML_STAT_ADD(mTimedHandlerTime);
return nextTimer; // report to caller when we need to be called again to meet next timer
}
#ifndef ESP_PLATFORM
bool MainLoop::checkWait()
{
if (mWaitHandlers.size()>0) {
// check for process signal
int status;
pid_t pid = waitpid(-1, &status, WNOHANG);
if (pid>0) {
LOG(LOG_DEBUG, "checkWait: child pid=%d reports exit status %d", pid, status);
// process has status
WaitHandlerMap::iterator pos = mWaitHandlers.find(pid);
if (pos!=mWaitHandlers.end()) {
// we have a callback
WaitCB cb = pos->second.callback; // get it
// remove it from list
mWaitHandlers.erase(pos);
// call back
ML_STAT_START
LOG(LOG_DEBUG, "- calling wait handler for pid=%d now with status=%d", pid, status);
cb(pid, status);
ML_STAT_ADD(mWaitHandlerTime);
return false; // more process status could be ready, call soon again
}
}
else if (pid<0) {
// error when calling waitpid
int e = errno;
if (e==ECHILD) {
// no more children
LOG(LOG_WARNING, "checkWait: pending handlers but no children any more -> ending all waits WITH FAKE STATUS 0 - probably SIGCHLD ignored?");
// - inform all still waiting handlers
WaitHandlerMap oldHandlers = mWaitHandlers; // copy
mWaitHandlers.clear(); // remove all handlers from real list, as new handlers might be added in handlers we'll call now
ML_STAT_START
for (WaitHandlerMap::iterator pos = oldHandlers.begin(); pos!=oldHandlers.end(); pos++) {
WaitCB cb = pos->second.callback; // get callback
LOG(LOG_DEBUG, "- calling wait handler for pid=%d now WITH FAKE STATUS 0", pos->second.pid);
cb(pos->second.pid, 0); // fake status
}
ML_STAT_ADD(mWaitHandlerTime);
}
else {
LOG(LOG_DEBUG, "checkWait: waitpid returns error %s", strerror(e));
}
}
}
return true; // all checked
}
#endif
// MARK: - IO event handling
#if MAINLOOP_LIBEV_BASED
static inline int pollToEv(int aPollFlags)
{
// POLLIN, POLLOUT -> EV_READ, EV_WRITE
int events = 0;
if (aPollFlags & POLLIN) events |= EV_READ;
if (aPollFlags & POLLOUT) events |= EV_WRITE;
return events;
}
static inline int evToPoll(int aLibEvEvents)
{
int pollFlags = 0;
if (aLibEvEvents & EV_READ) pollFlags |= POLLIN;
if (aLibEvEvents & EV_WRITE) pollFlags |= POLLOUT;