-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
daemon.js
2035 lines (1927 loc) · 72.8 KB
/
daemon.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// no npm!
const fs = require('fs')
const os = require('os')
const net = require('net')
const dns = require('dns')
const path = require('path')
const lib = require(__dirname + '/lib')
const lokinet = require(__dirname + '/lokinet')
const configUtil = require(__dirname + '/config')
const networkTest = require(__dirname + '/lib.networkTest')
const cp = require('child_process')
const spawn = cp.spawn
const execSync = cp.execSync
const stdin = process.openStdin()
// use this to debug the EPIPEs
//const longjohn = require('longjohn')
let g_config = false
let server = false
let webApiServer = false
// start but not anything else (interactive, daemon-start)
if (1) {
process.on('uncaughtException', function (err) {
// might be amplifying the write EPIPE error
//console.trace('Caught exception:', err)
let var_path = '/tmp'
if (g_config) var_path = g_config.launcher.var_path
fs.appendFileSync(var_path + '/launcher_exception.log', JSON.stringify({
err: err,
code: err.code,
msg: err.message,
trace: err.stack.split("\n")
}) + "\n")
// if we're in cimode, throw up red flag
if (savePidConfig.config && savePidConfig.config.launcher.cimode) {
process.exit(1)
}
// we can't have this be looped written to the log...
/*
{"err":{"errno":-32,"code":"EPIPE","syscall":"write"},"code":"EPIPE","msg":"write EPIPE","trace":["Error: write EPIPE"," at afterWriteDispatched
*/
})
}
let connections = []
function disconnectAllClients() {
//console.log('SOCKET: Disconnecting all', connections.length, 'clients.')
for(let i in connections) {
const conn = connections[i]
if (!conn.destroyed) {
//console.log('disconnecting client #'+i)
conn.destroy()
}
}
connections = [] // clear them
}
// lower permissions and run cb
// don't use this for lokinet on MacOS
function lowerPermissions(user, cb) {
process.setuid(user)
}
function blockchain_running() {
return loki_daemon && loki_daemon.pid && lib.isPidRunning(loki_daemon.pid)
}
function storage_running() {
return storageServer && storageServer.pid && lib.isPidRunning(storageServer.pid)
}
function network_running() {
let lokinetState = lokinet.isRunning()
return lokinetState && lokinetState.pid && lib.isPidRunning(lokinetState.pid)
}
function waitfor_blockchain_shutdown(cb) {
setTimeout(function() {
if (!blockchain_running()) {
cb()
} else {
waitfor_blockchain_shutdown(cb)
}
}, 1000)
}
function shutdown_blockchain() {
if (loki_daemon) {
if (loki_daemon.outputFlushTimer) {
clearTimeout(loki_daemon.outputFlushTimer)
loki_daemon.outputFlushTimer = null
}
}
if (loki_daemon && !loki_daemon.killed) {
console.log('LAUNCHER: Requesting lokid be shutdown.', loki_daemon.pid)
try {
process.kill(loki_daemon.pid, 'SIGINT')
} catch(e) {
}
loki_daemon.killed = true
}
}
function shutdown_storage() {
if (storageServer && storageServer.killed) {
if (lib.isPidRunning(storageServer.pid)) {
console.log('LAUNCHER: killing SS again')
process.kill(storageServer.pid, 'SIGKILL')
}
}
if (storageServer && !storageServer.killed) {
// FIXME: was killed not set?
try {
// if this pid isn't running we crash
if (lib.isPidRunning(storageServer.pid)) {
console.log('LAUNCHER: Requesting storageServer be shutdown.', storageServer.pid)
process.kill(storageServer.pid, 'SIGINT')
} else {
console.log('LAUNCHER: ', storageServer.pid, 'is not running')
}
} catch(e) {
}
// mark that we've tried
storageServer.killed = true
// can't null it if we're using killed property
//storageServer = null
}
}
let shuttingDown = false
let exitRequested = false
let shutDownTimer = null
let lokinetPidwatcher = false
function shutdown_everything() {
//console.log('shutdown_everything()!')
//console.trace('shutdown_everything()!')
if (lokinetPidwatcher !== false) {
clearInterval(lokinetPidwatcher)
lokinetPidwatcher = false
}
shuttingDown = true
stdin.pause()
shutdown_storage()
// even if not running, yet, stop any attempts at starting it too
lokinet.stop()
lib.stop()
shutdown_blockchain()
// clear our start up lock (if needed, will crash if not there)
lib.clearStartupLock(module.exports.config)
// kill any blockchain restarts
module.exports.config.blockchain.restart = false
// FIXME: should we be savings pids as we shutdown? probably
// only set this timer once... (and we'll shut ourselves down)
if (shutDownTimer === null) {
shutDownTimer = setInterval(function () {
let stop = true
if (storage_running()) {
console.log('LAUNCHER: Storage server still running.')
stop = false
}
if (loki_daemon) {
if (loki_daemon.outputFlushTimer) {
// it can and does, if shutdown is called before lokid exits...
// sig handler?
//console.log('Should never hit me')
clearTimeout(loki_daemon.outputFlushTimer)
loki_daemon.outputFlushTimer = null
}
}
if (blockchain_running()) {
console.log('LAUNCHER: lokid still running.')
// lokid on macos may need a kill -9 after a couple failed 15
// lets say 50s of not stopping -15 then wait 30s if still run -9
stop = false
} else {
if (server) {
//console.log('SOCKET: Closing socket server.')
disconnectAllClients()
server.close()
server.unref()
if (fs.existsSync(module.exports.config.launcher.var_path + '/launcher.socket')) {
console.log('SOCKET: Cleaning socket.')
fs.unlinkSync(module.exports.config.launcher.var_path + '/launcher.socket')
}
server = false
}
}
const lokinetState = lokinet.isRunning()
if (network_running()) {
console.log('LAUNCHER: lokinet still running.')
stop = false
}
if (stop) {
if (webApiServer) {
webApiServer.close()
webApiServer.unref()
webApiServer = false
}
console.log('All daemons down.')
// deallocate
// can't null these yet because lokid.onExit
// race between the pid dying and registering of the exit
storageServer = null
loki_daemon = null
// FIXME: make sure lokinet.js handles this
// lokinetState = null
lib.clearPids(module.exports.config)
/*
if (fs.existsSync(config.launcher.var_path + '/pids.json')) {
console.log('LAUNCHER: clearing pids.json')
fs.unlinkSync(config.launcher.var_path + '/pids.json')
} else {
console.log('LAUNCHER: NO pids.json found, can\'t clear')
}
*/
clearInterval(shutDownTimer)
// docker/node 10 on linux has issue with this
// 10.15 on macos has a handle, probably best to release
if (stdin.unref) {
//console.log('unref stdin')
stdin.unref()
}
// if lokinet wasn't started yet, due to slow net/dns stuff
// then it'll take a long time for a timeout to happen
// 2 writes, 1 read
/*
var handles = process._getActiveHandles()
console.log('handles', handles.length)
for(var i in handles) {
var handle = handles[i]
console.log(i, 'type', handle._type)
}
console.log('requests', process._getActiveRequests().length)
*/
}
}, 5000)
}
// don't think we need, seems to handle itself
//console.log('should exit?')
//process.exit()
}
let storageServer
var storageLogging = true
// you get one per sec... so how many seconds to do you give lokid to recover?
// you don't get one per sec
// 120s
// it's one every 36 seconds
// so lets say 360 = 10
var lastLokidContactFailures = []
function launcherStorageServer(config, args, cb) {
if (shuttingDown) {
//if (cb) cb()
console.log('STORAGE: Not going to start storageServer, shutting down.')
return
}
// no longer true
/*
if (!config.storage.lokid_key) {
console.error('storageServer requires lokid_key to be configured.')
if (cb) cb(false)
return
}
*/
// set storage port default
if (!config.storage.port) {
config.storage.port = 8080
}
// configure command line parameters
const optionals = []
const requireds = []
if (config.storage.testnet) {
optionals.push('--testnet')
}
if (config.storage.log_level) {
optionals.push('--log-level', config.storage.log_level)
}
if (config.storage.data_dir) {
optionals.push('--data-dir', config.storage.data_dir)
}
// BLOCKCHAIN communication
if (configUtil.isStorageBinary2X(config) && !configUtil.isStorageBinary20X(config)) {
// 2.1+
if (config.storage.oxend_rpc_socket) {
optionals.push('--oxend-rpc', config.storage.oxend_rpc_socket)
}
else {
if (config.storage.oxend_rpc_ip) {
optionals.push('--oxend-rpc-ip', config.storage.oxend_rpc_ip)
}
if (config.storage.oxend_rpc_port) {
optionals.push('--oxend-rpc-port', config.storage.oxend_rpc_port)
}
}
} else {
if (config.storage.lokid_rpc_port) {
optionals.push('--lokid-rpc-port', config.storage.lokid_rpc_port)
}
}
// key/lmq-port
if (!configUtil.isStorageBinary2X(config)) {
// 1.0.x
// this was required, we'll stop supporting it in 2x (tho 2.0 still accepts it)
if (config.storage.lokid_key) {
optionals.push('--lokid-key', config.storage.lokid_key)
}
} else {
// 2.x
requireds.push('--lmq-port', config.storage.lmq_port)
}
if (config.storage.force_start) {
optionals.push('--force-start')
}
console.log('STORAGE: Launching', config.storage.binary_path, [config.storage.ip, config.storage.port, ...requireds, ...optionals].join(' '))
/*
// ip and port must be first
var p1 = '"' + (['ulimit', '-n', '16384 ; ', config.storage.binary_path, config.storage.ip, config.storage.port, ...requireds, ...optionals].join(' ')) + '"'
console.log('p1', p1)
storageServer = spawn('/bin/bash', ['-c', p1], {
})
*/
storageServer = spawn(config.storage.binary_path, [config.storage.ip, config.storage.port, ...requireds, ...optionals])
//storageServer = spawn('/usr/bin/valgrind', ['--leak-check=yes', config.storage.binary_path, config.storage.ip, config.storage.port, '--log-level=trace', ...optionals])
// , { stdio: 'inherit' })
//console.log('storageServer', storageServer)
if (!storageServer.stdout || !storageServer.pid) {
console.error('storageServer failed?')
if (cb) cb(false)
return
}
storageServer.killed = false
storageServer.startTime = Date.now()
storageServer.blockchainFailures = {}
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
function getPidLimit(pid) {
// linux only
try {
const currentLimit = execSync(`grep 'open file' /proc/${pid}/limits`)
const lines = currentLimit.toString().split('\n')
const parts = lines[0].split(/\s{2,}/)
//console.log('lines', lines)
//console.log('parts', parts)
return [ parts[1], parts[2]]
} catch(e) {
console.error('getPidLimit error', e.code, e.message)
return [ 0, 0 ]
}
}
if (configUtil.isStorageBinary2X(config)) {
var limits = getPidLimit(storageServer.pid)
if (limits[0] < 16384 || limits[1] < 16384) {
console.error('')
var ourlimits = getPidLimit(process.pid)
console.warn('')
console.warn('node limits', ourlimits, 'oxen-storage limits', limits)
console.warn('There maybe not enough file descriptors to run oxen-storage, you may want to look at increasing it')
console.warn('')
// console.error('Not enough file descriptors to run loki-storage, shutting down')
// console.error("put LimitNOFILE=16384 in your [Service] section of /etc/systemd/system/lokid.service")
// shutdown_everything()
}
}
//var fixResult = execSync(`prlimit --pid ${storageServer.pid} --nofile=16384:16384`)
//var fixResult = execSync(`python3 -c "import resource; resource.prlimit(${storageServer.pid}, resource.RLIMIT_NOFILE, (2048, 16384))"`)
//console.log('fixResult', fixResult.toString())
//console.log('after', getPidLimit())
// copy the output to stdout
let storageServer_version = 'unknown'
let stdout = '', stderr = '', collectData = true
let probablySyncing = false
storageServer.stdout
.on('data', (data) => {
const logLinesStr = data.toString('utf8').trim()
if (collectData) {
const lines = logLinesStr.split(/\n/)
for(let i in lines) {
const tline = lines[i].trim()
if (tline.match('Loki Storage Server v')) {
const parts = tline.split('Loki Storage Server v')
storageServer_version = parts[1]
}
if (tline.match('git commit hash: ')) {
const parts = tline.split('git commit hash: ')
fs.writeFileSync(config.launcher.var_path + '/storageServer.version', storageServer_version+"\n"+parts[1])
}
if (tline.match(/pubkey_x25519_hex is missing from sn info/)) {
// it's be nice to know lokid was syncing
// but from the loki-storage logs doesn't look like it's possible to tell
// save some logging space
continue
}
// can't do this if backgrounded
//if (storageLogging) console.log(`STORAGE(Start): ${tline}`)
}
stdout += data
} else {
const lines = logLinesStr.split(/\n/)
for(let i in lines) {
const str = lines[i].trim()
let outputError = true
// all that don't need storageServer set
// could be testing a remote node
if (str.match(/Could not report node status: bad json in response/)) {
} else if (str.match(/Could not report node status/)) {
}
if (str.match(/Empty body on Lokid report node status/)) {
}
// end remote node
if (!storageServer) {
if (storageLogging && outputError) console.log(`STORAGE: ${logLinesStr}`)
console.log('storageServer is unset, yet getting output', logLinesStr)
continue
}
// all that need storageServer set
// blockchain test
if (str.match(/Could not send blockchain request to Lokid/)) {
if (storageLogging) console.log(`STORAGE: blockchain test failure`)
storageServer.blockchainFailures.last_blockchain_test = Date.now()
//communicate this out
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
// blockchain ping
if (str.match(/Empty body on Lokid ping/) || str.match(/Could not ping Lokid. Status: {}/) ||
str.match(/Could not ping Lokid: bad json in response/) || str.match(/Could not ping Lokid/)) {
if (storageLogging) console.log(`STORAGE: blockchain ping failure`)
storageServer.blockchainFailures.last_blockchain_ping = Date.now()
//communicate this out
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
// probably syncing
if (str.match(/Bad lokid rpc response: invalid json fields/)) {
probablySyncing = true
}
if (str.match(/pubkey_x25519_hex is missing from sn info/)) {
// it's be nice to know lokid was syncing
// but from the loki-storage logs doesn't look like it's possible to tell
// save some logging space
outputError = false // hide these
continue // no need to output it again
}
// swarm_tick communication error
// but happens when lokid is syncing, so we can't restart lokid
if (str.match(/Exception caught on swarm update: Failed to parse swarm update/)) {
if (probablySyncing) {
if (storageLogging) console.log(`STORAGE: blockchain comms failure, probably syncing`)
outputError = false // hide these
continue // no need to output it again
} else {
if (storageLogging) console.log(`STORAGE: blockchain tick failure`)
storageServer.blockchainFailures.last_blockchain_tick = Date.now()
//communicate this out
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
} else if (str.match(/Exception caught on swarm update/)) {
if (storageLogging) console.log(`STORAGE: blockchain tick failure. Maybe syncing? ${probablySyncing}`)
storageServer.blockchainFailures.last_blockchain_tick = Date.now()
//communicate this out
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
// swarm_tick communication error
if (str.match(/Failed to contact local Lokid/)) {
var ts = Date.now()
// skip if lokid is restarting...
if (requestBlockchainRestartLock) continue
lastLokidContactFailures.push(ts)
if (lastLokidContactFailures.length > 5) {
lastLokidContactFailures.splice(-5)
}
// exitRequested doesn't need to double up on the output in interactive-debug
if (!shuttingDown && !exitRequested) {
console.log('STORAGE: can not contact blockchain, failure count', lastLokidContactFailures.length, 'first', parseInt((ts - lastLokidContactFailures[0]) / 1000) + 's ago')
}
// if the oldest one is not more than 180s ago
// it's not every 36s
// a user provided a ss where there was 300s between the 1st and the 2nd
// 0,334,374.469.730,784
// where it should have been restarted, so 5 in 15 mins will be our new tune
// was 11 * 36
if (lastLokidContactFailures.length == 5 && ts - lastLokidContactFailures[0] < 900 * 1000) {
// now it's a race, between us detect lokid shutting down
// and us trying to restart it...
// mainly will help deadlocks
if (!exitRequested) { // user typed exit
// don't keep trying to restart it
// lokid will be done for 30s if it's being restarted.
//if (loki_daemon && !loki_daemon.killed) {
console.log('we should restart lokid');
requestBlockchainRestart(config);
//}
}
}
if (storageLogging) console.log(`STORAGE: blockchain tick contact failure`)
storageServer.blockchainFailures.last_blockchain_tick = Date.now()
//communicate this out
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
//if (storageLogging && outputError) console.log(`STORAGE: ${logLinesStr}`)
}
}
//if (storageLogging) console.log(`STORAGE: ${logLinesStr}`)
})
.on('error', (err) => {
console.error(`Storage Server stdout error: ${err.toString('utf8').trim()}`)
})
storageServer.stderr
.on('data', (err) => {
if (storageLogging) console.log(`Storage Server error: ${err.toString('utf8').trim()}`)
})
.on('error', (err) => {
console.error(`Storage Server stderr error: ${err.toString('utf8').trim()}`)
})
function watchdogCheck() {
// console.log('STORAGE: checking for deadlock')
lib.runStorageRPCTest(lokinet, config, function(data) {
if (data === undefined) {
console.log('STORAGE: RPC server not responding, restarting storage server')
shutdown_storage()
// what restarts this? something does
}
})
}
function startupComplete() {
//console.log('STORAGE: Turning off storage server start up watcher, starting watchdog')
collectData = false
stdout = ''
stderr = ''
clearInterval(memoryWatcher)
memoryWatcher = null
watchdog = setInterval(watchdogCheck, 10 * 60 * 1000)
}
// don't hold up the exit too much
let watchdog = null
// startupComplete will stop us
let memoryWatcher = setInterval(function() {
lib.runStorageRPCTest(lokinet, config, function(data) {
// start complete is complete when the RPC responds
if (data !== undefined) {
startupComplete()
}
})
}, 10 * 1000)
storageServer.on('error', (err) => {
console.error('STORAGEP_ERR:', JSON.stringify(err))
})
storageServer.on('close', (code, signal) => {
if (memoryWatcher !== null) clearInterval(memoryWatcher)
if (watchdog !== null) clearInterval(watchdog)
console.log(`StorageServer process exited with code ${code}/${signal} after`, (Date.now() - storageServer.startTime).toLocaleString()+'ms')
storageServer.killed = true
if (code == 1) {
// these seem to be empty
console.log(stdout, 'stderr', stderr)
// also now can be a storage server crash
// also can mean bad params passed in
// we can use a port to check to make sure...
console.log('')
console.warn('StorageServer bind port could be in use, please check to make sure.', config.storage.binary_path, 'is not already running on port', config.storage.port)
// we could want to issue one kill just to make sure
// however since we don't know the pid, we won't know if it's ours
// or meant be running by another copy of the launcher
// at least any launcher copies will be restarted
//
// we could exit, or prevent a restart
storageServer = null // it's already dead
// we can no longer shutdown here, if storage server crashes, we do need to restart it...
//return shutdown_everything()
}
// code null means clean shutdown
if (!shuttingDown) {
// wait 30s
setTimeout(function() {
console.log('loki_daemon is still running, restarting storageServer.')
launcherStorageServer(config, args)
}, 30 * 1000)
}
})
/*
function flushOutput() {
if (!storageServer || storageServer.killed) {
console.log('storageServer flushOutput lost handle, stopping flushing')
return
}
storageServer.stdin.write("\n")
// schedule next flush
storageServer.outputFlushTimer = setTimeout(flushOutput, 1000)
}
console.log('starting log flusher for storageServer')
storageServer.outputFlushTimer = setTimeout(flushOutput, 1000)
*/
if (cb) cb(true)
}
let waitForLokiKeyTimer = null
// as of 6.x storage and network not get their key via rpc call
// and this isn't called unless the lokid is pre 6.x
function waitForLokiKey(config, timeout, start, cb) {
if (start === undefined) start = Date.now()
if (config.storage.lokid_key === undefined) {
if (config.storage.enabled) {
console.error('Storage lokid_key is not configured')
process.exit(1)
}
cb(true)
return
}
console.log('DAEMON: Checking on', config.storage.lokid_key)
if (!fs.existsSync(config.storage.lokid_key)) {
if (timeout && (Date.now - start > timeout)) {
cb(false)
return
}
waitForLokiKeyTimer = setTimeout(function() {
waitForLokiKey(config, timeout, start, cb)
}, 1000)
return
}
waitForLokiKeyTimer = null
cb(true)
}
// FIXME: make sure blockchain.rpc port is bound before starting...
let rpcUpTimer = null
function startStorageServer(config, args, cb) {
//console.log('trying to get IP information about lokinet')
// does this belong here?
if (config.storage.enabled) {
if (config.storage.data_dir !== undefined) {
if (!fs.existsSync(config.storage.data_dir)) {
lokinet.mkDirByPathSync(config.storage.data_dir)
}
}
}
function checkRpcUp(cb) {
if (shuttingDown) {
//if (cb) cb()
console.log('STORAGE: Not going to start storageServer, shutting down.')
return
}
// runStorageRPCTest(lokinet, config, function(data) {
// if (data !== undefined) {
// return cb()
// }
//})
lokinet.portIsFree(config.blockchain.rpc_ip, config.blockchain.rpc_port, function(portFree) {
if (!portFree) {
cb()
return
}
rpcUpTimer = setTimeout(function() {
checkRpcUp(cb)
}, 5 * 1000)
})
}
checkRpcUp(function() {
//console.log('checkRpcUp cb')
config.storage.ip = '0.0.0.0';
if (config.network.enabled) {
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
launcherStorageServer(config, args, cb)
/*
lokinet.getLokiNetIP(function (ip) {
// lokinet has started, save config and various process pid
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
if (ip) {
console.log('DAEMON: Starting storageServer on', ip)
config.storage.ip = ip
launcherStorageServer(config, args, cb)
} else {
console.error('DAEMON: Sorry cant detect our lokinet IP:', ip)
if (cb) cb(false)
//shutdown_everything()
}
})
*/
} else if (config.storage.enabled) {
/*
lokinet.getNetworkIP(function(err, localIP) {
console.log('DAEMON: Starting storageServer on', localIP)
// we can only ever bind to the local IP
config.storage.ip = localIP
launcherStorageServer(config, args, cb)
})
*/
launcherStorageServer(config, args, cb)
} else {
console.log('StorageServer is not enabled.')
}
})
}
function startLokinet(config, args, cb) {
//console.log('DAEMON: startLokinet')
// we no longer need to wait for LokiKey before starting network/storage
// waitForLokiKey(config, timeout, start, cb)
if (configUtil.isBlockchainBinary3X(config) || configUtil.isBlockchainBinary4Xor5X(config)) {
// 3.x-5.x, we need the key
if (config.storage.lokid_key === undefined) {
if (config.storage.enabled) {
console.error('Storage server enabled but no key location given.')
process.exit(1)
}
if (config.network.enabled) {
lokinet.startServiceNode(config, function () {
startStorageServer(config, args, cb)
})
} else {
//console.log('no storage key configured')
if (cb) cb(true)
}
return
}
console.log('DAEMON: Waiting for oxen key at', config.storage.lokid_key)
waitForLokiKey(config, 30 * 1000, undefined, function(haveKey) {
if (!haveKey) {
console.error('DAEMON: Timeout waiting for loki key.')
// FIXME: what do?
return
}
console.log('DAEMON: Got Oxen key!')
if (config.network.enabled) {
lokinet.startServiceNode(config, function () {
startStorageServer(config, args, cb)
})
} else {
if (config.storage.enabled) {
startStorageServer(config, args, cb)
} else {
if (cb) cb(true)
}
}
})
} else {
// 6.x+, not key needed
if (config.network.enabled) {
config.network.onStart = function(config, instance, lokinetProc) {
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
config.network.onStop = function(config, instance, lokinetProc) {
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
lokinet.startServiceNode(config, function () {
lokinetPidwatcher = setInterval(function() {
// read pids.json
var pids = lib.getPids(config)
var lokinetProc = lokinet.isRunning()
if (lokinetProc) {
// console.log('lokinet pid is', lokinetProc.pid, 'json is', pids.lokinet)
if (lokinetProc.pid != pids.lokinet) {
console.warn('Updating lokinet PID')
lib.savePids(config, args, loki_daemon, lokinet, storageServer)
}
} else {
console.log('no lokinet pid', lokinet)
}
}, 30 * 1000)
startStorageServer(config, args, cb)
})
} else {
if (config.storage.enabled) {
startStorageServer(config, args, cb)
} else {
if (cb) cb(true)
}
}
}
}
function startLauncherDaemon(config, interactive, entryPoint, args, debug, cb) {
/*
try {
process.seteuid('rtharp')
console.log(`New uid: ${process.geteuid()}`)
} catch(err) {
console.log(`Failed to set uid: ${err}`)
}
*/
function doStart() {
function startBackgroundCode() {
// backgrounded or launched in interactive mode
// strip any launcher-specific params we shouldn't need any more
for(var i in args) {
var arg = args[i]
if (arg == '--skip-storage-server-port-check') {
args.splice(i, 1) // remove this option
} else
if (arg == '--ignore-storage-server-port-check') {
args.splice(i, 1) // remove this option
}
}
//console.log('backgrounded or launched in interactive mode')
g_config = config
lib.setStartupLock(config)
cb()
}
// see if we need to detach
//console.log('interactive', interactive)
if (!interactive) {
//console.log('fork check', process.env.__daemon)
if (!process.env.__daemon || config.launcher.cimode) {
//console.log('cimode', config.launcher.cimode)
let child
if (!config.launcher.cimode) {
// first run
process.env.__daemon = true
// spawn as child
const cp_opt = {
stdio: ['ignore', 'pipe', 'pipe'],
env: process.env,
cwd: process.cwd(),
detached: true
}
// this doesn't work like this...
//args.push('1>', 'log.out', '2>', 'err.out')
console.log('Launching', process.execPath, entryPoint, 'daemon-start', args)
child = spawn(process.execPath, [entryPoint, 'daemon-start', '--skip-storage-server-port-check'].concat(args), cp_opt)
//console.log('child', child)
if (!child) {
console.error('Could not spawn detached process')
process.exit(1)
}
// won't accumulate cause we're quitting...
var stdout = '', stderr = ''
child.stdout.on('data', (data) => {
//if (debug) console.log(data.toString())
stdout += data.toString()
})
child.stderr.on('data', (data) => {
//if (debug) console.error(data.toString())
stderr += data.toString()
})
//var launcherHasExited = false
function crashHandler(code, signal) {
console.log('Background launcher died with', code, signal, stdout, stderr)
//launcherHasExited = true
process.exit(1)
}
child.on('close', crashHandler)
}
// required so we can exit
var startTime = Date.now()
console.log('Waiting on start up confirmation...')
function areWeRunningYet() {
//console.debug('areWeRunningYet')
var diff = Date.now() - startTime
// , process.pid
console.log('Checking start up progress...')
lib.getLauncherStatus(config, lokinet, 'waiting...', function(running, checklist) {
//console.debug('getLauncherStatus called back')
var nodeVer = Number(process.version.match(/^v(\d+\.\d+)/)[1])
if (nodeVer >= 10) {
console.table(checklist)
} else {
console.log(checklist)
}
var pids = lib.getPids(config) // need to get the config
// blockchain rpc is now required for SN
var blockchainIsFine = pids.runningConfig && pids.runningConfig.blockchain && checklist.blockchain_rpc !== 'waiting...'
// donish conditions
if (running.launcher && running.lokid && checklist.socketWorks !== 'waiting...' &&
pids.runningConfig && blockchainIsFine
) {
if (checklist.blockchain_status && checklist.blockchain_status.split(/ /).includes('syncingChain')) {
console.log('Blockchain is syncing, likely will be a long time until storage/network will be ready, check status periodically')
if (child) child.removeListener('close', crashHandler)
process.exit()
}
var networkIsFine = (!pids.runningConfig) || (!pids.runningConfig.network) || (!pids.runningConfig.network.enabled) || (checklist.network !== 'waiting...')
if (running.launcher && running.lokid && checklist.socketWorks !== 'waiting...' &&
pids.runningConfig && blockchainIsFine && networkIsFine &&
checklist.storageServer !== 'waiting...' && checklist.storage_rpc !== 'waiting...'
) {
console.log('Start up successful!')
if (child) child.removeListener('close', crashHandler)
process.exit()
}
}
// if storage is enabled but not running, wait for it
if (pids.runningConfig && pids.runningConfig.storage.enabled && checklist.storageServer === 'waiting...' && blockchainIsFine && networkIsFine) {
// give it 30s more if everything else is fine... for what?
if (diff > 1.5 * 60 * 1000) {
console.log('Storage server start up timeout, likely failed.')
process.exit(1)
}
setTimeout(areWeRunningYet, 5000)
return
}
if (pids.runningConfig && pids.runningConfig.storage.enabled && checklist.storage_rpc === 'waiting...' && blockchainIsFine && networkIsFine) {
// give it 15s more if everything else is fine... for it's DH generation
if (diff > 1.75 * 60 * 1000) {
console.log('Storage server rpc timeout, likely DH generation is taking long...')
process.exit(0)
}
setTimeout(areWeRunningYet, 5000)
return
}
if (diff > 1 * 60 * 1000) {
console.log('Start up timeout, likely failed.')
process.exit(1)
}
//if (!launcherHasExited) {
setTimeout(areWeRunningYet, 5000)
//}
})
}
// 5s might not be enough
setTimeout(areWeRunningYet, 5000)
if (child) child.unref()
if (config.launcher.cimode) {
console.log('continuing foreground startup')
startBackgroundCode()
}
return
}
// no one sees these
//console.log('backgrounded')
} else {
// interactive is mainly for lokid
if (!debug) {
lokinet.disableLogging(true)
storageLogging = false
}
}
startBackgroundCode()
}
function testOpenPorts() {
// move deterministic behavior than letting the OS decide
console.log('Starting verification phase')
const testingHostname = 'testing.hesiod.network'
console.log('Downloading test servers from', testingHostname)
dns.resolve4(testingHostname, function(err, addresses) {
if (err) console.error('dnsLookup err', err)
//console.log('addresses', addresses)
function tryAndConnect() {
var idx = parseInt(Math.random() * addresses.length)
var server = addresses[idx]
/*
dns.resolvePtr(server, function(err, names) {
if (err) console.error('dnsPtrLookup err', err)
if (names.length) console.log('trying to connect to', names[0])
})
*/
console.log('Trying to connect to', server)
addresses.splice(idx, 1) // remove it
networkTest.createClient(server, 3000, async function(client) {
//console.log('client', client)
if (debug) console.debug('got createClient cb')
if (client === false) {
if (!addresses.length) {
console.warn('We could not connect to ANY testing server, you may want to check your internet connection and DNS settings')
/*
setTimeout(function() {
testOpenPorts()
}, 30 * 1000)
*/
console.log('Verification phase complete')
doStart()
} else {
// retry with a different server
tryAndConnect()
}
return
}
// select your tests
const ourTests = []
if (!configUtil.isBlockchainBinary3X(config) && !configUtil.isBlockchainBinary4Xor5X(config)) {
ourTests.push({
name: 'blockchain quorumnet',