forked from FlowFuse/device-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·156 lines (138 loc) · 5 KB
/
index.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
#!/usr/bin/env node
const semver = require('semver')
if (semver.lt(process.version, '14.0.0')) {
console.log('FlowForge Device Agent requires at least NodeJS v14.x')
process.exit(1)
}
const TESTING = process.env.NODE_ENV === 'test'
const commandLineArgs = require('command-line-args')
const { info } = require('./lib/log')
const path = require('path')
const fs = require('fs')
const { AgentManager } = require('./lib/AgentManager')
const { WebServer } = require('./frontend/server')
const ConfigLoader = require('./lib/config')
const webServer = new WebServer()
function main (testOptions) {
let options
try {
options = commandLineArgs(require('./lib/cli/args'), { camelCase: true })
options = options._all
} catch (err) {
console.log(err.toString())
console.log('Run with -h for help')
quit()
}
if (options.version) {
console.log(require('./package.json').version)
quit()
}
if (options.help) {
console.log(require('./lib/cli/usage').usage())
quit()
}
if (!path.isAbsolute(options.dir)) {
options.dir = path.join(process.cwd(), options.dir)
}
// Require dir to be created
if (!fs.existsSync(options.dir)) {
const quitMsg = `Cannot find dir '${options.dir}'.
Please ensure it exists and is writable, or set a different path with -d`
quit(quitMsg, 20) // Exit Code 20 - Invalid dir
// REF: https://slg.ddnss.de/list-of-common-exit-codes-for-gnu-linux/
}
// Locate the config file. Either the path exactly as specified,
// or relative to dir
let configFound = false
const deviceFile1 = options.config || 'device.yaml'
const deviceFile2 = path.join(options.dir, deviceFile1)
if (fs.existsSync(deviceFile1)) {
configFound = true
options.deviceFile = deviceFile1
} else if (fs.existsSync(deviceFile2)) {
configFound = true
options.deviceFile = deviceFile2
}
// If the config file is not found, set the `deviceFile` to the default value
// ready for when the config file is created.
if (!configFound) {
options.deviceFile = deviceFile2 // deviceFile2 is the default value
}
delete options.config
AgentManager.init(options)
info('FlowForge Device Agent')
info('----------------------')
if (options.ui) {
info('Starting Web UI')
if (!options.uiUser || !options.uiPass) {
quit('Web UI cannot run without a username and password. These are set via with --ui-user and --ui-pass', 2)
}
const uiRuntime = Number(options.uiRuntime)
if (isNaN(uiRuntime) || uiRuntime === Infinity || uiRuntime < 0) {
quit('Web UI runtime must be 0 or greater', 2)
}
const opts = {
port: options.uiPort || 1879,
host: options.uiHost || '0.0.0.0',
credentials: {
username: options.uiUser,
password: options.uiPass
},
runtime: uiRuntime,
dir: options.dir,
config: options.config,
deviceFile: options.deviceFile
}
webServer.initialize(AgentManager, opts)
webServer.start().then().catch((err) => {
info(`Web UI failed to start: ${err.message}`)
})
}
process.on('SIGINT', closeAgentAndQuit)
process.on('SIGTERM', closeAgentAndQuit)
process.on('SIGQUIT', closeAgentAndQuit)
const parsedConfig = configFound && (ConfigLoader.parseDeviceConfigFile(options.deviceFile) || { valid: false })
const isValidDeviceConfig = !!parsedConfig.valid
if (isValidDeviceConfig) {
AgentManager.startAgent()
} else if (configFound && options.ui === true) {
info(`Invalid config file '${options.deviceFile}'.`)
} else if (!configFound && options.ui === true) {
info(`No config file found at '${deviceFile1}' or '${deviceFile2}'`)
} else {
if (configFound) {
quit(`Invalid config file '${options.deviceFile}': ${parsedConfig?.message || 'Unknown error'}'.`, 9) // Exit Code 9 - Invalid config file
} else {
quit(`No config file found at '${deviceFile1}' or '${deviceFile2}'`, 2) // No such file or directory
}
}
function quit (msg, errCode = 0) {
if (msg) { console.log(msg) }
if (TESTING) {
// don't exit if we are testing. Instead, call the onExit callback stub
if (testOptions?.onExit) {
testOptions.onExit(msg, errCode)
}
} else {
process.exit(errCode)
}
}
async function closeAgentAndQuit (msg, errCode = 0) {
if (AgentManager) { await AgentManager.close() }
quit(msg, errCode)
}
if (TESTING) {
return {
AgentManager,
webServer,
options
}
}
return null
}
// if we are testing, export the main function so we can call it directly, otherwise call it now
if (TESTING) {
module.exports = { main }
} else {
main()
}