forked from openiap/opencore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
256 lines (239 loc) · 11.2 KB
/
Copy pathcli.ts
File metadata and controls
256 lines (239 loc) · 11.2 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
#!/usr/bin/env node
// npm link --force
// npm i npm install --global --production windows-build-tools
import * as fs from "fs";
import { Logger } from './Logger';
Logger.configure(true, true);
Logger.enabled["cli"] = 7
Logger.enabled["cliutil"] = 7
import { Config } from "./Config";
import { logger, loadenv, envfilename, envfilepathname, servicename, isOpenFlow } from "./nodeclient/cliutil";
import { WebSocketClient, NoderedUtil } from "@openiap/openflow-api";
import { pm2stop, pm2delete, pm2start, pm2restart, pm2disconnect, pm2dump, pm2startup, pm2exists } from "./nodeclient/pm2util";
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'authenticate', alias: 'a', type: Boolean },
{ name: 'init', type: Boolean },
{ name: 'install', alias: 'i', type: Boolean },
{ name: 'uninstall', alias: 'u', type: Boolean },
{ name: 'start', type: Boolean },
{ name: 'restart', type: Boolean },
{ name: 'stop', type: Boolean },
{ name: 'run', type: Boolean },
{ name: 'name', type: String, defaultOption: true },
{ name: 'config', type: String },
{ name: 'inspect', type: String },
{ name: 'networks', type: Boolean }
]
const commandLineArgs = require('command-line-args');
const path = require('path');
const readlineSync = require('readline-sync');
const envfile = require('envfile')
const { networkInterfaces } = require('os');
let options = null;
try {
options = commandLineArgs(optionDefinitions);
if (!options.init) {
if (options.networks) {
const nets = networkInterfaces();
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
if (net.family === 'IPv4' && !net.internal) {
Logger.instanse.info("cli", "", name + " " + net.address);
}
}
}
process.exit();
}
if (options.name == null || options.name == "") throw new Error("Name is mandatory");
if (options.name.endsWith(".env")) options.name = options.name.substring(0, options.name.length - 4);
(servicename as any) = options.name;
(envfilename as any) = options.name + ".env";
(envfilepathname as any) = path.join(process.cwd(), envfilename);
if (options.config != null && options.config != "") (envfilepathname as any) = options.config;
if (!isOpenFlow()) {
let parsedFile = envfile.parse(fs.readFileSync(envfilepathname));
if (parsedFile.jwt == null || parsedFile.jwt == "") {
if (options.authenticate != true) Logger.instanse.warn("cli", "", envfilename + " is missing a jwt, switching to --authenticate")
options.authenticate = true;
}
}
}
} catch (error) {
Logger.instanse.error("cli", "", error.message ? error.message : error);
printusage();
process.exit();
}
function getToken(): Promise<string> {
return new Promise<string>(async (resolve, reject) => {
Logger.instanse.info("cli", "", "wsurl " + Config.api_ws_url);
let socket: WebSocketClient = new WebSocketClient(logger, Config.api_ws_url);
socket.agent = "nodered-cli";
socket.version = Config.version;
socket.events.on("onopen", async () => {
try {
const username: string = readlineSync.question('username? ');
const password: string = readlineSync.question('password? ', { hideEchoBack: true });
const result = await NoderedUtil.SigninWithUsername({ username, password, longtoken: true });
Logger.instanse.info("cli", "", "signed in as " + result.user.name + " with id " + result.user._id);
WebSocketClient.instance.user = result.user;
WebSocketClient.instance.jwt = result.jwt;
socket.close(1000, "Close by user");
resolve(result.jwt);
socket = null;
} catch (error) {
let closemsg: any = (error.message ? error.message : error);
Logger.instanse.error("cli", "", error);
socket.close(1000, closemsg);
reject(closemsg);
socket = null;
}
});
});
}
async function doit() {
try {
if (options.init) {
Logger.instanse.info("cli", "", "init");
const files = fs.readdirSync(path.join(__dirname, ".."))
for (let i = 0; i < files.length; i++) {
let filename = files[i];
if (path.extname(filename) == '.env') {
const target = path.join(process.cwd(), filename);
if (!fs.existsSync(target)) {
Logger.instanse.info("cli", "", "Creating " + filename);
filename = path.join(__dirname, "..", filename);
fs.copyFileSync(filename, target);
let parsedFile = envfile.parse(fs.readFileSync(target));
parsedFile.logpath = process.cwd();
fs.writeFileSync(target, envfile.stringify(parsedFile));
} else {
Logger.instanse.info("cli", "", "Skipping " + filename + " already exists.");
}
}
}
} else if (options.authenticate == true) {
Logger.instanse.info("cli", "", "authenticate");
if (await pm2exists(servicename)) {
await pm2stop(servicename);
await pm2delete(servicename);
}
try {
Logger.instanse.info("cli", "", "isOpenFlow: " + isOpenFlow());
if (!isOpenFlow()) {
loadenv();
let jwt = await getToken();
let parsedFile = envfile.parse(fs.readFileSync(envfilepathname));
parsedFile.jwt = jwt;
fs.writeFileSync(envfilepathname, envfile.stringify(parsedFile));
WebSocketClient.instance.close(1000, "done");
}
loadenv();
await pm2start({
name: servicename,
script: __filename,
args: [servicename, "--run", "--config", envfilepathname]
});
Logger.instanse.info("cli", "", "Quit");
pm2disconnect();
} catch (error) {
Logger.instanse.error("cli", "", error);
}
} else if (options.install == true) {
Logger.instanse.info("cli", "", "install");
loadenv();
if (!await pm2exists(servicename)) {
await pm2start({
name: servicename,
script: __filename,
args: [servicename, "--run", "--config", envfilepathname]
});
if (process.platform == "linux") {
try {
await pm2startup("systemd");
} catch (error) {
Logger.instanse.error("cli", "", error);
}
}
else if (process.platform != "win32") {
try {
await pm2startup(process.platform as any);
} catch (error) {
Logger.instanse.error("cli", "", error);
}
}
await pm2dump();
} else {
await pm2restart(servicename);
}
pm2disconnect();
} else if (options.uninstall == true) {
Logger.instanse.info("cli", "", "uninstall");
if (await pm2exists(servicename)) {
await pm2stop(servicename);
await pm2delete(servicename);
await pm2dump();
} else {
Logger.instanse.error("cli", "", servicename + " not found");
}
pm2disconnect();
} else if (options.start == true) {
Logger.instanse.info("cli", "", "start");
loadenv();
await pm2restart(servicename);
pm2disconnect();
} else if (options.stop == true) {
Logger.instanse.info("cli", "", "stop");
await pm2stop(servicename);
pm2disconnect();
} else if (options.restart == true) {
Logger.instanse.info("cli", "", "restart");
await pm2restart(servicename);
pm2disconnect();
} else if (options.run == true) {
pm2disconnect();
Logger.instanse.info("cli", "", "run");
loadenv();
Logger.instanse.info("cli", "", "Starting as service " + servicename);
let index = path.join(__dirname, "/index.js");
if (!fs.existsSync(index)) {
index = path.join(__dirname, "dist", "/index.js");
}
Logger.instanse.info("cli", "", "run: " + index);
require(index);
} else {
Logger.instanse.info("cli", "", "unknown, print usage");
printusage();
}
} catch (error) {
Logger.instanse.error("cli", "", error);
process.exit();
}
}
function printusage() {
if (!isOpenFlow()) {
Logger.instanse.info("cli", "", "openflow-nodered-cli [--init][--install][--uninstall][--config][--start][--stop] name");
Logger.instanse.info("cli", "", " --init - Create sample environment files for running nodered");
Logger.instanse.info("cli", "", " --install - Install openflow as an service that runs at boot");
Logger.instanse.info("cli", "", " --uninstall - Uninstalls service, if openflow has been installed as an service");
Logger.instanse.info("cli", "", " --config - Prompt for credentials and create config");
Logger.instanse.info("cli", "", " --start - Will start the service with the given name");
Logger.instanse.info("cli", "", " --stop - Will stop the service with the given name");
Logger.instanse.info("cli", "", " name - Service and instance name");
Logger.instanse.info("cli", "", "Will look for an envoriment file called name.env and copy that to the");
Logger.instanse.info("cli", "", "source directory");
return;
}
Logger.instanse.info("cli", "", "openflow-cli [--init][--install][--uninstall][--start][--stop] name");
Logger.instanse.info("cli", "", " --init - Create a sample environment file for running openflow");
Logger.instanse.info("cli", "", " --install - Install openflow as an service that runs at boot");
Logger.instanse.info("cli", "", " --uninstall - Uninstalls service, if openflow has been installed as an service");
Logger.instanse.info("cli", "", " --start - Will start the service with the given name");
Logger.instanse.info("cli", "", " --stop - Will stop the service with the given name");
Logger.instanse.info("cli", "", " name - Service and instance name");
Logger.instanse.info("cli", "", "Will look for an envoriment file called name.env and copy that to the");
Logger.instanse.info("cli", "", "source directory");
}
doit();
// node C:\code\openflow\OpenFlowNodeRED\dist\cli.js --install noderedlocal