Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
346 lines (297 loc) · 10.5 KB
/
Copy pathmain.js
File metadata and controls
346 lines (297 loc) · 10.5 KB
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
#!/usr/bin/env node
// xySat - xyOps Satellite - Main entry point
// Copyright (c) 2019 - 2025 PixlCore LLC
// BSD 3-Clause License -- see LICENSE.md
const Path = require('path');
const fs = require('fs');
const cp = require('child_process');
const os = require('os');
const PixlServer = require("pixl-server");
const pkg = require('./package.json');
const self_bin = Path.resolve(process.argv[0]) + ' ' + Path.resolve(process.argv[1]);
const config_file = process.env.XYSAT_config_file || Path.join( __dirname, 'config.json' );
const is_windows = !!process.platform.match(/^win/);
var config = {};
var sample_config = {
hosts: [ "localhost" ],
port: 5522,
secure: false,
socket_opts: { rejectUnauthorized: false },
pid_file: "pid.txt",
log_dir: "logs",
log_filename: "[component].log",
log_crashes: true,
log_archive_path: "logs/archives/[filename]-[yyyy]-[mm]-[dd].log.gz",
log_archive_keep: "7 days",
temp_dir: "temp",
debug_level: 5,
child_kill_timeout: 10,
monitoring_enabled: true,
quickmon_enabled: true,
graphics_enabled: false,
docker_enabled: true
};
const cli = require('pixl-cli');
var Tools = cli.Tools;
var args = cli.args;
cli.global();
// special windows install mode
if ((args.install || args.uninstall || args.stop) && is_windows) {
// install as a windows service, or uninstall
process.chdir( __dirname );
// patch out console.log because node-windows dumps debug info to it
// see: https://github.com/coreybutler/node-windows/issues/382
console.log = function() {};
var Service = require('node-windows').Service;
var svc = new Service({
name: 'xyOps Satellite',
description: 'xyOps Satellite',
script: Path.resolve( __dirname, 'main.js' ),
execPath: process.execPath,
scriptOptions: [ '--foreground' ],
delayedAutoStart: true
});
if (args.install) {
svc.on('start', function() {
print("\nxyOps Satellite has been started successfully.\n\n");
process.exit(0);
});
svc.on('error', function(err) {
print("\nWindows Service Installation Error: " + err + "\n\n");
process.exit(1);
});
var installCompleted = function() {
print("\nxyOps Satellite has been installed successfully.\n");
if (!fs.existsSync(config_file)) {
config = sample_config;
var raw_config = JSON.stringify( config, null, "\t" );
Tools.writeFileAtomicSync( config_file, raw_config, { mode: 0o600, flush: true } );
print("\nA sample config file has been created: " + config_file + ":\n");
print( raw_config + "\n" );
process.exit(0);
}
else {
svc.start();
}
};
svc.on('install', installCompleted);
svc.on('alreadyinstalled', installCompleted);
svc.install();
} // install
if (args.uninstall) {
const task = `xysat-delete-${Date.now()}`;
const logFile = Path.join(os.tmpdir(), `${task}.log`);
cli.setLogFile( logFile );
println("Uninstalling xyOps Satellite...");
var scheduleBackgroundDelete = function() {
println("Preparing final background deletion process...");
try {
// kill main process if still running
var pid = parseInt( fs.readFileSync( 'pid.txt', 'utf8' ) );
if (pid) process.kill( pid, 'SIGTERM' );
} catch (e) {;}
// delete directory in background using schtasks
const installDir = __dirname;
try { process.chdir(os.tmpdir()); } catch {}
const psFile = Path.join(os.tmpdir(), `${task}.ps1`);
const escPS = (s) => s.replace(/'/g, "''"); // for single-quoted PS strings
const ps = [
`$log = '${escPS(logFile)}'`,
`function Log($msg) {`,
` $ts = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff')`,
` Add-Content -LiteralPath $log -Value ("[$ts] " + $msg)`,
`}`,
``,
`Log "BEGIN self-delete script"`,
`Log ("Script path: " + $MyInvocation.MyCommand.Path)`,
`Log ("Target dir: ${escPS(installDir)}")`,
`Log "Sleeping for 10 seconds..."`,
`Start-Sleep -Seconds 10`,
``,
`try {`,
` if (Test-Path -LiteralPath '${escPS(installDir)}') {`,
` Log "Attempting Remove-Item..."`,
` $err = $null`,
` Remove-Item -LiteralPath '${escPS(installDir)}' -Recurse -Force -ErrorAction SilentlyContinue -ErrorVariable err`,
` if (Test-Path -LiteralPath '${escPS(installDir)}') {`,
` Log "Remove-Item completed but target still exists."`,
` if ($err) { Log ("Remove-Item error: " + ($err | Out-String).Trim()) }`,
` } else {`,
` Log "SUCCESS: target deleted."`,
` }`,
` } else {`,
` Log "Target did not exist at delete time."`,
` }`,
`} catch {`,
` Log ("EXCEPTION: " + $_.Exception.Message)`,
`}`,
``,
`Log "Cleaning up script file..."`,
`try { Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue } catch {}`,
`Log "END self-delete script"`
].join('\n') + '\n';
fs.writeFileSync(psFile, ps, 'utf8');
cli.log("Temp Script: " + psFile);
const tr = `powershell.exe -NoProfile -ExecutionPolicy Bypass -File \\"${psFile}\\"`;
// Use a locale-free placeholder schedule, then explicitly run and delete the task below.
let cmd = `schtasks /Create /TN "${task}" /SC ONSTART /RU SYSTEM /RL HIGHEST /TR "${tr}"`;
cmd += ` && schtasks /Run /TN "${task}" && schtasks /Delete /TN "${task}" /F`;
cli.log("Executing Command: " + cmd);
const child = cp.spawn(cmd, {
shell: true,
detached: true,
stdio: 'ignore',
windowsHide: true
});
child.unref();
print("\nBackground deletion was scheduled successfully.\n\n");
}; // scheduleBackgroundDelete
scheduleBackgroundDelete();
svc.on('uninstall', function() {
println("Service 'uninstall' hook has fired.");
});
svc.on('alreadyuninstalled', function() {
println("Service 'alreadyuninstalled' hook has fired.");
});
svc.on('error', function(err) {
print("\nWindows Service Error: " + err + "\n\n");
process.exit(1);
});
setTimeout( function() {
// giving scheduleBackgroundDelete a chance to register the task
// svc.uninstall seems to kill the current process, so we have to do it last
println("Calling service uninstall...");
svc.uninstall();
}, 1000 );
} // uninstall
if (args.stop) {
svc.on('stop', function() {
print("\nxyOps Satellite has been stopped.\n\n");
process.exit(0);
});
svc.on('error', function(err) {
print("\nWindows Service Error: " + err + "\n\n");
process.exit(1);
});
svc.stop();
} // stop
return;
} // windows
// setup pixl-boot for startup service
var boot = require('pixl-boot');
var boot_opts = {
name: "xysat",
company: "PixlCore LLC",
script: self_bin,
linux_type: "forking",
linux_after: "network.target",
linux_wanted_by: "multi-user.target",
darwin_type: "agent"
};
if (args.install || (args.other && (args.other[0] == 'install'))) {
// first time install
process.chdir( __dirname );
boot.install(boot_opts, function(err) {
if (err) throw err;
print("\nxyOps Satellite has been installed successfully.\n");
if (!fs.existsSync(config_file)) {
config = sample_config;
var raw_config = JSON.stringify( config, null, "\t" );
Tools.writeFileAtomicSync( config_file, raw_config, { mode: 0o600, flush: true } );
print("\nA sample config file has been created: " + config_file + ":\n");
print( raw_config + "\n" );
}
print("\n");
process.exit(0);
} );
}
else if (args.uninstall || (args.other && (args.other[0] == 'uninstall'))) {
// uninstall satellite
process.chdir( __dirname );
boot.uninstall(boot_opts, function(err) {
try {
// kill main process if still running
var pid = parseInt( fs.readFileSync( 'pid.txt', 'utf8' ) );
if (pid) process.kill( pid, 'SIGTERM' );
} catch (e) {;}
// delete entire sat directory
try { Tools.rimraf.sync( __dirname ); }
catch (e) { die("\nError: Failed to delete folder: " + __dirname + ": " + e + "\n\n"); }
print("\nxyOps Satellite has been removed successfully.\n");
print("\n");
process.exit(0);
} );
}
else if (args.stop || (args.other && (args.other[0] == 'stop'))) {
// shutdown if running
process.chdir( __dirname );
var pid = 0;
try { pid = parseInt( fs.readFileSync( 'pid.txt', 'utf8' ) ); } catch (e) {;}
if (!pid) die("\nError: xyOps Satellite is not currently running.\n\n");
try { process.kill( pid, 'SIGTERM' ); }
catch (err) {
die("\nError: Failed to stop process: " + err + "\n\n");
}
// wait for pid to actually exit
var checkExit = function() {
try { process.kill(pid, 0); }
catch (e) { process.exit(0); }
setTimeout( checkExit, 250 );
}
checkExit();
}
else if (args.plugin || (args.other && (args.other[0] == 'plugin') && args.other[1])) {
// execute plugin
var plugin_name = Path.basename(args.plugin || args.other[1]);
var plugin_file = Path.resolve( __dirname, Path.join( 'plugins', plugin_name + '.js' ) );
if (!fs.existsSync(plugin_file)) die("\nError: Unknown plugin: " + plugin_name + "\n\n");
process.title = plugin_name + '.js';
require(plugin_file);
}
else {
// normal startup
process.chdir( __dirname );
if (!fs.existsSync(config_file)) {
// create sample config file if needed (user may have skipped the install step)
Tools.writeFileAtomicSync( config_file, JSON.stringify( sample_config, null, "\t" ), { mode: 0o600, flush: true } );
}
// map XYSAT_ env vars to SATELLITE_, for convenience
for (var key in process.env) {
if (key.match(/^XYSAT_(.+)$/)) process.env[ 'SATELLITE_' + RegExp.$1 ] = process.env[key];
}
// merge CLI into config file and save it
delete args.start;
delete args.other;
if (Tools.numKeys(args) && !args.debug && !args.echo) {
var temp_config = Tools.mergeHashes( JSON.parse( fs.readFileSync( config_file, 'utf8' ) ), args );
Tools.writeFileAtomicSync( config_file, JSON.stringify(temp_config, null, "\t") + "\n", { mode: 0o600, flush: true } );
}
// start server
var server = new PixlServer({
__name: 'Satellite',
__version: pkg.version,
configFile: config_file,
components: [
require('./lib/engine.js')
]
});
server.startup( function() {
// server startup complete
process.title = "xyOps Satellite";
if (server.config.get('auth_token')) {
server.logDebug(3, "Authentication method: auth_token");
}
else if (server.config.get('secret_key')) {
server.logDebug(3, "Authentication method: secret_key");
}
else {
server.logDebug(1, "ERROR: Both auth_token and secret_key are missing from config. Shutting down.");
server.shutdown();
}
} );
// process.once('SIGINT', function() {
// // Note: Doesn't pixl-server take care of this? Why are we hooking SIGINT in main.js?
// // Ohhhh did this have something to do with the ptty lib?
// server.shutdown();
// });
}