-
Notifications
You must be signed in to change notification settings - Fork 0
/
WolframServerManageTool.wl
63 lines (48 loc) · 2.06 KB
/
WolframServerManageTool.wl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(* ::Package:: *)
BeginPackage["WolframServerManageTool`"]
ServerShutdown::usage = "ServerShutdown[]";
ServerRestart::usage = "ServerRestart[]";
ServerMonitor::usage = "Hold the main loop to forbid process to exit. When a specific message is generated, restart the server.";
ApacheDateString::usage = "It's the Apache type DateString[], which is used for ExportString[expr, \"ApacheLog\"]."
ShowLog::usage = "ShowLog[logfile]. ShowLog[] is equivalent to ShowLog[\"nohup.out\"]";
$ServerHost
$CurrentListener
$CurrentZMQTask := ZeroMQLink`Private`$AsyncState["Task"]
ServerStart[OptionsPattern[]] := (
$CurrentListener = SocketListen[{OptionValue["IPAddress"],OptionValue["Port"]}, OptionValue[HandlerFunctions]]
)
Options[ServerStart] = {"IPAddress" -> "0.0.0.0", "Port" -> 8080, HandlerFunctions -> WolframServer`HTTPRespond};
ServerShutdown = With[{sockets = Cases[$CurrentListener /@ {"Socket", "SourceSocket"}, _SocketObject]},
RemoveAsynchronousTask@$CurrentZMQTask;
DeleteObject@WolframServer`$CurrentListener;
Close /@ sockets;
Print@"Server is closed."
]&;
ServerRestart = With[
{
socketspec = $CurrentListener["Socket"]/@{"DestinationIPAddress","DestinationPort"},
respond = $CurrentListener["HandlerFunctions"]["DataReceived"]
},
ServerShutdown[];
Pause[1];
WolframServerManageTool`$CurrentListener = SocketListen[socketspec, respond];
Print@"Server is restarted.";
]&;
ServerMonitor[Optional[msg:{_MessageName..}|_Sequence, {Write::zmqexception}], Optional[period_?NumericQ, 0.1]] :=
While[True,
Check[
Pause@period,
(
TaskRemove@$CurrentZMQTask;
ServerRestart[]
),
msg
]
];
SetAttributes[ServerMonitor,HoldFirst];
ApacheDateString[dateObj_DateObject:Now] := With[{timeZone = StringReplace[DateString["ISOTimeZone"], ":" -> ""]},
DateString@@{dateObj, {"[", "Day", "/", "Month", "/", "Year", ":", "Hour", ":", "Minute", ":", "Second", " ", timeZone, "]"}}
];
ApacheLog := StringTemplate["`IP` - - `Time` \"`Method` `Path` `Scheme`/`HTTPVersion`\" `StatusCode` `Query`"];
ShowLog[logfile_:"./nohup.out"] := Import[logfile, "Text"]
EndPackage[]