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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file scheduler.lua
--
-- define module: scheduler
local scheduler = scheduler or {}
local _coroutine = _coroutine or {}
-- load modules
local table = require("base/table")
local utils = require("base/utils")
local option = require("base/option")
local string = require("base/string")
local poller = require("base/poller")
local timer = require("base/timer")
local hashset = require("base/hashset")
local coroutine = require("base/coroutine")
local bit = require("base/bit")
-- new a coroutine instance
function _coroutine.new(name, thread)
local instance = table.inherit(_coroutine)
instance._NAME = name
instance._THREAD = thread
setmetatable(instance, _coroutine)
return instance
end
-- get the coroutine name
function _coroutine:name()
return self._NAME or "none"
end
-- set the coroutine name
function _coroutine:name_set(name)
self._NAME = name
end
-- get the waiting poller object
function _coroutine:waitobj()
return self._WAITOBJ
end
-- set the waiting poller object
function _coroutine:waitobj_set(obj)
self._WAITOBJ = obj
end
-- get user private data
function _coroutine:data(name)
return self._DATA and self._DATA[name]
end
-- set user private data
function _coroutine:data_set(name, data)
self._DATA = self._DATA or {}
self._DATA[name] = data
end
-- add user private data
function _coroutine:data_add(name, data)
self._DATA = self._DATA or {}
self._DATA[name] = table.unwrap(table.join(self._DATA[name] or {}, data))
end
-- get the raw coroutine thread
function _coroutine:thread()
return self._THREAD
end
-- get the coroutine status
function _coroutine:status()
return coroutine.status(self:thread())
end
-- is dead?
function _coroutine:is_dead()
return self:status() == "dead"
end
-- is running?
function _coroutine:is_running()
return self:status() == "running"
end
-- is suspended?
function _coroutine:is_suspended()
return self:status() == "suspended"
end
-- is isolated?
function _coroutine:is_isolated()
return self._ISOLATED
end
-- isolate coroutine environments
function _coroutine:isolate(isolate)
self._ISOLATED = isolate
end
-- get the current timer task
function _coroutine:_timer_task()
return self._TIMER_TASK
end
-- set the timer task
function _coroutine:_timer_task_set(task)
self._TIMER_TASK = task
end
-- tostring(coroutine)
function _coroutine:__tostring()
return string.format("<co: %s/%s>", self:name(), self:status())
end
-- gc(coroutine)
function _coroutine:__gc()
self._THREAD = nil
end
-- get the timer of scheduler
function scheduler:_timer()
local t = self._TIMER
if t == nil then
t = timer:new()
self._TIMER = t
end
return t
end
-- get poller object data for socket, pipe, process, fwatcher object
function scheduler:_poller_data(obj)
return self._POLLERDATA and self._POLLERDATA[obj] or nil
end
-- set poller object data
--
-- data.co_recv: the suspended coroutine for waiting poller/recv
-- data.co_send: the suspended coroutine for waiting poller/send
-- data.poller_events_wait: the waited events for poller
-- data.poller_events_save: the saved events for poller (triggered)
--
function scheduler:_poller_data_set(obj, data)
local pollerdata = self._POLLERDATA
if not pollerdata then
pollerdata = {}
self._POLLERDATA = pollerdata
end
pollerdata[obj] = data
end
-- resume the suspended coroutine after poller callback
function scheduler:_poller_resume_co(co, events)
-- cancel timer task if exists
local timer_task = co:_timer_task()
if timer_task then
timer_task.cancel = true
end
-- the scheduler has been stopped? mark events as error to stop the coroutine
if not self._STARTED then
events = poller.EV_POLLER_ERROR
end
-- this coroutine must be suspended, (maybe also dead)
if not co:is_suspended() then
return false, string.format("%s cannot be resumed, status: %s", co, co:status())
end
-- resume this coroutine task
co:waitobj_set(nil)
return self:co_resume(co, (bit.band(events, poller.EV_POLLER_ERROR) ~= 0) and -1 or events)
end
-- the poller events callback
function scheduler:_poller_events_cb(obj, events)
-- get poller object data
local pollerdata = self:_poller_data(obj)
if not pollerdata then
return false, string.format("%s: cannot get poller data!", obj)
end
-- is process/fwatcher object?
if obj:otype() == poller.OT_PROC or obj:otype() == poller.OT_FWATCHER then
-- resume coroutine and return the process exit status/fwatcher event
pollerdata.object_event = events
-- waiting process/fwatcher? resume this coroutine
if pollerdata.co_waiting then
local co_waiting = pollerdata.co_waiting
pollerdata.co_waiting = nil
return self:_poller_resume_co(co_waiting, 1)
else
pollerdata.object_pending = 1
end
return true
end
-- get poller object events
local events_prev_wait = pollerdata.poller_events_wait
local events_prev_save = pollerdata.poller_events_save
-- eof for edge trigger?
if bit.band(events, poller.EV_POLLER_EOF) ~= 0 then
-- cache this eof as next recv/send event
events = bit.band(events, bit.bnot(poller.EV_POLLER_EOF))
events_prev_save = bit.bor(events_prev_save, events_prev_wait)
pollerdata.poller_events_save = events_prev_save
end
-- get the waiting coroutines
local co_recv = bit.band(events, poller.EV_POLLER_RECV) ~= 0 and pollerdata.co_recv or nil
local co_send = bit.band(events, poller.EV_POLLER_SEND) ~= 0 and pollerdata.co_send or nil
-- return the events result for the waiting coroutines
if co_recv and co_recv == co_send then
pollerdata.co_recv = nil
pollerdata.co_send = nil
return self:_poller_resume_co(co_recv, events)
else
if co_recv then
pollerdata.co_recv = nil
local ok, errors = self:_poller_resume_co(co_recv, bit.band(events, bit.bnot(poller.EV_POLLER_SEND)))
if not ok then
return false, errors
end
events = bit.band(events, bit.bnot(poller.EV_POLLER_RECV))
end
if co_send then
pollerdata.co_send = nil
local ok, errors = self:_poller_resume_co(co_send, bit.band(events, bit.bnot(poller.EV_POLLER_RECV)))
if not ok then
return false, errors
end
events = bit.band(events, bit.bnot(poller.EV_POLLER_SEND))
end
-- no coroutines are waiting? cache this events
if bit.band(events, poller.EV_POLLER_RECV) ~= 0 or bit.band(events, poller.EV_POLLER_SEND) ~= 0 then
events_prev_save = bit.bor(events_prev_save, events)
pollerdata.poller_events_save = events_prev_save
end
end
return true
end
-- update the current directory hash of current coroutine
function scheduler:_co_curdir_update(curdir)
-- get running coroutine
local running = self:co_running()
if not running then
return
end
-- save the current directory hash
curdir = curdir or os.curdir()
local curdir_hash = hash.uuid4(path.absolute(curdir)):sub(1, 8)
self._CO_CURDIR_HASH = curdir_hash
-- save the current directory for each coroutine
local co_curdirs = self._CO_CURDIRS
if not co_curdirs then
co_curdirs = {}
self._CO_CURDIRS = co_curdirs
end
co_curdirs[running] = {curdir_hash, curdir}
end
-- update the current environments hash of current coroutine
function scheduler:_co_curenvs_update(envs)
-- get running coroutine
local running = self:co_running()
if not running then
return
end
-- save the current directory hash
local envs_hash = ""
envs = envs or os.getenvs()
for _, key in ipairs(table.orderkeys(envs)) do
envs_hash = envs_hash .. key:upper() .. envs[key]
end
envs_hash = hash.uuid4(envs_hash):sub(1, 8)
self._CO_CURENVS_HASH = envs_hash
-- save the current directory for each coroutine
local co_curenvs = self._CO_CURENVS
if not co_curenvs then
co_curenvs = {}
self._CO_CURENVS = co_curenvs
end
co_curenvs[running] = {envs_hash, envs}
end
-- resume it's waiting coroutine if all coroutines are dead in group
function scheduler:_co_groups_resume()
local resumed_count = 0
local co_groups = self._CO_GROUPS
if co_groups then
local co_groups_waiting = self._CO_GROUPS_WAITING
local co_resumed_list = {}
for name, co_group in pairs(co_groups) do
-- get coroutine and limit in waiting group
local item = co_groups_waiting and co_groups_waiting[name] or nil
if item then
local co_waiting = item[1]
local limit = item[2]
-- get dead coroutines count in this group
local count = 0
for _, co in ipairs(co_group) do
if count < limit then
if co:is_dead() then
count = count + 1
end
else
break
end
end
-- resume the waiting coroutine of this group if some coroutines are dead in this group
if count >= limit and co_waiting and co_waiting:is_suspended() then
resumed_count = resumed_count + 1
self._CO_GROUPS_WAITING[name] = nil
table.insert(co_resumed_list, co_waiting)
end
end
end
if #co_resumed_list > 0 then
for _, co_waiting in ipairs(co_resumed_list) do
local ok, errors = self:co_resume(co_waiting)
if not ok then
return -1, errors
end
end
end
end
return resumed_count
end
-- get profiler
function scheduler:_profiler()
local profiler = self._PROFILE
if profiler == nil then
profiler = require("base/profiler")
if not profiler:enabled() then
profiler = false
end
end
return profiler or nil
end
-- start a new coroutine task
function scheduler:co_start(cotask, ...)
return self:co_start_named(nil, cotask, ...)
end
-- start a new named coroutine task
function scheduler:co_start_named(coname, cotask, ...)
return self:co_start_withopt({name = coname}, cotask, ...)
end
-- start a new coroutine task with options
function scheduler:co_start_withopt(opt, cotask, ...)
-- check coroutine task
opt = opt or {}
local coname = opt.name
if not cotask then
return nil, string.format("cannot start coroutine, invalid cotask(%s/%s)", coname and coname or "anonymous", cotask)
end
-- start coroutine
local co
co = _coroutine.new(coname, coroutine.create(function(...)
local profiler = self:_profiler()
if profiler and profiler:enabled() then
profiler:start()
end
self:_co_curdir_update()
self:_co_curenvs_update()
cotask(...)
self:co_tasks()[co:thread()] = nil
if self:co_count() > 0 then
self._CO_COUNT = self:co_count() - 1
end
end))
if opt.isolate then
co:isolate(true)
end
self:co_tasks()[co:thread()] = co
self._CO_COUNT = self:co_count() + 1
if self._STARTED then
local ok, errors = self:co_resume(co, ...)
if not ok then
return nil, errors
end
else
self._CO_READY_TASKS = self._CO_READY_TASKS or {}
table.insert(self._CO_READY_TASKS, {co, table.pack(...)})
end
-- add this coroutine to the pending groups
local co_groups_pending = self._CO_GROUPS_PENDING
if co_groups_pending then
for _, co_group_pending in pairs(co_groups_pending) do
table.insert(co_group_pending, co)
end
end
return co
end
-- resume the given coroutine
function scheduler:co_resume(co, ...)
-- do resume
local ok, errors = coroutine.resume(co:thread(), ...)
local running = self:co_running()
if running then
-- has the current directory been changed? restore it
local curdir = self._CO_CURDIR_HASH
local olddir = self._CO_CURDIRS and self._CO_CURDIRS[running] or nil
if olddir and curdir ~= olddir[1] then -- hash changed?
os.cd(olddir[2])
end
-- has the current environments been changed? restore it
local curenvs = self._CO_CURENVS_HASH
local oldenvs = self._CO_CURENVS and self._CO_CURENVS[running] or nil
if oldenvs and curenvs ~= oldenvs[1] and running:is_isolated() then -- hash changed?
os.setenvs(oldenvs[2])
end
end
return ok, errors
end
-- suspend the current coroutine
function scheduler:co_suspend(...)
-- suspend it
local results = table.pack(coroutine.yield(...))
-- has the current directory been changed? restore it
local running = assert(self:co_running())
local curdir = self._CO_CURDIR_HASH
local olddir = self._CO_CURDIRS and self._CO_CURDIRS[running] or nil
if olddir and curdir ~= olddir[1] then -- hash changed?
os.cd(olddir[2])
end
-- has the current environments been changed? restore it
local curenvs = self._CO_CURENVS_HASH
local oldenvs = self._CO_CURENVS and self._CO_CURENVS[running] or nil
if oldenvs and curenvs ~= oldenvs[1] and running:is_isolated() then -- hash changed?
os.setenvs(oldenvs[2])
end
-- return results
return table.unpack(results)
end
-- yield the current coroutine
function scheduler:co_yield()
return scheduler.co_sleep(self, 1)
end
-- sleep some times (ms)
function scheduler:co_sleep(ms)
-- we don't need to sleep
if ms == 0 then
return true
end
-- get the running coroutine
local running = self:co_running()
if not running then
return false, "we must call sleep() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return false, "the scheduler is stopped!"
end
-- register timeout task to timer
self:_timer():post(function (cancel)
if running:is_suspended() then
return self:co_resume(running)
end
return true
end, ms)
-- wait
self:co_suspend()
return true
end
-- lock the current coroutine
function scheduler:co_lock(lockname)
-- get the running coroutine
local running = self:co_running()
if not running then
return false, "we must call co_lock() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return false, "the scheduler is stopped!"
end
-- do lock
local co_locked_tasks = self._CO_LOCKED_TASKS
if co_locked_tasks == nil then
co_locked_tasks = {}
self._CO_LOCKED_TASKS = co_locked_tasks
end
while true do
-- try to lock it
if co_locked_tasks[lockname] == nil then
co_locked_tasks[lockname] = running
return true
-- has been locked by the current coroutine
elseif co_locked_tasks[lockname] == running then
return true
end
-- register timeout task to timer
local function timer_callback (cancel)
if co_locked_tasks[lockname] == nil then
if running:is_suspended() then
return self:co_resume(running)
end
else
self:_timer():post(timer_callback, 500)
end
return true
end
self:_timer():post(timer_callback, 500)
-- wait
self:co_suspend()
end
return true
end
-- unlock the current coroutine
function scheduler:co_unlock(lockname)
-- get the running coroutine
local running = self:co_running()
if not running then
return false, "we must call co_unlock() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return false, "the scheduler is stopped!"
end
-- do unlock
local co_locked_tasks = self._CO_LOCKED_TASKS
if co_locked_tasks == nil then
co_locked_tasks = {}
self._CO_LOCKED_TASKS = co_locked_tasks
end
if co_locked_tasks[lockname] == nil then
return false, string.format("we need to call lock(%s) first before calling unlock(%s)", lockname, lockname)
end
if co_locked_tasks[lockname] == running then
co_locked_tasks[lockname] = nil
else
return false, string.format("unlock(%s) is called in other %s", lockname, running)
end
return true
end
-- get the given coroutine group
function scheduler:co_group(name)
return self._CO_GROUPS and self._CO_GROUPS[name]
end
-- begin coroutine group
function scheduler:co_group_begin(name, scopefunc)
-- enter groups
self._CO_GROUPS = self._CO_GROUPS or {}
self._CO_GROUPS_PENDING = self._CO_GROUPS_PENDING or {}
if self._CO_GROUPS_PENDING[name] then
return false, string.format("co_group(%s): already exists!", name)
end
self._CO_GROUPS_PENDING[name] = self._CO_GROUPS_PENDING[name] or {}
-- call the scope function
local co_group = self._CO_GROUPS[name] or {}
local ok, errors = utils.trycall(scopefunc, nil, co_group)
if not ok then
return false, errors
end
-- leave groups
self._CO_GROUPS[name] = co_group
table.join2(self._CO_GROUPS[name], self._CO_GROUPS_PENDING[name])
self._CO_GROUPS_PENDING[name] = nil
return true
end
-- wait for finishing the given coroutine group
function scheduler:co_group_wait(name, opt)
-- get coroutine group
local co_group = self:co_group(name)
if not co_group or #co_group == 0 then
-- no coroutines in this group
return true
end
-- get the running coroutine
local running = self:co_running()
if not running then
return false, "we must call co_group_wait() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return false, "the scheduler is stopped!"
end
-- get limit count
local limit = opt and opt.limit or #co_group
-- wait it
local count
repeat
count = 0
for _, co in ipairs(co_group) do
if count < limit then
if co:is_dead() then
count = count + 1
end
else
break
end
end
if count < limit then
self._CO_GROUPS_WAITING = self._CO_GROUPS_WAITING or {}
self._CO_GROUPS_WAITING[name] = {running, limit}
self:co_suspend()
end
until count >= limit
-- remove all dead coroutines in group
if limit == #co_group and count == limit then
self._CO_GROUPS[name] = nil
else
for i = #co_group, 1, -1 do
local co = co_group[i]
if co:is_dead() then
table.remove(co_group, i)
end
end
end
return true
end
-- get waiting objects for the given group name
function scheduler:co_group_waitobjs(name)
local objs = hashset.new()
for _, co in ipairs(table.wrap(self:co_group(name))) do
if not co:is_dead() then
local obj = co:waitobj()
if obj then
objs:insert(obj)
end
end
end
return objs
end
-- get the current running coroutine
function scheduler:co_running()
if self._ENABLED then
local running = coroutine.running()
return running and self:co_tasks()[running] or nil
end
end
-- get all coroutine tasks
function scheduler:co_tasks()
local cotasks = self._CO_TASKS
if not cotasks then
cotasks = {}
self._CO_TASKS = cotasks
end
return cotasks
end
-- get all coroutine count
function scheduler:co_count()
return self._CO_COUNT or 0
end
-- wait poller object io events, only for socket and pipe object
function scheduler:poller_wait(obj, events, timeout)
-- get the running coroutine
local running = self:co_running()
if not running then
return -1, "we must call poller_wait() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return -1, "the scheduler is stopped!"
end
-- check the object type
local otype = obj:otype()
if otype ~= poller.OT_SOCK and otype ~= poller.OT_PIPE then
return -1, string.format("%s: invalid object type(%d)!", obj, otype)
end
-- get and allocate poller object data
local pollerdata = self:_poller_data(obj)
if not pollerdata then
pollerdata = {poller_events_wait = 0, poller_events_save = 0}
self:_poller_data_set(obj, pollerdata)
end
-- enable edge-trigger mode if be supported
if self._SUPPORT_EV_POLLER_CLEAR and (otype == poller.OT_SOCK or otype == poller.OT_PIPE) then
events = bit.bor(events, poller.EV_POLLER_CLEAR)
end
-- get the previous poller object events
local events_wait = events
if pollerdata.poller_events_wait ~= 0 then
-- return the cached events directly if the waiting events exists cache
local events_prev_wait = pollerdata.poller_events_wait
local events_prev_save = pollerdata.poller_events_save
if events_prev_save ~= 0 and bit.band(events_prev_wait, events) ~= 0 then
-- check error?
if bit.band(events_prev_save, poller.EV_POLLER_ERROR) ~= 0 then
pollerdata.poller_events_save = 0
return -1, string.format("%s: events error!", obj)
end
-- clear cache events
pollerdata.poller_events_save = bit.band(events_prev_save, bit.bnot(events))
-- return the cached events
return bit.band(events_prev_save, events)
end
-- modify the wait events and reserve the pending events in other coroutine
events_wait = events_prev_wait
if bit.band(events_wait, poller.EV_POLLER_RECV) ~= 0 and not pollerdata.co_recv then
events_wait = bit.band(events_wait, bit.bnot(poller.EV_POLLER_RECV))
end
if bit.band(events_wait, poller.EV_POLLER_SEND) ~= 0 and not pollerdata.co_send then
events_wait = bit.band(events_wait, bit.bnot(poller.EV_POLLER_SEND))
end
events_wait = bit.bor(events_wait, events)
-- modify poller object from poller for waiting events if the waiting events has been changed
if bit.band(events_prev_wait, events_wait) ~= events_wait then
-- maybe wait recv/send at same time
local ok, errors = poller:modify(obj, events_wait, self._poller_events_cb)
if not ok then
return -1, errors
end
end
else
-- insert poller object events
local ok, errors = poller:insert(obj, events_wait, self._poller_events_cb)
if not ok then
return -1, errors
end
end
-- register timeout task to timer
local timer_task = nil
if timeout > 0 then
timer_task = self:_timer():post(function (cancel)
if not cancel and running:is_suspended() then
running:waitobj_set(nil)
return self:co_resume(running, 0)
end
return true
end, timeout)
end
running:_timer_task_set(timer_task)
-- save waiting events
pollerdata.poller_events_wait = events_wait
pollerdata.poller_events_save = 0
-- save the current coroutine
if bit.band(events, poller.EV_POLLER_RECV) ~= 0 then
pollerdata.co_recv = running
end
if bit.band(events, poller.EV_POLLER_SEND) ~= 0 then
pollerdata.co_send = running
end
-- save the waiting poller object
running:waitobj_set(obj)
-- wait
return self:co_suspend()
end
-- wait poller object/process status
function scheduler:poller_waitproc(obj, timeout)
-- get the running coroutine
local running = self:co_running()
if not running then
return -1, "we must call poller_wait() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return -1, "the scheduler is stopped!"
end
-- check the object type
local otype = obj:otype()
if otype ~= poller.OT_PROC then
return -1, string.format("%s: invalid object type(%d)!", obj, otype)
end
-- get and allocate poller object data
local pollerdata = self:_poller_data(obj)
if not pollerdata then
pollerdata = {object_pending = 0, object_event = 0}
self:_poller_data_set(obj, pollerdata)
end
-- has pending process status?
if pollerdata.object_pending ~= 0 then
pollerdata.object_pending = 0
return 1, pollerdata.object_event
end
-- insert poller object to poller for waiting process
local ok, errors = poller:insert(obj, 0, self._poller_events_cb)
if not ok then
return -1, errors
end
-- register timeout task to timer
local timer_task = nil
if timeout > 0 then
timer_task = self:_timer():post(function (cancel)
if not cancel and running:is_suspended() then
pollerdata.co_waiting = nil
running:waitobj_set(nil)
return self:co_resume(running, 0)
end
return true
end, timeout)
end
running:_timer_task_set(timer_task)
-- set process status
pollerdata.object_event = 0
pollerdata.object_pending = 0
pollerdata.co_waiting = running
-- save the waiting poller object
running:waitobj_set(obj)
-- wait
local ok = self:co_suspend()
return ok, pollerdata.object_event
end
-- wait poller object/fwatcher status
function scheduler:poller_waitfs(obj, timeout)
-- get the running coroutine
local running = self:co_running()
if not running then
return -1, "we must call poller_wait() in coroutine with scheduler!"
end
-- is stopped?
if not self._STARTED then
return -1, "the scheduler is stopped!"
end
-- check the object type
local otype = obj:otype()
if otype ~= poller.OT_FWATCHER then
return -1, string.format("%s: invalid object type(%d)!", obj, otype)
end
-- get and allocate poller object data
local pollerdata = self:_poller_data(obj)
if not pollerdata then
pollerdata = {object_pending = 0, object_event = 0}
self:_poller_data_set(obj, pollerdata)
end
-- has pending process status?
if pollerdata.object_pending ~= 0 then
pollerdata.object_pending = 0
return 1, pollerdata.object_event
end
-- insert poller object to poller for waiting fwatcher
local ok, errors = poller:insert(obj, 0, self._poller_events_cb)
if not ok then
return -1, errors
end
-- register timeout task to timer
local timer_task = nil
if timeout > 0 then
timer_task = self:_timer():post(function (cancel)
if not cancel and running:is_suspended() then
pollerdata.co_waiting = nil
running:waitobj_set(nil)
return self:co_resume(running, 0)
end
return true
end, timeout)
end
running:_timer_task_set(timer_task)
-- set fwatcher status
pollerdata.object_event = 0
pollerdata.object_pending = 0
pollerdata.co_waiting = running
-- save the waiting poller object
running:waitobj_set(obj)
-- wait
local ok = self:co_suspend()
return ok, pollerdata.object_event
end
-- cancel poller object events
function scheduler:poller_cancel(obj)
-- reset the pollerdata data
local pollerdata = self:_poller_data(obj)
if pollerdata then
if pollerdata.poller_events_wait ~= 0 or obj:otype() == poller.OT_PROC or obj:otype() == poller.OT_FWATCHER then
local ok, errors = poller:remove(obj)
if not ok then
return false, errors
end
end
self:_poller_data_set(obj, nil)
end
return true
end
-- enable or disable to scheduler
function scheduler:enable(enabled)
self._ENABLED = enabled
end
-- stop the scheduler loop
function scheduler:stop()
-- mark scheduler status as stopped and spank the poller:wait()
self._STARTED = false
poller:spank()
return true
end
-- run loop, schedule coroutine with socket/io, sub-processes, fwatcher
function scheduler:runloop()
-- start loop
self._STARTED = true
self._ENABLED = true
-- ensure poller has been initialized first (for windows/iocp) and check edge-trigger mode (for epoll/kqueue)
if poller:support(poller.EV_POLLER_CLEAR) then
self._SUPPORT_EV_POLLER_CLEAR = true
end
-- set on change directory callback for scheduler
os._sched_chdir_set(function (curdir)
self:_co_curdir_update(curdir)
end)
-- set on change environments callback for scheduler
os._sched_chenvs_set(function (envs)
self:_co_curenvs_update(envs)
end)
-- start all ready coroutine tasks
local co_ready_tasks = self._CO_READY_TASKS
if co_ready_tasks then
for _, task in pairs(co_ready_tasks) do
local co = task[1]
local argv = task[2]
local ok, errors = self:co_resume(co, table.unpack(argv))
if not ok then
return false, errors
end
end
end
self._CO_READY_TASKS = nil
-- run loop
opt = opt or {}
local ok = true
local errors = nil
local timeout = -1
while self._STARTED and self:co_count() > 0 do
-- resume it's waiting coroutine if some coroutines are dead in group
local resumed_count, resumed_errors = self:_co_groups_resume()
if resumed_count < 0 then
ok = false
errors = resumed_errors
break
elseif resumed_count == 0 then
-- get the next timeout
timeout = self:_timer():delay() or 1000
-- wait events
local count, events = poller:wait(timeout)
if count < 0 then
ok = false
errors = events
break
end
-- resume all suspended tasks with events
for _, e in ipairs(events) do
local obj = e[1]
local objevents = e[2]
local eventfunc = e[3]
if eventfunc then
ok, errors = eventfunc(self, obj, objevents)
if not ok then
-- This causes a direct exit from the entire runloop and
-- a quick escape from nested try-catch blocks and coroutines groups.
--
-- So some try-catch cannot catch these errors, such as when a build fails (in build group).
-- @see https://github.com/xmake-io/xmake/issues/3401
--
-- We should catch it in coroutines and re-throw it outside scheduler,
-- it will avoid co_resume to get and return this error.
--
-- e.g. we can see runjobs.lua implementation
break
end
end
end
if not ok then
break
end
end
-- spank the timer and trigger all timeout tasks
ok, errors = self:_timer():next()
if not ok then
break
end
end
-- mark the loop as stopped first
self._STARTED = false
-- cancel all timeout tasks and trigger them
self:_timer():kill()
-- finished and we need not resume other pending coroutines, because xmake will be aborted directly if fails
return ok, errors
end
-- return module: scheduler
return scheduler
|