vibe.core.core 42/318(13%) 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
12741
12750
12760
12770
12780
12793
12800
12811
12820
12831
12840
12851
12861
12870
12881
12891
12901
12911
12920
12931
12940
12950
12960
12970
12980
12990
13000
13010
13021
13031
13040
13050
13060
13071
13080
13090
13101
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
132913
13300
133112
133236
133325
133411
13350
13360
13370
133812
13390
13400
13410
13420
134312
13440
134512
13460
134736
134835
134948
13500
13510
135212
13531
13541
13550
13560
135736
135835
135912
136012
136112
136212
13630
13640
13650
13660
136723
13680
136912
13700
13710
13720
13730
13741
13750
13764
13770
13780
13791
13800
13810
13820
13830
13840
13850
13860
138711
13880
13890
13900
13910
139211
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
/** This module contains the core functionality of the vibe.d framework. Copyright: © 2012-2017 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.task; import eventcore.core; import vibe.core.args; import vibe.core.concurrency; import vibe.core.log; import vibe.core.sync : ManualEvent, createSharedManualEvent; import vibe.core.taskpool : TaskPool; import vibe.internal.async; import vibe.internal.array : FixedRingBuffer; //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.traits : isFunctionPointer; import std.typecons : Flag, Yes, Typedef, Tuple, tuple; import std.variant; import core.atomic; import core.sync.condition; import core.sync.mutex; import core.stdc.stdlib; import core.thread; 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(string[]* args_out = null) @safe { try if (!() @trusted { return finalizeCommandLineOptions(); } () ) return 0; 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) { try conn.write(conn); catch (Exception e) { /* log error */ } }); // 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) { try conn.write(conn); catch (Exception e) { /* log error */ } }); // 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() @safe nothrow { setupSignalHandlers(); logDebug("Starting event loop."); s_eventLoopRunning = true; scope (exit) { s_eventLoopRunning = false; s_exitEventLoop = false; () @trusted nothrow { scope (failure) assert(false); // notifyAll is not marked nothrow st_threadShutdownCondition.notifyAll(); } (); } // runs any yield()ed tasks first assert(!s_exitEventLoop, "Exit flag set before event loop has started."); s_exitEventLoop = false; performIdleProcessing(); if (getExitFlag()) return 0; Task exit_task; // handle exit flag in the main thread to exit when // exitEventLoop(true) is called from a thread) () @trusted nothrow { if (s_isMainThread) exit_task = runTask(toDelegate(&watchExitFlag)); } (); while (true) { auto er = s_scheduler.waitAndProcess(); if (er != ExitReason.idle || s_exitEventLoop) { logDebug("Event loop exit reason (exit flag=%s): %s", s_exitEventLoop, er); break; } performIdleProcessing(); } // make sure the exit flag watch task finishes together with this loop // TODO: would be niced to do this without exceptions if (exit_task && exit_task.running) exit_task.interrupt(); logDebug("Event loop done (scheduled tasks=%s, waiters=%s, thread exit=%s).", s_scheduler.scheduledTaskCount, eventDriver.core.waiterCount, s_exitEventLoop); eventDriver.core.clearExitFlag(); s_exitEventLoop = false; 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) @safe nothrow { logDebug("exitEventLoop called (%s)", shutdown_all_threads); assert(s_eventLoopRunning || shutdown_all_threads, "Exiting event loop when none is running."); if (shutdown_all_threads) { () @trusted nothrow { shutdownWorkerPool(); atomicStore(st_term, true); st_threadsSignal.emit(); } (); } // shutdown the calling thread s_exitEventLoop = true; if (s_eventLoopRunning) eventDriver.core.exit(); } /** 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() @safe nothrow { return !s_scheduler.process().among(ExitReason.exited, ExitReason.outOfWaiters); } /** Wait once for events and process them. */ ExitReason runEventLoopOnce() @safe nothrow { auto ret = s_scheduler.waitAndProcess(); if (ret == ExitReason.idle) performIdleProcessing(); return ret; } /** 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 nothrow del) @safe nothrow { s_idleHandler = () @safe nothrow { del(); return false; }; } /// ditto void setIdleHandler(bool delegate() @safe nothrow del) @safe nothrow { s_idleHandler = 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, auto ref ARGS args) { return runTask_internal!((ref tfi) { tfi.set(task, args); }); } /// Task runTask(ARGS...)(void delegate(ARGS) @system task, auto ref ARGS args) @system { return runTask_internal!((ref tfi) { tfi.set(task, args); }); } /// ditto Task runTask(CALLABLE, ARGS...)(CALLABLE task, auto ref ARGS args) if (!is(CALLABLE : void delegate(ARGS)) && is(typeof(CALLABLE.init(ARGS.init)))) { return runTask_internal!((ref tfi) { tfi.set(task, args); }); } /** Runs an asyncronous task that is guaranteed to finish before the caller's scope is left. */ auto runTaskScoped(FT, ARGS)(scope FT callable, ARGS args) { static struct S { Task handle; @disable this(this); ~this() { handle.joinUninterruptible(); } } return S(runTask(callable, args)); } package Task runTask_internal(alias TFI_SETUP)() { import std.typecons : Tuple, tuple; TaskFiber 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..."); f = new TaskFiber; } TFI_SETUP(f.m_taskFunc); f.bumpTaskCounter(); auto handle = f.task(); debug if (TaskFiber.ms_taskCreationCallback) { TaskCreationInfo info; info.handle = handle; info.functionPointer = () @trusted { return cast(void*)f.m_taskFunc.functionPointer; } (); () @trusted { TaskFiber.ms_taskCreationCallback(info); } (); } debug if (TaskFiber.ms_taskEventCallback) { () @trusted { TaskFiber.ms_taskEventCallback(TaskEvent.preStart, handle); } (); } s_scheduler.switchTo(handle, TaskFiber.getThis().m_yieldLockCount > 0 ? Flag!"defer".yes : Flag!"defer".no); debug if (TaskFiber.ms_taskEventCallback) { () @trusted { TaskFiber.ms_taskEventCallback(TaskEvent.postStart, handle); } (); } return handle; } /** 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 (isFunctionPointer!FT) { setupWorkerThreads(); st_workerPool.runTask(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))))) { setupWorkerThreads(); st_workerPool.runTask!method(object, 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 (isFunctionPointer!FT) { setupWorkerThreads(); return st_workerPool.runTaskH(func, args); } /// ditto Task runWorkerTaskH(alias method, T, ARGS...)(shared(T) object, auto ref ARGS args) if (is(typeof(__traits(getMember, object, __traits(identifier, method))))) { setupWorkerThreads(); return st_workerPool.runTaskH!method(object, args); } /// 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 (receiveOnly!string() == "ping" && --counter) { logInfo("pong"); caller.send("pong"); } caller.send("goodbye"); } static void test() { Task callee = runWorkerTaskH(&workerFunc, Task.getThis); do { logInfo("ping"); callee.send("ping"); } while (receiveOnly!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 (receiveOnly!string() == "ping" && --counter) { logInfo("pong"); caller.send("pong"); } caller.send("goodbye"); } } static void test() { auto cls = new shared Test; Task callee = runWorkerTaskH!(Test.workerMethod)(cls, Task.getThis()); do { logInfo("ping"); callee.send("ping"); } while (receiveOnly!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 local task from outside of a task int i = 0; auto t = runTask({ sleep(1.msecs); i = 1; }); t.join(); assert(i == 1); } unittest { // run and join worker task from outside of a task __gshared int i = 0; auto t = runWorkerTaskH({ sleep(5.msecs); i = 1; }); t.join(); assert(i == 1); } /** 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)) { setupWorkerThreads(); return st_workerPool.runTaskDist(func, args); } /// ditto void runWorkerTaskDist(alias method, T, ARGS...)(shared(T) object, ARGS args) { setupWorkerThreads(); return st_workerPool.runTaskDist!method(object, args); } /** Sets up num worker threads. This function gives explicit control over the number of worker threads. Note, to have an effect the function must be called prior to related worker tasks functions which set up the default number of worker threads implicitly. Params: num = The number of worker threads to initialize. Defaults to `logicalProcessorCount`. See_also: `runWorkerTask`, `runWorkerTaskH`, `runWorkerTaskDist` */ public void setupWorkerThreads(uint num = logicalProcessorCount()) { static bool s_workerThreadsStarted = false; if (s_workerThreadsStarted) return; s_workerThreadsStarted = true; synchronized (st_threadsMutex) { if (!st_workerPool) st_workerPool = new shared TaskPool(num); } } /** Determines the number of logical processors in the system. This number includes virtual cores on hyper-threading enabled CPUs. */ public @property uint logicalProcessorCount() { import std.parallelism : totalCPUs; return totalCPUs; } /** 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 { auto t = Task.getThis(); if (t != Task.init) { auto tf = () @trusted { return t.taskFiber; } (); tf.handleInterrupt(); s_scheduler.yield(); tf.handleInterrupt(); } else { // Let yielded tasks execute assert(TaskFiber.getThis().m_yieldLockCount == 0, "May not yield within an active yieldLock()!"); () @safe nothrow { performIdleProcessing(); } (); } } /** Suspends the execution of the calling task until `switchToTask` is called manually. This low-level scheduling function is usually only used internally. Failure to call `switchToTask` will result in task starvation and resource leakage. Params: on_interrupt = If specified, is required to See_Also: `switchToTask` */ void hibernate(scope void delegate() @safe nothrow on_interrupt = null) @safe nothrow { auto t = Task.getThis(); if (t == Task.init) { assert(TaskFiber.getThis().m_yieldLockCount == 0, "May not yield within an active yieldLock!"); runEventLoopOnce(); } else { auto tf = () @trusted { return t.taskFiber; } (); tf.handleInterrupt(on_interrupt); s_scheduler.hibernate(); tf.handleInterrupt(on_interrupt); } } /** Switches execution to the given task. This function can be used in conjunction with `hibernate` to wake up a task. The task must live in the same thread as the caller. See_Also: `hibernate` */ void switchToTask(Task t) @safe nothrow { s_scheduler.switchTo(t); } /** 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. Throws: May throw an `InterruptException` if the task gets interrupted using `Task.interrupt()`. */ 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. 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() nothrow @safe callback, bool periodic = false) @safe nothrow { auto tm = createTimer(callback); tm.rearm(timeout, periodic); return tm; } /// unittest { void printTime() @safe nothrow { 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, toDelegate(&printTime), true); } } /// Compatibility overload - use a `@safe nothrow` callback instead. Timer setTimer(Duration timeout, void delegate() callback, bool periodic = false) @system nothrow { return setTimer(timeout, () @trusted nothrow { try callback(); catch (Exception e) { logWarn("Timer callback failed: %s", e.msg); scope (failure) assert(false); logDebug("Full error: %s", e.toString().sanitize); } }, periodic); } /** Creates a new timer without arming it. See_also: setTimer */ Timer createTimer(void delegate() nothrow @safe callback) @safe nothrow { auto ret = Timer(eventDriver.timers.create()); if (callback !is null) { runTask((void delegate() nothrow @safe cb, Timer tm) { while (!tm.unique || tm.pending) { tm.wait(); cb(); } }, callback, ret); } return ret; } /** 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 Returns: Returns a newly created FileDescriptorEvent associated with the given file descriptor. */ FileDescriptorEvent createFileDescriptorEvent(int file_descriptor, FileDescriptorEvent.Trigger event_mask) @safe nothrow { return FileDescriptorEvent(file_descriptor, event_mask); } /** 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) nothrow { TaskFiber.ms_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, "No worker threads started after setupWorkerThreads!?"); } body { setupWorkerThreads(); synchronized (st_threadsMutex) return st_workerPool.threadCount; } /** 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). */ 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(TaskEventCallback func) { debug TaskFiber.ms_taskEventCallback = func; } /** Sets a callback that is invoked whenever new task is created. The callback is guaranteed to be invoked before the one set by `setTaskEventCallback` for the same task handle. 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 setTaskCreationCallback(TaskCreationCallback func) { debug TaskFiber.ms_taskCreationCallback = func; } /** A version string representing the current vibe.d core version */ enum vibeVersionString = "1.4.0"; /** Generic file descriptor event. This kind of event can be used to wait for events on a non-blocking file descriptor. Note that this can usually only be used on socket based file descriptors. */ struct FileDescriptorEvent { /** Event mask selecting the kind of events to listen for. */ enum Trigger { none = 0, /// Match no event (invalid value) read = 1<<0, /// React on read-ready events write = 1<<1, /// React on write-ready events any = read|write /// Match any kind of event } private { StreamSocketFD m_socket; Trigger m_trigger; } @safe: private this(int fd, Trigger event_mask) nothrow { m_socket = eventDriver.sockets.adoptStream(fd); m_trigger = event_mask; } this(this) nothrow { if (m_socket != StreamSocketFD.invalid) eventDriver.sockets.addRef(m_socket); } ~this() nothrow { if (m_socket != StreamSocketFD.invalid) eventDriver.sockets.releaseRef(m_socket); } /** Waits for the selected event to occur. Params: which = Optional event mask to react only on certain events timeout = Maximum time to wait for an event Returns: The overload taking the timeout parameter returns true if an event was received on time and false otherwise. */ void wait(Trigger which = Trigger.any) { wait(Duration.max, which); } /// ditto bool wait(Duration timeout, Trigger which = Trigger.any) { if ((which & m_trigger) == Trigger.none) return true; assert((which & m_trigger) == Trigger.read, "Waiting for write event not yet supported."); bool got_data; alias readwaiter = Waitable!(IOCallback, cb => eventDriver.sockets.waitForData(m_socket, cb), cb => eventDriver.sockets.cancelRead(m_socket), (fd, st, nb) { got_data = st == IOStatus.ok; } ); asyncAwaitAny!(true, readwaiter)(timeout); return got_data; } } /** Represents a timer. */ struct Timer { private { typeof(eventDriver.timers) m_driver; TimerID m_id; debug uint m_magicNumber = 0x4d34f916; } @safe: private this(TimerID id) nothrow { assert(id != TimerID.init, "Invalid timer ID."); m_driver = eventDriver.timers; m_id = id; } this(this) nothrow { debug assert(m_magicNumber == 0x4d34f916, "Timer corrupted."); if (m_driver) m_driver.addRef(m_id); } ~this() nothrow { debug assert(m_magicNumber == 0x4d34f916, "Timer corrupted."); if (m_driver) m_driver.releaseRef(m_id); } /// True if the timer is yet to fire. @property bool pending() nothrow { return m_driver.isPending(m_id); } /// The internal ID of the timer. @property size_t id() const nothrow { return m_id; } bool opCast() const nothrow { return m_driver !is null; } /// Determines if this reference is the only one @property bool unique() const nothrow { return m_driver ? m_driver.isUnique(m_id) : false; } /** Resets the timer to the specified timeout */ void rearm(Duration dur, bool periodic = false) nothrow in { assert(dur > 0.seconds, "Negative timer duration specified."); } body { m_driver.set(m_id, dur, periodic ? dur : 0.seconds); } /** Resets the timer and avoids any firing. */ void stop() nothrow { if (m_driver) m_driver.stop(m_id); } /** Waits until the timer fires. */ void wait() { asyncAwait!(TimerCallback, cb => m_driver.wait(m_id, cb), cb => m_driver.cancelWait(m_id) ); } } /** Returns an object that ensures that no task switches happen during its life time. Any attempt to run the event loop or switching to another task will cause an assertion to be thrown within the scope that defines the lifetime of the returned object. Multiple yield locks can appear in nested scopes. */ auto yieldLock() { static struct YieldLock { private this(bool) { inc(); } @disable this(); @disable this(this); ~this() { dec(); } private void inc() { TaskFiber.getThis().m_yieldLockCount++; } private void dec() { TaskFiber.getThis().m_yieldLockCount--; } } return YieldLock(true); } unittest { auto tf = TaskFiber.getThis(); assert(tf.m_yieldLockCount == 0); { auto lock = yieldLock(); assert(tf.m_yieldLockCount == 1); { auto lock2 = yieldLock(); assert(tf.m_yieldLockCount == 2); } assert(tf.m_yieldLockCount == 1); } assert(tf.m_yieldLockCount == 0); } /**************************************************************************************************/ /* private types */ /**************************************************************************************************/ private void setupGcTimer() { s_gcTimer = createTimer(() @trusted { import core.memory; logTrace("gc idle collect"); GC.collect(); GC.minimize(); s_ignoreIdleForGC = true; }); s_gcCollectTimeout = dur!"seconds"(2); } package(vibe) void performIdleProcessing() @safe nothrow { bool again = !getExitFlag(); while (again) { if (s_idleHandler) again = s_idleHandler(); else again = false; again = (s_scheduler.schedule() == ScheduleStatus.busy || again) && !getExitFlag(); if (again) { auto er = eventDriver.core.processEvents(0.seconds); if (er.among!(ExitReason.exited, ExitReason.outOfWaiters) && s_scheduler.scheduledTaskCount == 0) { logDebug("Setting exit flag due to driver signalling exit: %s", er); s_exitEventLoop = true; return; } } } if (s_scheduler.scheduledTaskCount) logDebug("Exiting from idle processing although there are still yielded tasks"); if (!s_ignoreIdleForGC && s_gcTimer) { s_gcTimer.rearm(s_gcCollectTimeout); } else s_ignoreIdleForGC = false; } private struct ThreadContext { Thread thread; } /**************************************************************************************************/ /* private functions */ /**************************************************************************************************/ private { Duration s_gcCollectTimeout; Timer s_gcTimer; bool s_ignoreIdleForGC = false; __gshared core.sync.mutex.Mutex st_threadsMutex; shared TaskPool st_workerPool; shared ManualEvent st_threadsSignal; __gshared ThreadContext[] st_threads; __gshared Condition st_threadShutdownCondition; shared bool st_term = false; bool s_isMainThread = false; // set in shared static this bool s_exitEventLoop = false; package bool s_eventLoopRunning = false; bool delegate() @safe nothrow s_idleHandler; TaskScheduler s_scheduler; FixedRingBuffer!TaskFiber s_availableFibers; size_t s_maxRecycledFibers = 100; string s_privilegeLoweringUserName; string s_privilegeLoweringGroupName; __gshared bool s_disableSignalHandlers = false; } private bool getExitFlag() @trusted nothrow { return s_exitEventLoop || atomicLoad(st_term); } package @property bool isEventLoopRunning() @safe nothrow @nogc { return s_eventLoopRunning; } package @property ref TaskScheduler taskScheduler() @safe nothrow @nogc { return s_scheduler; } package void recycleFiber(TaskFiber fiber) @safe nothrow { if (s_availableFibers.length >= s_maxRecycledFibers) { auto fl = s_availableFibers.front; s_availableFibers.popFront(); fl.shutdown(); () @trusted { try destroy(fl); catch (Exception e) logWarn("Failed to destroy fiber: %s", e.msg); } (); } if (s_availableFibers.full) s_availableFibers.capacity = 2 * s_availableFibers.capacity; s_availableFibers.put(fiber); } private void setupSignalHandlers() @trusted nothrow { scope (failure) assert(false); // _d_monitorexit is not nothrow __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() { 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); } } s_isMainThread = true; // 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"); 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); st_threadsSignal = createSharedManualEvent(); version(VibeIdleCollect) { logTrace("setup gc"); 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."); } import std.concurrency; scheduler = new VibedScheduler; import vibe.core.sync : SpinLock; SpinLock.setup(); } shared static ~this() { shutdownDriver(); size_t tasks_left = s_scheduler.scheduledTaskCount; if (tasks_left > 0) logWarn("There were still %d tasks running at exit.", tasks_left); } // 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; auto thisthr = Thread.getThis(); synchronized (st_threadsMutex) if (!st_threads.any!(c => c.thread is thisthr)) st_threads ~= ThreadContext(thisthr); import vibe.core.sync : SpinLock; SpinLock.setup(); } static ~this() { auto thisthr = Thread.getThis(); bool is_main_thread = s_isMainThread; synchronized (st_threadsMutex) { auto idx = st_threads.countUntil!(c => c.thread is thisthr); logDebug("Thread exit %s (index %s) (main=%s)", thisthr.name, idx, is_main_thread); } if (is_main_thread) { logDiagnostic("Main thread exiting"); shutdownWorkerPool(); } synchronized (st_threadsMutex) { auto idx = st_threads.countUntil!(c => c.thread is thisthr); 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) shutdownDriver(); st_threadShutdownCondition.notifyAll(); } private void shutdownWorkerPool() nothrow { shared(TaskPool) tpool; try synchronized (st_threadsMutex) swap(tpool, st_workerPool); catch (Exception e) assert(false, e.msg); if (tpool) { logDiagnostic("Still waiting for worker threads to exit."); tpool.terminate(); } } private void shutdownDriver() { if (ManualEvent.ms_threadEvent != EventID.init) { eventDriver.events.releaseRef(ManualEvent.ms_threadEvent); ManualEvent.ms_threadEvent = EventID.init; } eventDriver.dispose(); } private void watchExitFlag() { auto emit_count = st_threadsSignal.emitCount; while (true) { synchronized (st_threadsMutex) { if (getExitFlag()) break; } try emit_count = st_threadsSignal.wait(emit_count); catch (InterruptException e) return; } logDebug("main thread exit"); eventDriver.core.exit(); } private extern(C) void extrap() @safe nothrow { logTrace("exception trap"); } private extern(C) void onSignal(int signal) nothrow { logInfo("Received signal %d. Shutting down.", signal); atomicStore(st_term, true); try st_threadsSignal.emit(); catch (Throwable) {} } private extern(C) void onBrokenPipe(int signal) nothrow { logTrace("Broken pipe."); } version(Posix) { private bool isRoot() @trusted { return geteuid() == 0; } private void setUID(int uid, int gid) @trusted { logInfo("Lowering privileges to uid=%d, gid=%d...", uid, gid); if (gid >= 0) { enforce(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(getpwuid(uid) !is null, "Invalid user id!"); enforce(seteuid(uid) == 0, "Error setting user id!"); } } private int getUID(string name) @trusted { auto pw = getpwnam(name.toStringz()); enforce(pw !is null, "Unknown user name: "~name); return pw.pw_uid; } private int getGID(string name) @trusted { auto gr = 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); } }