vibe.core.core 45/603(7%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
13470
13480
13490
13500
13510
13520
13530
13540
13550
13560
13570
13580
13590
13600
13610
13620
13630
13640
13650
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
14120
14130
14140
14150
14160
14170
14180
14190
14200
14210
14220
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
14360
14370
14380
14390
14400
14410
14420
14430
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
14860
14870
14880
14890
14900
14910
14920
14930
14940
14950
14960
14970
14980
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15453
15460
15470
15480
15490
15500
15510
15520
15530
15540
15550
15560
15570
15580
15590
15600
15610
15620
15630
15640
15650
15660
15670
15680
15690
15700
15710
15720
15730
15740
15750
15760
15770
15780
15790
15800
15810
15820
15830
15840
15850
15860
15870
15880
15890
15900
15910
15920
15930
15940
15950
15960
15970
15980
15990
16000
16010
16020
16030
16040
16050
16060
16070
16080
16090
16100
16110
16120
16131
16140
16150
16160
16170
16180
16190
16200
16210
16220
16230
16240
16250
16260
16270
16280
16290
16300
16310
16320
16330
16340
16350
16360
16370
16380
16390
16400
16410
16420
16430
16440
16450
16460
16470
16480
16490
16500
16510
16520
16530
16540
16550
16560
16570
16580
16590
16601
16610
16620
16630
16640
16650
16660
16670
16680
16690
16700
16710
16720
16730
16740
16750
16760
16770
16780
16793
16800
16811
16820
16831
16840
16851
16861
16871
16880
16891
16901
16911
16921
16930
16941
16950
16961
16970
16980
16990
17000
17010
17020
17030
17040
17051
17061
17070
17080
17090
17100
17111
17120
17130
17140
17150
17160
17170
17180
17190
17200
17210
17220
17230
17240
17250
17260
17270
17280
17290
17300
17310
17320
17330
17340
17350
17360
17370
17380
17392
17400
17411
17420
17431
17443
17452
17460
17470
17480
17490
17501
17510
17520
17530
17540
17550
17561
17570
17580
17590
17600
17610
17620
17631
17640
17651
17660
17673
17682
17690
17700
17711
17721
17731
17741
17750
17761
17770
17780
17790
17800
17811
17820
17830
17841
17851
17861
17871
17880
17890
17900
17910
17921
17930
17941
17950
17960
17970
17980
17993
18000
18011
18021
18031
18040
18050
18060
18070
18080
18090
18100
18110
18120
18130
18140
18150
18160
18170
18180
18190
18200
18210
18220
18230
18240
18250
18260
18270
18280
18290
18300
18310
18320
18330
18340
18350
18360
18370
18380
18390
18400
18410
18420
18430
18440
18450
18460
18470
18480
18490
18500
18510
18520
18530
18540
18550
18560
18570
18580
18590
18600
18610
18620
18630
18640
18650
18660
18670
18680
18690
18700
18710
18720
18730
18740
18750
18760
18770
18780
18790
18800
18810
18820
18830
18840
18850
18860
18870
18880
18890
18900
18910
18920
18930
18940
18950
18960
18970
18980
18990
19000
19010
19020
19030
19040
19050
19060
19070
19080
19090
19100
19110
19120
19130
19140
19150
19160
19170
19180
19190
19200
19210
19220
19230
19240
19250
19260
19270
19280
19290
19300
19310
19320
19330
19340
19350
19360
19370
19380
19390
19400
19410
19420
19430
19440
19450
19460
19470
19480
19490
19500
19510
19520
19530
19540
19550
19560
19570
19580
19590
19600
19610
19620
19630
19640
19650
19660
19670
19680
19690
19700
19710
19720
19730
19740
19750
19760
19770
19780
19790
19800
19810
19820
19830
19840
19850
19860
19870
19880
19890
19900
19910
19920
19930
19940
19950
19960
19970
19980
19990
20000
20010
20020
20030
20040
20050
20060
20070
20080
20090
20100
20110
20120
20130
20140
20150
20160
20170
20180
20190
20200
20210
20220
20230
20240
20250
20260
20270
20280
20290
20300
20310
20320
20330
20340
20350
20360
20370
20380
20390
20400
20410
20420
20430
20440
20450
20460
20470
20480
20490
20500
20510
20520
20530
20540
20550
20560
20570
20580
/** This module contains the core functionality of the vibe.d framework. See `runApplication` for the main entry point for typical vibe.d server or GUI applications. Copyright: © 2012-2016 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.core.core; public import vibe.core.driver; import vibe.core.args; import vibe.core.concurrency; import vibe.core.log; import vibe.utils.array; import std.algorithm; import std.conv; import std.encoding; import core.exception; import std.exception; import std.functional; import std.range : empty, front, popFront; import std.string; import std.variant; import std.typecons : Typedef, Tuple, tuple; import core.atomic; import core.sync.condition; import core.sync.mutex; import core.stdc.stdlib; import core.thread; alias TaskEventCb = void function(TaskEvent, Task) nothrow; version(Posix) { import core.sys.posix.signal; import core.sys.posix.unistd; import core.sys.posix.pwd; static if (__traits(compiles, {import core.sys.posix.grp; getgrgid(0);})) { import core.sys.posix.grp; } else { extern (C) { struct group { char* gr_name; char* gr_passwd; gid_t gr_gid; char** gr_mem; } group* getgrgid(gid_t); group* getgrnam(in char*); } } } version (Windows) { import core.stdc.signal; } /**************************************************************************************************/ /* Public functions */ /**************************************************************************************************/ /** Performs final initialization and runs the event loop. This function performs three tasks: $(OL $(LI Makes sure that no unrecognized command line options are passed to the application and potentially displays command line help. See also `vibe.core.args.finalizeCommandLineOptions`.) $(LI Performs privilege lowering if required.) $(LI Runs the event loop and blocks until it finishes.) ) Params: args_out = Optional parameter to receive unrecognized command line arguments. If left to `null`, an error will be reported if any unrecognized argument is passed. See_also: ` vibe.core.args.finalizeCommandLineOptions`, `lowerPrivileges`, `runEventLoop` */ int runApplication(scope void delegate(string[]) args_out = null) { try { string[] args; if (!finalizeCommandLineOptions(args_out is null ? null : &args)) return 0; if (args_out) args_out(args); } catch (Exception e) { logDiagnostic("Error processing command line: %s", e.msg); return 1; } lowerPrivileges(); logDiagnostic("Running event loop..."); int status; version (VibeDebugCatchAll) { try { status = runEventLoop(); } catch( Throwable th ){ logError("Unhandled exception in event loop: %s", th.msg); logDiagnostic("Full exception: %s", th.toString().sanitize()); return 1; } } else { status = runEventLoop(); } logDiagnostic("Event loop exited with status %d.", status); return status; } /// A simple echo server, listening on a privileged TCP port. unittest { import vibe.core.core; import vibe.core.net; int main() { // first, perform any application specific setup (privileged ports still // available if run as root) listenTCP(7, (conn) { conn.pipe(conn); }); // then use runApplication to perform the remaining initialization and // to run the event loop return runApplication(); } } /** The same as above, but performing the initialization sequence manually. This allows to skip any additional initialization (opening the listening port) if an invalid command line argument or the `--help` switch is passed to the application. */ unittest { import vibe.core.core; import vibe.core.net; int main() { // process the command line first, to be able to skip the application // setup if not required if (!finalizeCommandLineOptions()) return 0; // then set up the application listenTCP(7, (conn) { conn.pipe(conn); }); // finally, perform privilege lowering (safe to skip for non-server // applications) lowerPrivileges(); // and start the event loop return runEventLoop(); } } /** Starts the vibe.d event loop for the calling thread. Note that this function is usually called automatically by the vibe.d framework. However, if you provide your own `main()` function, you may need to call either this or `runApplication` manually. The event loop will by default continue running during the whole life time of the application, but calling `runEventLoop` multiple times in sequence is allowed. Tasks will be started and handled only while the event loop is running. Returns: The returned value is the suggested code to return to the operating system from the `main` function. See_Also: `runApplication` */ int runEventLoop() { setupSignalHandlers(); logDebug("Starting event loop."); s_eventLoopRunning = true; scope (exit) { s_eventLoopRunning = false; s_exitEventLoop = false; st_threadShutdownCondition.notifyAll(); } // runs any yield()ed tasks first assert(!s_exitEventLoop); s_exitEventLoop = false; driverCore.notifyIdle(); if (getExitFlag()) return 0; // handle exit flag in the main thread to exit when // exitEventLoop(true) is called from a thread) if (Thread.getThis() is st_threads[0].thread) runTask(toDelegate(&watchExitFlag)); if (auto err = getEventDriver().runEventLoop() != 0) { if (err == 1) { logDebug("No events active, exiting message loop."); return 0; } logError("Error running event loop: %d", err); return 1; } logDebug("Event loop done."); return 0; } /** Stops the currently running event loop. Calling this function will cause the event loop to stop event processing and the corresponding call to runEventLoop() will return to its caller. Params: shutdown_all_threads = If true, exits event loops of all threads - false by default. Note that the event loops of all threads are automatically stopped when the main thread exits, so usually there is no need to set shutdown_all_threads to true. */ void exitEventLoop(bool shutdown_all_threads = false) { logDebug("exitEventLoop called (%s)", shutdown_all_threads); assert(s_eventLoopRunning || shutdown_all_threads, "Trying to exit event loop when no loop is running."); if (shutdown_all_threads) { atomicStore(st_term, true); st_threadsSignal.emit(); } // shutdown the calling thread s_exitEventLoop = true; if (s_eventLoopRunning) getEventDriver().exitEventLoop(); } /** Process all pending events without blocking. Checks if events are ready to trigger immediately, and run their callbacks if so. Returns: Returns false $(I iff) exitEventLoop was called in the process. */ bool processEvents() { if (!getEventDriver().processEvents()) return false; driverCore.notifyIdle(); return true; } /** Sets a callback that is called whenever no events are left in the event queue. The callback delegate is called whenever all events in the event queue have been processed. Returning true from the callback will cause another idle event to be triggered immediately after processing any events that have arrived in the meantime. Returning false will instead wait until another event has arrived first. */ void setIdleHandler(void delegate() @safe del) { s_idleHandler = { del(); return false; }; } /// ditto void setIdleHandler(bool delegate() @safe del) { s_idleHandler = del; } /// Scheduled for deprecation - use a `@safe` callback instead. void setIdleHandler(void delegate() @system del) @system { s_idleHandler = () @trusted { del(); return false; }; } /// ditto void setIdleHandler(bool delegate() @system del) @system { s_idleHandler = () @trusted => del(); } /** Runs a new asynchronous task. task will be called synchronously from within the vibeRunTask call. It will continue to run until vibeYield() or any of the I/O or wait functions is called. Note that the maximum size of all args must not exceed `maxTaskParameterSize`. */ Task runTask(ARGS...)(void delegate(ARGS) @safe task, ARGS args) { auto tfi = makeTaskFuncInfo(task, args); return runTask_internal(tfi); } /// ditto Task runTask(ARGS...)(void delegate(ARGS) task, ARGS args) { auto tfi = makeTaskFuncInfo(task, args); return runTask_internal(tfi); } private Task runTask_internal(ref TaskFuncInfo tfi) @safe nothrow { import std.typecons : Tuple, tuple; CoreTask f; while (!f && !s_availableFibers.empty) { f = s_availableFibers.back; s_availableFibers.popBack(); if (() @trusted nothrow { return f.state; } () != Fiber.State.HOLD) f = null; } if (f is null) { // if there is no fiber available, create one. if (s_availableFibers.capacity == 0) s_availableFibers.capacity = 1024; logDebugV("Creating new fiber..."); s_fiberCount++; f = new CoreTask; } f.m_taskFunc = tfi; f.bumpTaskCounter(); auto handle = f.task(); debug Task self = Task.getThis(); debug if (s_taskEventCallback) { if (self != Task.init) () @trusted { s_taskEventCallback(TaskEvent.yield, self); } (); () @trusted { s_taskEventCallback(TaskEvent.preStart, handle); } (); } driverCore.resumeTask(handle, null, true); debug if (s_taskEventCallback) { () @trusted { s_taskEventCallback(TaskEvent.postStart, handle); } (); if (self != Task.init) () @trusted { s_taskEventCallback(TaskEvent.resume, self); } (); } return handle; } @safe unittest { runTask({}); } /** Runs a new asynchronous task in a worker thread. Only function pointers with weakly isolated arguments are allowed to be able to guarantee thread-safety. */ void runWorkerTask(FT, ARGS...)(FT func, auto ref ARGS args) if (is(typeof(*func) == function)) { foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads."); runWorkerTask_unsafe(func, args); } /// ditto void runWorkerTask(alias method, T, ARGS...)(shared(T) object, auto ref ARGS args) if (is(typeof(__traits(getMember, object, __traits(identifier, method))))) { foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads."); auto func = &__traits(getMember, object, __traits(identifier, method)); runWorkerTask_unsafe(func, args); } /** Runs a new asynchronous task in a worker thread, returning the task handle. This function will yield and wait for the new task to be created and started in the worker thread, then resume and return it. Only function pointers with weakly isolated arguments are allowed to be able to guarantee thread-safety. */ Task runWorkerTaskH(FT, ARGS...)(FT func, auto ref ARGS args) if (is(typeof(*func) == function)) { foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads."); alias PrivateTask = Typedef!(Task, Task.init, __PRETTY_FUNCTION__); Task caller = Task.getThis(); // workaround for runWorkerTaskH to work when called outside of a task if (caller == Task.init) { Task ret; runTask({ ret = runWorkerTaskH(func, args); }).join(); return ret; } assert(caller != Task.init, "runWorkderTaskH can currently only be called from within a task."); static void taskFun(Task caller, FT func, ARGS args) { PrivateTask callee = Task.getThis(); caller.prioritySendCompat(callee); mixin(callWithMove!ARGS("func", "args")); } runWorkerTask_unsafe(&taskFun, caller, func, args); return () @trusted { return cast(Task)receiveOnlyCompat!PrivateTask(); } (); } /// ditto Task runWorkerTaskH(alias method, T, ARGS...)(shared(T) object, auto ref ARGS args) if (is(typeof(__traits(getMember, object, __traits(identifier, method))))) { foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads."); auto func = &__traits(getMember, object, __traits(identifier, method)); alias FT = typeof(func); alias PrivateTask = Typedef!(Task, Task.init, __PRETTY_FUNCTION__); Task caller = Task.getThis(); // workaround for runWorkerTaskH to work when called outside of a task if (caller == Task.init) { Task ret; runTask({ ret = runWorkerTaskH!method(object, args); }).join(); return ret; } assert(caller != Task.init, "runWorkderTaskH can currently only be called from within a task."); static void taskFun(Task caller, FT func, ARGS args) { PrivateTask callee = Task.getThis(); () @trusted { caller.prioritySendCompat(callee); } (); mixin(callWithMove!ARGS("func", "args")); } runWorkerTask_unsafe(&taskFun, caller, func, args); return cast(Task)receiveOnlyCompat!PrivateTask(); } /// Running a worker task using a function unittest { static void workerFunc(int param) { logInfo("Param: %s", param); } static void test() { runWorkerTask(&workerFunc, 42); runWorkerTask(&workerFunc, cast(ubyte)42); // implicit conversion #719 runWorkerTaskDist(&workerFunc, 42); runWorkerTaskDist(&workerFunc, cast(ubyte)42); // implicit conversion #719 } } /// Running a worker task using a class method unittest { static class Test { void workerMethod(int param) shared { logInfo("Param: %s", param); } } static void test() { auto cls = new shared Test; runWorkerTask!(Test.workerMethod)(cls, 42); runWorkerTask!(Test.workerMethod)(cls, cast(ubyte)42); // #719 runWorkerTaskDist!(Test.workerMethod)(cls, 42); runWorkerTaskDist!(Test.workerMethod)(cls, cast(ubyte)42); // #719 } } /// Running a worker task using a function and communicating with it unittest { static void workerFunc(Task caller) { int counter = 10; while (receiveOnlyCompat!string() == "ping" && --counter) { logInfo("pong"); caller.sendCompat("pong"); } caller.sendCompat("goodbye"); } static void test() { Task callee = runWorkerTaskH(&workerFunc, Task.getThis); do { logInfo("ping"); callee.sendCompat("ping"); } while (receiveOnlyCompat!string() == "pong"); } static void work719(int) {} static void test719() { runWorkerTaskH(&work719, cast(ubyte)42); } } /// Running a worker task using a class method and communicating with it unittest { static class Test { void workerMethod(Task caller) shared { int counter = 10; while (receiveOnlyCompat!string() == "ping" && --counter) { logInfo("pong"); caller.sendCompat("pong"); } caller.sendCompat("goodbye"); } } static void test() { auto cls = new shared Test; Task callee = runWorkerTaskH!(Test.workerMethod)(cls, Task.getThis()); do { logInfo("ping"); callee.sendCompat("ping"); } while (receiveOnlyCompat!string() == "pong"); } static class Class719 { void work(int) shared {} } static void test719() { auto cls = new shared Class719; runWorkerTaskH!(Class719.work)(cls, cast(ubyte)42); } } unittest { // run and join worker task from outside of a task __gshared int i = 0; auto t = runWorkerTaskH({ sleep(5.msecs); i = 1; }); // FIXME: joining between threads not yet supported //t.join(); //assert(i == 1); } private void runWorkerTask_unsafe(CALLABLE, ARGS...)(CALLABLE callable, ref ARGS args) { import std.traits : ParameterTypeTuple; import vibe.internal.meta.traits : areConvertibleTo; import vibe.internal.meta.typetuple; alias FARGS = ParameterTypeTuple!CALLABLE; static assert(areConvertibleTo!(Group!ARGS, Group!FARGS), "Cannot convert arguments '"~ARGS.stringof~"' to function arguments '"~FARGS.stringof~"'."); setupWorkerThreads(); auto tfi = makeTaskFuncInfo(callable, args); () @trusted { synchronized (st_threadsMutex) st_workerTasks ~= tfi; st_threadsSignal.emit(); } (); } /** Runs a new asynchronous task in all worker threads concurrently. This function is mainly useful for long-living tasks that distribute their work across all CPU cores. Only function pointers with weakly isolated arguments are allowed to be able to guarantee thread-safety. The number of tasks started is guaranteed to be equal to `workerThreadCount`. */ void runWorkerTaskDist(FT, ARGS...)(FT func, auto ref ARGS args) if (is(typeof(*func) == function)) { foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads."); runWorkerTaskDist_unsafe(func, args); } /// ditto void runWorkerTaskDist(alias method, T, ARGS...)(shared(T) object, ARGS args) { auto func = &__traits(getMember, object, __traits(identifier, method)); foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads."); runWorkerTaskDist_unsafe(func, args); } private void runWorkerTaskDist_unsafe(CALLABLE, ARGS...)(ref CALLABLE callable, ref ARGS args) { import std.traits : ParameterTypeTuple; import vibe.internal.meta.traits : areConvertibleTo; import vibe.internal.meta.typetuple; alias FARGS = ParameterTypeTuple!CALLABLE; static assert(areConvertibleTo!(Group!ARGS, Group!FARGS), "Cannot convert arguments '"~ARGS.stringof~"' to function arguments '"~FARGS.stringof~"'."); setupWorkerThreads(); auto tfi = makeTaskFuncInfo(callable, args); synchronized (st_threadsMutex) { foreach (ref ctx; st_threads) if (ctx.isWorker) ctx.taskQueue ~= tfi; } st_threadsSignal.emit(); } private TaskFuncInfo makeTaskFuncInfo(CALLABLE, ARGS...)(ref CALLABLE callable, ref ARGS args) { import std.algorithm : move; import std.traits : hasElaborateAssign; static struct TARGS { ARGS expand; } static assert(CALLABLE.sizeof <= TaskFuncInfo.callable.length); static assert(TARGS.sizeof <= maxTaskParameterSize, "The arguments passed to run(Worker)Task must not exceed "~ maxTaskParameterSize.to!string~" bytes in total size."); static void callDelegate(TaskFuncInfo* tfi) { assert(tfi.func is &callDelegate); // copy original call data to stack CALLABLE c; TARGS args; move(*(cast(CALLABLE*)tfi.callable.ptr), c); move(*(cast(TARGS*)tfi.args.ptr), args); // reset the info tfi.func = null; // make the call mixin(callWithMove!ARGS("c", "args.expand")); } TaskFuncInfo tfi; tfi.func = &callDelegate; static if (hasElaborateAssign!CALLABLE) tfi.initCallable!CALLABLE(); static if (hasElaborateAssign!TARGS) tfi.initArgs!TARGS(); () @trusted { tfi.typedCallable!CALLABLE = callable; foreach (i, A; ARGS) { static if (needsMove!A) args[i].move(tfi.typedArgs!TARGS.expand[i]); else tfi.typedArgs!TARGS.expand[i] = args[i]; } } (); return tfi; } import core.cpuid : threadsPerCPU; /** Sets up the thread pool used for executing worker tasks. This function gives explicit control over the number of worker threads. Note, to have an effect the function must be called before any worker tasks are started. Otherwise the default number of worker threads (`logicalProcessorCount`) will be used automatically. Params: num = The number of worker threads to initialize. Defaults to `logicalProcessorCount`. See_also: `runWorkerTask`, `runWorkerTaskH`, `runWorkerTaskDist` */ public void setupWorkerThreads(uint num = logicalProcessorCount()) @safe { static bool s_workerThreadsStarted = false; if (s_workerThreadsStarted) return; s_workerThreadsStarted = true; () @trusted { synchronized (st_threadsMutex) { if (st_threads.any!(t => t.isWorker)) return; foreach (i; 0 .. num) { auto thr = new Thread(&workerThreadFunc); thr.name = format("Vibe Task Worker #%s", i); st_threads ~= ThreadContext(thr, true); thr.start(); } } } (); } /** Determines the number of logical processors in the system. This number includes virtual cores on hyper-threading enabled CPUs. */ public @property uint logicalProcessorCount() { version (linux) { import core.sys.linux.sys.sysinfo; return get_nprocs(); } else version (OSX) { int count; size_t count_len = count.sizeof; sysctlbyname("hw.logicalcpu", &count, &count_len, null, 0); return cast(uint)count_len; } else version (FreeBSD) { int count; size_t count_len = count.sizeof; sysctlbyname("hw.logicalcpu", &count, &count_len, null, 0); return cast(uint)count_len; } else version (NetBSD) { int count; size_t count_len = count.sizeof; sysctlbyname("hw.logicalcpu", &count, &count_len, null, 0); return cast(uint)count_len; } else version (Solaris) { return get_nprocs(); } else version (Windows) { import core.sys.windows.windows; SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; } else static assert(false, "Unsupported OS!"); } version (OSX) private extern(C) int sysctlbyname(const(char)* name, void* oldp, size_t* oldlen, void* newp, size_t newlen); version (FreeBSD) private extern(C) int sysctlbyname(const(char)* name, void* oldp, size_t* oldlen, void* newp, size_t newlen); version (NetBSD) private extern(C) int sysctlbyname(const(char)* name, void* oldp, size_t* oldlen, void* newp, size_t newlen); version (Solaris) private extern(C) int get_nprocs(); /** Suspends the execution of the calling task to let other tasks and events be handled. Calling this function in short intervals is recommended if long CPU computations are carried out by a task. It can also be used in conjunction with Signals to implement cross-fiber events with no polling. Throws: May throw an `InterruptException` if `Task.interrupt()` gets called on the calling task. */ void yield() @safe { // throw any deferred exceptions driverCore.processDeferredExceptions(); auto t = CoreTask.getThis(); if (t && t !is CoreTask.ms_coreTask) { assert(!t.m_queue, "Calling yield() when already yielded!?"); if (!t.m_queue) s_yieldedTasks.insertBack(t); scope (exit) assert(t.m_queue is null, "Task not removed from yielders queue after being resumed."); rawYield(); } else { // Let yielded tasks execute () @trusted { driverCore.notifyIdle(); } (); } } /** Yields execution of this task until an event wakes it up again. Beware that the task will starve if no event wakes it up. */ void rawYield() @safe { driverCore.yieldForEvent(); } /** Suspends the execution of the calling task for the specified amount of time. Note that other tasks of the same thread will continue to run during the wait time, in contrast to $(D core.thread.Thread.sleep), which shouldn't be used in vibe.d applications. */ void sleep(Duration timeout) @safe { assert(timeout >= 0.seconds, "Argument to sleep must not be negative."); if (timeout <= 0.seconds) return; auto tm = setTimer(timeout, null); tm.wait(); } /// unittest { import vibe.core.core : sleep; import vibe.core.log : logInfo; import core.time : msecs; void test() { logInfo("Sleeping for half a second..."); sleep(500.msecs); logInfo("Done sleeping."); } } /** Returns a new armed timer. Note that timers can only work if an event loop is running. Passing a `@system` callback is scheduled for deprecation. Use a `@safe` callback instead. Params: timeout = Determines the minimum amount of time that elapses before the timer fires. callback = This delegate will be called when the timer fires periodic = Speficies if the timer fires repeatedly or only once Returns: Returns a Timer object that can be used to identify and modify the timer. See_also: createTimer */ Timer setTimer(Duration timeout, void delegate() @safe callback, bool periodic = false) @safe { auto tm = createTimer(callback); tm.rearm(timeout, periodic); return tm; } /// ditto Timer setTimer(Duration timeout, void delegate() @system callback, bool periodic = false) @system { return setTimer(timeout, () @trusted => callback(), periodic); } /// unittest { void printTime() @safe { import std.datetime; logInfo("The time is: %s", Clock.currTime()); } void test() { import vibe.core.core; // start a periodic timer that prints the time every second setTimer(1.seconds, &printTime, true); } } /** Creates a new timer without arming it. Passing a `@system` callback is scheduled for deprecation. Use a `@safe` callback instead. See_also: setTimer */ Timer createTimer(void delegate() @safe callback) @safe { auto drv = getEventDriver(); return Timer(drv, drv.createTimer(callback)); } /// ditto Timer createTimer(void delegate() @system callback) @system { return createTimer(() @trusted => callback()); } /** Creates an event to wait on an existing file descriptor. The file descriptor usually needs to be a non-blocking socket for this to work. Params: file_descriptor = The Posix file descriptor to watch event_mask = Specifies which events will be listened for event_mode = Specifies event waiting mode Returns: Returns a newly created FileDescriptorEvent associated with the given file descriptor. */ FileDescriptorEvent createFileDescriptorEvent(int file_descriptor, FileDescriptorEvent.Trigger event_mask, FileDescriptorEvent.Mode event_mode = FileDescriptorEvent.Mode.persistent) { auto drv = getEventDriver(); return drv.createFileDescriptorEvent(file_descriptor, event_mask, event_mode); } /** Sets the stack size to use for tasks. The default stack size is set to 512 KiB on 32-bit systems and to 16 MiB on 64-bit systems, which is sufficient for most tasks. Tuning this value can be used to reduce memory usage for large numbers of concurrent tasks or to avoid stack overflows for applications with heavy stack use. Note that this function must be called at initialization time, before any task is started to have an effect. Also note that the stack will initially not consume actual physical memory - it just reserves virtual address space. Only once the stack gets actually filled up with data will physical memory then be reserved page by page. This means that the stack can safely be set to large sizes on 64-bit systems without having to worry about memory usage. */ void setTaskStackSize(size_t sz) { s_taskStackSize = sz; } /** The number of worker threads used for processing worker tasks. Note that this function will cause the worker threads to be started, if they haven't already. See_also: `runWorkerTask`, `runWorkerTaskH`, `runWorkerTaskDist`, `setupWorkerThreads` */ @property size_t workerThreadCount() out(count) { assert(count > 0); } body { setupWorkerThreads(); return st_threads.count!(c => c.isWorker); } /** Disables the signal handlers usually set up by vibe.d. During the first call to `runEventLoop`, vibe.d usually sets up a set of event handlers for SIGINT, SIGTERM and SIGPIPE. Since in some situations this can be undesirable, this function can be called before the first invocation of the event loop to avoid this. Calling this function after `runEventLoop` will have no effect. */ void disableDefaultSignalHandlers() { synchronized (st_threadsMutex) s_disableSignalHandlers = true; } /** Sets the effective user and group ID to the ones configured for privilege lowering. This function is useful for services run as root to give up on the privileges that they only need for initialization (such as listening on ports <= 1024 or opening system log files). Note that this function is called automatically by vibe.d's default main implementation, as well as by `runApplication`. */ void lowerPrivileges(string uname, string gname) @safe { if (!isRoot()) return; if (uname != "" || gname != "") { static bool tryParse(T)(string s, out T n) { import std.conv, std.ascii; if (!isDigit(s[0])) return false; n = parse!T(s); return s.length==0; } int uid = -1, gid = -1; if (uname != "" && !tryParse(uname, uid)) uid = getUID(uname); if (gname != "" && !tryParse(gname, gid)) gid = getGID(gname); setUID(uid, gid); } else logWarn("Vibe was run as root, and no user/group has been specified for privilege lowering. Running with full permissions."); } // ditto void lowerPrivileges() @safe { lowerPrivileges(s_privilegeLoweringUserName, s_privilegeLoweringGroupName); } /** Sets a callback that is invoked whenever a task changes its status. This function is useful mostly for implementing debuggers that analyze the life time of tasks, including task switches. Note that the callback will only be called for debug builds. */ void setTaskEventCallback(TaskEventCb func) { debug s_taskEventCallback = func; } /** A version string representing the current vibe.d version */ enum vibeVersionString = "0.8.2"; /** The maximum combined size of all parameters passed to a task delegate See_Also: runTask */ enum maxTaskParameterSize = 128; /** Represents a timer. */ struct Timer { @safe: private { EventDriver m_driver; size_t m_id; debug uint m_magicNumber = 0x4d34f916; } private this(EventDriver driver, size_t id) { m_driver = driver; m_id = id; } this(this) { debug assert(m_magicNumber == 0x4d34f916); if (m_driver) m_driver.acquireTimer(m_id); } ~this() { debug assert(m_magicNumber == 0x4d34f916); if (m_driver && driverCore) m_driver.releaseTimer(m_id); } /// True if the timer is yet to fire. @property bool pending() { return m_driver.isTimerPending(m_id); } /// The internal ID of the timer. @property size_t id() const { return m_id; } bool opCast() const { return m_driver !is null; } /** Resets the timer to the specified timeout */ void rearm(Duration dur, bool periodic = false) in { assert(dur > 0.seconds); } body { m_driver.rearmTimer(m_id, dur, periodic); } /** Resets the timer and avoids any firing. */ void stop() nothrow { m_driver.stopTimer(m_id); } /** Waits until the timer fires. */ void wait() { m_driver.waitTimer(m_id); } } /** Implements a task local storage variable. Task local variables, similar to thread local variables, exist separately in each task. Consequently, they do not need any form of synchronization when accessing them. Note, however, that each TaskLocal variable will increase the memory footprint of any task that uses task local storage. There is also an overhead to access TaskLocal variables, higher than for thread local variables, but generelly still O(1) (since actual storage acquisition is done lazily the first access can require a memory allocation with unknown computational costs). Notice: FiberLocal instances MUST be declared as static/global thread-local variables. Defining them as a temporary/stack variable will cause crashes or data corruption! Examples: --- TaskLocal!string s_myString = "world"; void taskFunc() { assert(s_myString == "world"); s_myString = "hello"; assert(s_myString == "hello"); } shared static this() { // both tasks will get independent storage for s_myString runTask(&taskFunc); runTask(&taskFunc); } --- */ struct TaskLocal(T) { private { size_t m_offset = size_t.max; size_t m_id; T m_initValue; bool m_hasInitValue = false; } this(T init_val) { m_initValue = init_val; m_hasInitValue = true; } @disable this(this); void opAssign(T value) { this.storage = value; } @property ref T storage() { auto fiber = CoreTask.getThis(); // lazily register in FLS storage if (m_offset == size_t.max) { static assert(T.alignof <= 8, "Unsupported alignment for type "~T.stringof); assert(CoreTask.ms_flsFill % 8 == 0, "Misaligned fiber local storage pool."); m_offset = CoreTask.ms_flsFill; m_id = CoreTask.ms_flsCounter++; CoreTask.ms_flsFill += T.sizeof; while (CoreTask.ms_flsFill % 8 != 0) CoreTask.ms_flsFill++; } // make sure the current fiber has enough FLS storage if (fiber.m_fls.length < CoreTask.ms_flsFill) { fiber.m_fls.length = CoreTask.ms_flsFill + 128; fiber.m_flsInit.length = CoreTask.ms_flsCounter + 64; } // return (possibly default initialized) value auto data = fiber.m_fls.ptr[m_offset .. m_offset+T.sizeof]; if (!fiber.m_flsInit[m_id]) { fiber.m_flsInit[m_id] = true; import std.traits : hasElaborateDestructor, hasAliasing; static if (hasElaborateDestructor!T || hasAliasing!T) { void function(void[], size_t) destructor = (void[] fls, size_t offset){ static if (hasElaborateDestructor!T) { auto obj = cast(T*)&fls[offset]; // call the destructor on the object if a custom one is known declared obj.destroy(); } else static if (hasAliasing!T) { // zero the memory to avoid false pointers foreach (size_t i; offset .. offset + T.sizeof) { ubyte* u = cast(ubyte*)&fls[i]; *u = 0; } } }; FLSInfo fls_info; fls_info.fct = destructor; fls_info.offset = m_offset; // make sure flsInfo has enough space if (fiber.ms_flsInfo.length <= m_id) fiber.ms_flsInfo.length = m_id + 64; fiber.ms_flsInfo[m_id] = fls_info; } if (m_hasInitValue) { static if (__traits(compiles, emplace!T(data, m_initValue))) emplace!T(data, m_initValue); else assert(false, "Cannot emplace initialization value for type "~T.stringof); } else emplace!T(data); } return (cast(T[])data)[0]; } alias storage this; } private struct FLSInfo { void function(void[], size_t) fct; size_t offset; void destroy(void[] fls) { fct(fls, offset); } } /** High level state change events for a Task */ enum TaskEvent { preStart, /// Just about to invoke the fiber which starts execution postStart, /// After the fiber has returned for the first time (by yield or exit) start, /// Just about to start execution yield, /// Temporarily paused resume, /// Resumed from a prior yield end, /// Ended normally fail /// Ended with an exception } /**************************************************************************************************/ /* private types */ /**************************************************************************************************/ private class CoreTask : TaskFiber { import std.bitmanip; private { static CoreTask ms_coreTask; CoreTask m_nextInQueue; CoreTaskQueue* m_queue; TaskFuncInfo m_taskFunc; Exception m_exception; Task[] m_yielders; // task local storage static FLSInfo[] ms_flsInfo; static size_t ms_flsFill = 0; // thread-local static size_t ms_flsCounter = 0; BitArray m_flsInit; void[] m_fls; } static CoreTask getThis() @safe nothrow { auto f = () @trusted nothrow { return Fiber.getThis(); } (); if (f) return cast(CoreTask)f; if (!ms_coreTask) ms_coreTask = new CoreTask; return ms_coreTask; } this() @trusted nothrow { super(&run, s_taskStackSize); } // expose Fiber.state as @safe on older DMD versions static if (!__traits(compiles, () @safe { return Fiber.init.state; } ())) @property State state() @trusted const nothrow { return super.state; } @property size_t taskCounter() const { return m_taskCounter; } private void run() { version (VibeDebugCatchAll) alias UncaughtException = Throwable; else alias UncaughtException = Exception; try { while(true){ while (!m_taskFunc.func) { try { Fiber.yield(); } catch( Exception e ){ logWarn("CoreTaskFiber was resumed with exception but without active task!"); logDiagnostic("Full error: %s", e.toString().sanitize()); } } auto task = m_taskFunc; m_taskFunc = TaskFuncInfo.init; Task handle = this.task; try { m_running = true; scope(exit) m_running = false; static import std.concurrency; std.concurrency.thisTid; // force creation of a new Tid debug if (s_taskEventCallback) s_taskEventCallback(TaskEvent.start, handle); if (!s_eventLoopRunning) { logTrace("Event loop not running at task start - yielding."); .yield(); logTrace("Initial resume of task."); } task.func(&task); debug if (s_taskEventCallback) s_taskEventCallback(TaskEvent.end, handle); } catch( Exception e ){ debug if (s_taskEventCallback) s_taskEventCallback(TaskEvent.fail, handle); import std.encoding; logCritical("Task terminated with uncaught exception: %s", e.msg); logDebug("Full error: %s", e.toString().sanitize()); } this.tidInfo.ident = Tid.init; // reset Tid // check for any unhandled deferred exceptions if (m_exception !is null) { if (cast(InterruptException)m_exception) { logDebug("InterruptException not handled by task before exit."); } else { logCritical("Deferred exception not handled by task before exit: %s", m_exception.msg); logDebug("Full error: %s", m_exception.toString().sanitize()); } } foreach (t; m_yielders) s_yieldedTasks.insertBack(cast(CoreTask)t.fiber); m_yielders.length = 0; // make sure that the task does not get left behind in the yielder queue if terminated during yield() if (m_queue) { s_core.resumeYieldedTasks(); assert(m_queue is null, "Still in yielder queue at the end of task after resuming all yielders!?"); } // zero the fls initialization ByteArray for memory safety foreach (size_t i, ref bool b; m_flsInit) { if (b) { if (ms_flsInfo !is null && ms_flsInfo.length >= i && ms_flsInfo[i] != FLSInfo.init) ms_flsInfo[i].destroy(m_fls); b = false; } } // make the fiber available for the next task if (s_availableFibers.full) s_availableFibers.capacity = 2 * s_availableFibers.capacity; // clear the message queue for the next task messageQueue.clear(); s_availableFibers.put(this); } } catch (UncaughtException th) { logCritical("CoreTaskFiber was terminated unexpectedly: %s", th.msg); logDiagnostic("Full error: %s", th.toString().sanitize()); s_fiberCount--; } } override void join() { auto caller = Task.getThis(); if (!m_running) return; if (caller != Task.init) { assert(caller.fiber !is this, "A task cannot join itself."); assert(caller.thread is this.thread, "Joining tasks in foreign threads is currently not supported."); m_yielders ~= caller; } else assert(() @trusted { return Thread.getThis(); } () is this.thread, "Joining tasks in different threads is not yet supported."); auto run_count = m_taskCounter; if (caller == Task.init) () @trusted { return s_core; } ().resumeYieldedTasks(); // let the task continue (it must be yielded currently) while (m_running && run_count == m_taskCounter) rawYield(); } override void interrupt() { auto caller = Task.getThis(); if (caller != Task.init) { assert(caller != this.task, "A task cannot interrupt itself."); assert(caller.thread is this.thread, "Interrupting tasks in different threads is not yet supported."); } else assert(Thread.getThis() is this.thread, "Interrupting tasks in different threads is not yet supported."); s_core.yieldAndResumeTask(this.task, new InterruptException); } override void terminate() { assert(false, "Not implemented"); } } private class VibeDriverCore : DriverCore { @safe: private { Duration m_gcCollectTimeout; Timer m_gcTimer; bool m_ignoreIdleForGC = false; Exception m_eventException; } private void setupGcTimer() { m_gcTimer = createTimer(&collectGarbage); m_gcCollectTimeout = dur!"seconds"(2); } @property void eventException(Exception e) { m_eventException = e; } void yieldForEventDeferThrow() @safe nothrow { yieldForEventDeferThrow(Task.getThis()); } void processDeferredExceptions() @safe { processDeferredExceptions(Task.getThis()); } void yieldForEvent() @safe { auto task = Task.getThis(); processDeferredExceptions(task); yieldForEventDeferThrow(task); processDeferredExceptions(task); } void resumeTask(Task task, Exception event_exception = null) @safe nothrow { assert(Task.getThis() == Task.init, "Calling resumeTask from another task."); resumeTask(task, event_exception, false); } void yieldAndResumeTask(Task task, Exception event_exception = null) @safe { auto thisct = CoreTask.getThis(); if (thisct is null || thisct is CoreTask.ms_coreTask) { resumeTask(task, event_exception); return; } auto otherct = cast(CoreTask)task.fiber; assert(!thisct || otherct.thread is thisct.thread, "Resuming task in foreign thread."); assert(() @trusted { return otherct.state; } () == Fiber.State.HOLD, "Resuming fiber that is not on HOLD."); if (event_exception) otherct.m_exception = event_exception; if (!otherct.m_queue) s_yieldedTasks.insertBack(otherct); yield(); } void resumeTask(Task task, Exception event_exception, bool initial_resume) @safe nothrow { assert(initial_resume || task.running, "Resuming terminated task."); resumeCoreTask(cast(CoreTask)task.fiber, event_exception); } void resumeCoreTask(CoreTask ctask, Exception event_exception = null) nothrow @safe { assert(ctask.thread is () @trusted { return Thread.getThis(); } (), "Resuming task in foreign thread."); assert(() @trusted nothrow { return ctask.state; } () == Fiber.State.HOLD, "Resuming fiber that is not on HOLD"); if (event_exception) { extrap(); assert(!ctask.m_exception, "Resuming task with exception that is already scheduled to be resumed with exception."); ctask.m_exception = event_exception; } // do nothing if the task is aready scheduled to be resumed if (ctask.m_queue) return; try () @trusted { ctask.call!(Fiber.Rethrow.yes)(); } (); catch (Exception e) { extrap(); assert(() @trusted nothrow { return ctask.state; } () == Fiber.State.TERM); logError("Task terminated with unhandled exception: %s", e.msg); logDebug("Full error: %s", () @trusted { return e.toString().sanitize; } ()); } } void notifyIdle() { bool again = !getExitFlag(); while (again) { if (s_idleHandler) again = s_idleHandler(); else again = false; resumeYieldedTasks(); again = (again || !s_yieldedTasks.empty) && !getExitFlag(); if (again && !getEventDriver().processEvents()) { logDebug("Setting exit flag due to driver signalling exit"); s_exitEventLoop = true; return; } } if (!s_yieldedTasks.empty) logDebug("Exiting from idle processing although there are still yielded tasks (exit=%s)", getExitFlag()); if (() @trusted { return Thread.getThis() is st_mainThread; } ()) { if (!m_ignoreIdleForGC && m_gcTimer) { m_gcTimer.rearm(m_gcCollectTimeout); } else m_ignoreIdleForGC = false; } } bool isScheduledForResume(Task t) { if (t == Task.init) return false; if (!t.running) return false; auto cf = cast(CoreTask)t.fiber; return cf.m_queue !is null; } private void resumeYieldedTasks() nothrow @safe { for (auto limit = s_yieldedTasks.length; limit > 0 && !s_yieldedTasks.empty; limit--) { auto tf = s_yieldedTasks.front; s_yieldedTasks.popFront(); if (tf.state == Fiber.State.HOLD) resumeCoreTask(tf); } } private void yieldForEventDeferThrow(Task task) @safe nothrow { if (task != Task.init) { debug if (s_taskEventCallback) () @trusted { s_taskEventCallback(TaskEvent.yield, task); } (); () @trusted { task.fiber.yield(); } (); debug if (s_taskEventCallback) () @trusted { s_taskEventCallback(TaskEvent.resume, task); } (); // leave fiber.m_exception untouched, so that it gets thrown on the next yieldForEvent call } else { assert(!s_eventLoopRunning, "Event processing outside of a fiber should only happen before the event loop is running!?"); m_eventException = null; () @trusted nothrow { resumeYieldedTasks(); } (); // let tasks that yielded because they were started outside of an event loop try if (auto err = () @trusted { return getEventDriver().runEventLoopOnce(); } ()) { logError("Error running event loop: %d", err); assert(err != 1, "No events registered, exiting event loop."); assert(false, "Error waiting for events."); } catch (Exception e) { assert(false, "Driver.runEventLoopOnce() threw: "~e.msg); } // leave m_eventException untouched, so that it gets thrown on the next yieldForEvent call } } private void processDeferredExceptions(Task task) @safe { if (task != Task.init) { auto fiber = cast(CoreTask)task.fiber; if (auto e = fiber.m_exception) { fiber.m_exception = null; throw e; } } else { if (auto e = m_eventException) { m_eventException = null; throw e; } } } private void collectGarbage() { import core.memory; logTrace("gc idle collect"); () @trusted { GC.collect(); GC.minimize(); } (); m_ignoreIdleForGC = true; } } private struct ThreadContext { Thread thread; bool isWorker; TaskFuncInfo[] taskQueue; this(Thread thr, bool worker) { this.thread = thr; this.isWorker = worker; } } private struct TaskFuncInfo { void function(TaskFuncInfo*) func; void[2*size_t.sizeof] callable; void[maxTaskParameterSize] args; @property ref C typedCallable(C)() @trusted { static assert(C.sizeof <= callable.sizeof); return *cast(C*)callable.ptr; } @property ref A typedArgs(A)() @trusted { static assert(A.sizeof <= args.sizeof); return *cast(A*)args.ptr; } void initCallable(C)() @trusted { C cinit; this.callable[0 .. C.sizeof] = cast(void[])(&cinit)[0 .. 1]; } void initArgs(A)() @trusted { A ainit; this.args[0 .. A.sizeof] = cast(void[])(&ainit)[0 .. 1]; } } alias TaskArgsVariant = VariantN!maxTaskParameterSize; /**************************************************************************************************/ /* private functions */ /**************************************************************************************************/ private { static if ((void*).sizeof >= 8) enum defaultTaskStackSize = 16*1024*1024; else enum defaultTaskStackSize = 512*1024; __gshared VibeDriverCore s_core; __gshared size_t s_taskStackSize = defaultTaskStackSize; __gshared core.sync.mutex.Mutex st_threadsMutex; __gshared ManualEvent st_threadsSignal; __gshared Thread st_mainThread; __gshared ThreadContext[] st_threads; __gshared TaskFuncInfo[] st_workerTasks; __gshared Condition st_threadShutdownCondition; __gshared debug TaskEventCb s_taskEventCallback; shared bool st_term = false; bool s_exitEventLoop = false; bool s_eventLoopRunning = false; bool delegate() @safe s_idleHandler; CoreTaskQueue s_yieldedTasks; Variant[string] s_taskLocalStorageGlobal; // for use outside of a task FixedRingBuffer!CoreTask s_availableFibers; size_t s_fiberCount; string s_privilegeLoweringUserName; string s_privilegeLoweringGroupName; __gshared bool s_disableSignalHandlers = false; } private static @property VibeDriverCore driverCore() @trusted nothrow { return s_core; } private bool getExitFlag() @trusted nothrow { return s_exitEventLoop || atomicLoad(st_term); } private void setupSignalHandlers() { __gshared bool s_setup = false; // only initialize in main thread synchronized (st_threadsMutex) { if (s_setup) return; s_setup = true; if (s_disableSignalHandlers) return; logTrace("setup signal handler"); version(Posix){ // support proper shutdown using signals sigset_t sigset; sigemptyset(&sigset); sigaction_t siginfo; siginfo.sa_handler = &onSignal; siginfo.sa_mask = sigset; siginfo.sa_flags = SA_RESTART; sigaction(SIGINT, &siginfo, null); sigaction(SIGTERM, &siginfo, null); siginfo.sa_handler = &onBrokenPipe; sigaction(SIGPIPE, &siginfo, null); } version(Windows){ // WORKAROUND: we don't care about viral @nogc attribute here! import std.traits; signal(SIGABRT, cast(ParameterTypeTuple!signal[1])&onSignal); signal(SIGTERM, cast(ParameterTypeTuple!signal[1])&onSignal); signal(SIGINT, cast(ParameterTypeTuple!signal[1])&onSignal); } } } // per process setup shared static this() { st_mainThread = Thread.getThis(); version(Windows){ version(VibeLibeventDriver) enum need_wsa = true; else version(VibeWin32Driver) enum need_wsa = true; else enum need_wsa = false; static if (need_wsa) { logTrace("init winsock"); // initialize WinSock2 import core.sys.windows.winsock2; WSADATA data; WSAStartup(0x0202, &data); } } // COMPILER BUG: Must be some kind of module constructor order issue: // without this, the stdout/stderr handles are not initialized before // the log module is set up. import std.stdio; File f; f.close(); initializeLogModule(); logTrace("create driver core"); s_core = new VibeDriverCore; st_threadsMutex = new Mutex; st_threadShutdownCondition = new Condition(st_threadsMutex); auto thisthr = Thread.getThis(); thisthr.name = "Main"; assert(st_threads.length == 0, "Main thread not the first thread!?"); st_threads ~= ThreadContext(thisthr, false); setupDriver(); st_threadsSignal = getEventDriver().createManualEvent(); version(VibeIdleCollect){ logTrace("setup gc"); driverCore.setupGcTimer(); } version (VibeNoDefaultArgs) {} else { readOption("uid|user", &s_privilegeLoweringUserName, "Sets the user name or id used for privilege lowering."); readOption("gid|group", &s_privilegeLoweringGroupName, "Sets the group name or id used for privilege lowering."); } // set up vibe.d compatibility for std.concurrency static import std.concurrency; std.concurrency.scheduler = new VibedScheduler; } shared static ~this() { deleteEventDriver(); size_t tasks_left; synchronized (st_threadsMutex) { if( !st_workerTasks.empty ) tasks_left = st_workerTasks.length; } if (!s_yieldedTasks.empty) tasks_left += s_yieldedTasks.length; if (tasks_left > 0) { logWarn("There were still %d tasks running at exit.", tasks_left); } destroy(s_core); s_core = null; } // per thread setup static this() { /// workaround for: // object.Exception@src/rt/minfo.d(162): Aborting: Cycle detected between modules with ctors/dtors: // vibe.core.core -> vibe.core.drivers.native -> vibe.core.drivers.libasync -> vibe.core.core if (Thread.getThis().isDaemon && Thread.getThis().name == "CmdProcessor") return; assert(s_core !is null); auto thisthr = Thread.getThis(); synchronized (st_threadsMutex) if (!st_threads.any!(c => c.thread is thisthr)) st_threads ~= ThreadContext(thisthr, false); //CoreTask.ms_coreTask = new CoreTask; setupDriver(); } static ~this() { // Issue #1374: Sometimes Druntime for some reason calls `static ~this` after `shared static ~this` if (!s_core) return; version(VibeLibasyncDriver) { import vibe.core.drivers.libasync; if (LibasyncDriver.isControlThread) return; } auto thisthr = Thread.getThis(); bool is_main_thread = false; synchronized (st_threadsMutex) { auto idx = st_threads.countUntil!(c => c.thread is thisthr); // if we are the main thread, wait for all others before terminating is_main_thread = idx == 0; if (is_main_thread) { // we are the main thread, wait for others atomicStore(st_term, true); st_threadsSignal.emit(); // wait for all non-daemon threads to shut down while (st_threads[1 .. $].any!(th => !th.thread.isDaemon)) { logDiagnostic("Main thread still waiting for other threads: %s", st_threads[1 .. $].map!(t => t.thread.name ~ (t.isWorker ? " (worker thread)" : "")).join(", ")); st_threadShutdownCondition.wait(); } logDiagnostic("Main thread exiting"); } assert(idx >= 0, "No more threads registered"); if (idx >= 0) { st_threads[idx] = st_threads[$-1]; st_threads.length--; } } // delay deletion of the main event driver to "~shared static this()" if (!is_main_thread) deleteEventDriver(); st_threadShutdownCondition.notifyAll(); } package void setupDriver() { if (getEventDriver(true) !is null) return; logTrace("create driver"); setupEventDriver(driverCore); logTrace("driver %s created", (cast(Object)getEventDriver()).classinfo.name); } private void workerThreadFunc() nothrow { try { assert(s_core !is null); if (getExitFlag()) return; logDebug("entering worker thread"); runTask(toDelegate(&handleWorkerTasks)); logDebug("running event loop"); if (!getExitFlag()) runEventLoop(); logDebug("Worker thread exit."); } catch (Exception e) { scope (failure) abort(); logFatal("Worker thread terminated due to uncaught exception: %s", e.msg); logDebug("Full error: %s", e.toString().sanitize()); } catch (Throwable th) { scope (exit) abort(); logFatal("Worker thread terminated due to uncaught error: %s (%s)", th.msg); logFatal("Error type: %s", th.classinfo.name); logDebug("Full error: %s", th.toString().sanitize()); } } private void handleWorkerTasks() { logDebug("worker thread enter"); auto thisthr = Thread.getThis(); logDebug("worker thread loop enter"); while(true){ auto emit_count = st_threadsSignal.emitCount; TaskFuncInfo task; synchronized (st_threadsMutex) { auto idx = st_threads.countUntil!(c => c.thread is thisthr); assert(idx >= 0); logDebug("worker thread check"); if (getExitFlag()) { if (st_threads[idx].taskQueue.length > 0) logWarn("Worker thread shuts down with specific worker tasks left in its queue."); if (st_threads.count!(c => c.isWorker) == 1 && st_workerTasks.length > 0) logWarn("Worker threads shut down with worker tasks still left in the queue."); break; } if (!st_workerTasks.empty) { logDebug("worker thread got task"); task = st_workerTasks.front; st_workerTasks.popFront(); } else if (!st_threads[idx].taskQueue.empty) { logDebug("worker thread got specific task"); task = st_threads[idx].taskQueue.front; st_threads[idx].taskQueue.popFront(); } } if (task.func !is null) runTask_internal(task); else emit_count = st_threadsSignal.wait(emit_count); } logDebug("worker thread exit"); getEventDriver().exitEventLoop(); } private void watchExitFlag() { auto emit_count = st_threadsSignal.emitCount; while (true) { synchronized (st_threadsMutex) { if (getExitFlag()) break; } emit_count = st_threadsSignal.wait(emit_count); } logDebug("main thread exit"); getEventDriver().exitEventLoop(); } private extern(C) void extrap() @safe nothrow { logTrace("exception trap"); } private extern(C) void onSignal(int signal) nothrow { atomicStore(st_term, true); try st_threadsSignal.emit(); catch (Throwable) {} logInfo("Received signal %d. Shutting down.", signal); } private extern(C) void onBrokenPipe(int signal) nothrow { logTrace("Broken pipe."); } version(Posix) { private bool isRoot() @safe { return geteuid() == 0; } private void setUID(int uid, int gid) @safe { logInfo("Lowering privileges to uid=%d, gid=%d...", uid, gid); if (gid >= 0) { enforce(() @trusted { return getgrgid(gid); }() !is null, "Invalid group id!"); enforce(setegid(gid) == 0, "Error setting group id!"); } //if( initgroups(const char *user, gid_t group); if (uid >= 0) { enforce(() @trusted { return getpwuid(uid); }() !is null, "Invalid user id!"); enforce(seteuid(uid) == 0, "Error setting user id!"); } } private int getUID(string name) @safe { auto pw = () @trusted { return getpwnam(name.toStringz()); }(); enforce(pw !is null, "Unknown user name: "~name); return pw.pw_uid; } private int getGID(string name) @safe { auto gr = () @trusted { return getgrnam(name.toStringz()); }(); enforce(gr !is null, "Unknown group name: "~name); return gr.gr_gid; } } else version(Windows){ private bool isRoot() @safe { return false; } private void setUID(int uid, int gid) @safe { enforce(false, "UID/GID not supported on Windows."); } private int getUID(string name) @safe { enforce(false, "Privilege lowering not supported on Windows."); assert(false); } private int getGID(string name) @safe { enforce(false, "Privilege lowering not supported on Windows."); assert(false); } } private struct CoreTaskQueue { @safe nothrow: CoreTask first, last; size_t length; @disable this(this); @property bool empty() const { return first is null; } @property CoreTask front() { return first; } void insertBack(CoreTask task) { assert(task.m_queue == null, "Task is already scheduled to be resumed!"); assert(task.m_nextInQueue is null, "Task has m_nextInQueue set without being in a queue!?"); task.m_queue = &this; if (empty) first = task; else last.m_nextInQueue = task; last = task; length++; } void popFront() { if (first is last) last = null; assert(first && first.m_queue == &this); auto next = first.m_nextInQueue; first.m_nextInQueue = null; first.m_queue = null; first = next; length--; } } // mixin string helper to call a function with arguments that potentially have // to be moved private string callWithMove(ARGS...)(string func, string args) { import std.string; string ret = func ~ "("; foreach (i, T; ARGS) { if (i > 0) ret ~= ", "; ret ~= format("%s[%s]", args, i); static if (needsMove!T) ret ~= ".move"; } return ret ~ ");"; } private template needsMove(T) { template isCopyable(T) { enum isCopyable = __traits(compiles, (T a) { return a; }); } template isMoveable(T) { enum isMoveable = __traits(compiles, (T a) { return a.move; }); } enum needsMove = !isCopyable!T; static assert(isCopyable!T || isMoveable!T, "Non-copyable type "~T.stringof~" must be movable with a .move property."); } unittest { enum E { a, move } static struct S { @disable this(this); @property S move() { return S.init; } } static struct T { @property T move() { return T.init; } } static struct U { } static struct V { @disable this(); @disable this(this); @property V move() { return V.init; } } static struct W { @disable this(); } static assert(needsMove!S); static assert(!needsMove!int); static assert(!needsMove!string); static assert(!needsMove!E); static assert(!needsMove!T); static assert(!needsMove!U); static assert(needsMove!V); static assert(!needsMove!W); } // DMD currently has no option to set merging of coverage files at compile-time // This needs to be done via a Druntime API // As this option is solely for Vibed's internal testsuite, it's hidden behind // a long version version(VibedSetCoverageMerge) shared static this() { import core.runtime : dmd_coverSetMerge; dmd_coverSetMerge(true); }