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
211 lines (191 loc) · 8.46 KB
/
Copy pathcli.ts
File metadata and controls
211 lines (191 loc) · 8.46 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
#!/usr/bin/env node
// npm link --force
// npm i npm install --global --production windows-build-tools
import * as fs from "fs";
import { Config } from "./Config";
import { logger, StopService, StartService, RemoveService, InstallService, RunService, loadenv, envfilename, envfilepathname, servicename, isOpenFlow } from "./nodeclient/cliutil";
import { WebSocketClient, SigninMessage, Message, NoderedUtil } from "openflow-api";
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) {
//console.log(name, net);
console.log(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;
let parsedFile = envfile.parse(fs.readFileSync(envfilepathname));
if (parsedFile.jwt == null || parsedFile.jwt == "") {
if (options.authenticate != true) logger.warn(envfilename + " is missing a jwt, switching to --authenticate")
options.authenticate = true;
}
}
} catch (error) {
console.error(error);
printusage();
process.exit();
}
const unhandledRejection = require("unhandled-rejection");
let rejectionEmitter = unhandledRejection({
timeout: 20
});
rejectionEmitter.on("unhandledRejection", (error, promise) => {
logger.error('Unhandled Rejection at: Promise', promise, 'reason:', error);
logger.error(error.stack);
});
rejectionEmitter.on("rejectionHandled", (error, promise) => {
logger.error('Rejection handled at: Promise', promise, 'reason:', error);
logger.error(error.stack);
})
function getToken(): Promise<string> {
return new Promise<string>(async (resolve, reject) => {
logger.info("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, null, true);
logger.info("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.error(closemsg);
socket.close(1000, closemsg);
reject(closemsg);
socket = null;
}
});
});
}
async function doit() {
if (options.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)) {
console.log("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 {
console.log("Skipping " + filename + " already exists.");
}
}
}
} else if (options.authenticate == true) {
StopService(servicename);
RemoveService(servicename);
try {
logger.info("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));
}
loadenv();
InstallService(servicename, envfilepathname);
logger.info("Quit");
} catch (error) {
logger.error(error);
}
} else if (options.install == true) {
loadenv();
InstallService(servicename, envfilepathname);
} else if (options.uninstall == true) {
StopService(servicename);
RemoveService(servicename);
} else if (options.start == true) {
loadenv();
StartService(servicename);
} else if (options.stop == true) {
StopService(servicename);
} else if (options.restart == true) {
StopService(servicename);
loadenv();
StartService(servicename);
} else if (options.run == true) {
loadenv();
logger.info("Starting as service " + servicename);
RunService(null);
let index = path.join(__dirname, "/index.js");
if (!fs.existsSync(index)) {
index = path.join(__dirname, "dist", "/index.js");
}
logger.info("run: " + index);
require(index);
} else {
printusage();
}
}
function printusage() {
if (!isOpenFlow()) {
console.log("openflow-nodered-cli [--init][--install][--uninstall][--config][--start][--stop] name");
console.log(" --init - Create sample environment files for running nodered");
console.log(" --install - Install openflow as an service that runs at boot");
console.log(" --uninstall - Uninstalls service, if openflow has been installed as an service");
console.log(" --config - Prompt for credentials and create config");
console.log(" --start - Will start the service with the given name");
console.log(" --stop - Will stop the service with the given name");
console.log(" name - Service and instance name");
console.log("Will look for an envoriment file called name.env and copy that to the");
console.log("source directory");
return;
}
console.log("openflow-cli [--init][--install][--uninstall][--start][--stop] name");
console.log(" --init - Create a sample environment file for running openflow");
console.log(" --install - Install openflow as an service that runs at boot");
console.log(" --uninstall - Uninstalls service, if openflow has been installed as an service");
console.log(" --start - Will start the service with the given name");
console.log(" --stop - Will stop the service with the given name");
console.log(" name - Service and instance name");
console.log("Will look for an envoriment file called name.env and copy that to the");
console.log("source directory");
}
doit();