1
1
2
2
var exec = require ( 'child_process' ) . exec ;
3
- var wake = require ( 'wake-event' ) ;
4
3
var os = require ( 'os' ) ;
5
4
var http = require ( 'http' ) ;
6
5
@@ -26,31 +25,56 @@ program
26
25
. option ( '-p, --port <port>' , 'Port to run server on (default: 57339)' , 57339 )
27
26
. option ( '-H, --host <host>' , 'Interface to run server on (default: 0.0.0.0)' , '0.0.0.0' )
28
27
. option ( '-u, --url <url>' , 'URL to trigger sleep (default: sleep)' , 'sleep' )
29
- . option ( '-d, --delay <ms>' , 'Delay in milliseconds (default: 1000)' , 1000 )
28
+ . option ( '-w, --wait <ms>' , 'Wait in milliseconds before sleeping (default: 3000)' , 3000 )
29
+ . option ( '-d, --daemonize' , 'Daemonize the sleep server and send output to a file (default: log.txt)' , 'log.txt' )
30
30
. parse ( process . argv ) ;
31
31
32
+ //daemonize?
33
+ if ( program . daemonize && program . args . indexOf ( 'is-daemon' ) === - 1 ) {
34
+ var path = program . daemonize ;
35
+ var fs = require ( 'fs' ) ;
36
+ var spawn = require ( 'child_process' ) . spawn ;
37
+ var log = fs . openSync ( path , 'a' ) ;
38
+
39
+ var prog = process . argv [ 1 ] ;
40
+ var args = process . argv . slice ( 2 ) ;
41
+ args . push ( 'is-daemon' ) ;
42
+
43
+ var child = spawn ( prog , args , {
44
+ detached : true ,
45
+ stdio : [ 'ignore' , log , log ]
46
+ } ) ;
47
+ child . unref ( ) ;
48
+ process . exit ( 1 ) ;
49
+ return ;
50
+ }
51
+
32
52
//add a slash
33
53
if ( program . url . charAt ( 0 ) !== '/' )
34
54
program . url = '/' + program . url ;
35
55
36
56
var msgId = 1 ;
37
-
38
57
http . createServer ( function ( request , response ) {
39
58
if ( request . url . indexOf ( program . url ) !== 0 )
40
- return response . end ( ) ;
41
-
59
+ return response . end ( 'not-ok' ) ;
42
60
console . log ( "#%s:\n Sleeping in %sms\n Time: %s\n IP address: %s" ,
43
- msgId ++ , program . delay , new Date ( ) , request . connection . remoteAddress ) ;
44
-
61
+ msgId ++ , program . wait , new Date ( ) , request . connection . remoteAddress ) ;
45
62
setTimeout ( function ( ) {
46
63
exec ( command ) ;
47
- } , program . delay ) ;
64
+ } , program . wait ) ;
48
65
response . end ( 'ok' ) ;
49
66
} ) . listen ( program . port , function ( ) {
50
67
console . log ( 'Listening for sleep requests at http://%s:%s%s' , program . host , program . port , program . url ) ;
51
68
} ) ;
52
69
53
- wake ( function ( ) {
54
- console . log ( "#%s:\n Woke\n Time: %s" , msgId ++ , new Date ( ) ) ;
55
- } ) ;
70
+ //if interval is late by more than 2secs, assume has just awoken
71
+ var checkInterval = 5000 ;
72
+ var threshold = 2000 ;
73
+ var lastTime = Date . now ( ) ;
74
+ setInterval ( function ( ) {
75
+ var currentTime = Date . now ( ) ;
76
+ if ( currentTime > ( lastTime + checkInterval + threshold ) )
77
+ console . log ( "#%s:\n Woke\n Time: %s" , msgId ++ , new Date ( ) ) ;
78
+ lastTime = currentTime ;
79
+ } , checkInterval ) ;
56
80
0 commit comments