-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightning-rod.js
422 lines (268 loc) · 10.5 KB
/
lightning-rod.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
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* Copyright (c) 2014 2015 2016 Dario Bruneo, Francesco Longo, Andrea Rocco Lotronto, Arthur Warnier, Nicola Peditto, Fabio Verboso
*/
fs = require('fs');
path = require('path');
function checkSettings(callback){
try{
var check_response = null;
//Loading configuration file
nconf = require('nconf');
nconf.file ({file: 'settings.json'});
//main logging configuration
log4js = require('log4js');
log4js.loadAppender('file');
logfile = nconf.get('config:log:logfile');
log4js.addAppender(log4js.appenders.file(logfile));
//service logging configuration: "main"
logger = log4js.getLogger('main');
logger.info('##############################');
logger.info(' Stack4Things Lightning-rod');
logger.info('##############################');
// LOGGING CONFIGURATION --------------------------------------------------------------------
loglevel = nconf.get('config:log:loglevel');
/*
OFF nothing is logged
FATAL fatal errors are logged
ERROR errors are logged
WARN warnings are logged
INFO infos are logged
DEBUG debug infos are logged
TRACE traces are logged
ALL everything is logged
*/
if (loglevel === undefined){
logger.setLevel('INFO');
logger.warn('[SYSTEM] - LOG LEVEL not defined... default has been set: INFO');
}else if (loglevel === ""){
logger.setLevel('INFO');
logger.warn('[SYSTEM] - LOG LEVEL not specified... default has been set: INFO');
}else{
logger.setLevel(loglevel);
}
logger.info('[SYSTEM] - LOG LEVEL: ' + loglevel);
//------------------------------------------------------------------------------------------
// NODE ANALYSIS
uuid = nconf.get('config:node:uuid');
token = nconf.get('config:node:token');
if ( uuid == undefined || uuid == ""){
logger.debug('[SYSTEM] - Board uuid undefined or not specified! - uuid value: ' + uuid);
if (token == undefined || token == ""){
logger.error('[SYSTEM] - Board to be registered without token!');
check_response = false;
process.exit();
}
else{
logger.info('[SYSTEM] - Board to be registered with token ' + token);
check_response = true;
registration = true;
}
}else {
logger.info('[SYSTEM] - Board registered with parameters:');
logger.info('[SYSTEM] ...uuid -> ' + uuid);
if (token != "") logger.info('[SYSTEM] ...token -> ' + token);
}
// IOTRONIC ANALYSIS
var iotronic_cfg_list = ['registration-agent', 'command-agent'];
var agent_cfg_list = ['url', 'realm', 'port'];
logger.debug('[SYSTEM] - Iotronic parameters:');
iotronic_cfg_list.forEach(function(iotronic_param) {
if ( (registration === true && iotronic_param === 'registration-agent') || (registration === false && iotronic_param === 'command-agent') ){
logger.debug('[SYSTEM] ...'+iotronic_param+' analysing...');
agent_cfg_list.forEach(function(agent_param) {
//logger.debug('[SYSTEM] ......'+agent_param+' analysing...');
try{
value = nconf.get('config:iotronic:'+iotronic_param+':'+agent_param);
if (value === undefined){
logger.warn('[SYSTEM] ......'+agent_param+' not defined!');
check_response = false;
}else if (value === ""){
logger.warn('[SYSTEM] ......'+agent_param+' not specified!');
check_response = false;
}else{
logger.debug('[SYSTEM] ......'+agent_param+' -> '+ value);
if(check_response != false) check_response = true;
if(registration === false) registration = true;
}
}
catch(err){
logger.error('[SYSTEM] - Error in parsing settings.json: '+ err);
check_response = false;
}
});
}
});
callback(check_response);
}
catch(err){
// DEFAULT LOGGING
log4js = require('log4js');
log4js.loadAppender('file');
logfile = './s4t-lightning-rod.log';
log4js.addAppender(log4js.appenders.file(logfile));
//service logging configuration: "main"
logger = log4js.getLogger('main');
logger.error('[SYSTEM] - '+ err);
process.exit();
}
}
var cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
if (code==3) cluster.fork();
});
}
if (cluster.isWorker) {
// GLOBAL VARIABLES
token = null; //Used only for the registration process
autobahn = null;
uuid = null; //Used after the registration
logger = null;
registration = false; //By default set to false; It will be set at true only during the registration process...after that it will come back to be false.
checkSettings(function(check){
if(check === true){
autobahn = require('autobahn');
uuid = nconf.get('config:node:uuid');
if (!uuid) {
// FIRST REGISTRATION
logger.info('[SYSTEM] - First registration on the cloud!')
token = nconf.get('config:node:token');
url=nconf.get('config:iotronic:registration-agent:url');
port=nconf.get('config:iotronic:registration-agent:port');
realm=nconf.get('config:iotronic:registration-agent:realm');
create_wamp_connection(url,port,realm, function(wampConnection){
wampConnection.open();
});
}
else {
logger.info('[SYSTEM] - Board UUID: ' + uuid);
url=nconf.get('config:iotronic:command-agent:url');
port=nconf.get('config:iotronic:command-agent:port');
realm=nconf.get('config:iotronic:command-agent:realm');
create_wamp_connection(url,port,realm, function(wampConnection){
wampConnection.open();
});
}
}else{
logger.error('[SYSTEM] - Wrong configuration, check setting.json!\n')
}
});
}
///////////////////////////////////////////////////////////////////////////////////
function create_wamp_connection(url,port,wampRealm,cb){
var wampUrl = url+":"+port+"/ws";
if (token != null && uuid === undefined)
logger.info("[SYSTEM] - Registration token: "+token+' for connectiong to '+wampUrl);
wampConnection = new autobahn.Connection({
url: wampUrl,
realm: wampRealm
});
wampConnection.onopen = function (session, details) {
logger.info('[WAMP] - Connection to WAMP server '+ url +':'+port+' created successfully!');
logger.info('[WAMP] - Connected to realm '+ wampRealm);
logger.info('[WAMP] - Session ID: '+ session._id);
logger.debug('[WAMP] - Connection details:\n'+ JSON.stringify(details));
manage_WAMP_connection(session, details);
};
//This function is called if there are problems with the WAMP connection
wampConnection.onclose = function (reason, details) {
logger.error('[WAMP] - Error in connecting to WAMP server!');
logger.error(' - Reason: ' + reason);
logger.error(' - Reconnection Details: ');
logger.error(' - retry_delay:', details.retry_delay);
logger.error(' - retry_count:', details.retry_count);
logger.error(' - will_retry:', details.will_retry);
if(wampConnection.isOpen){logger.info("WAMP: connection is open!");}
else{logger.warn("[WAMP] - connection is closed!");}
if(session.isOpen){logger.info("WAMP: session is open!");}
else{logger.warn("[WAMP] - session is closed!");}
};
cb(wampConnection);
}
function manage_WAMP_connection (session, details){
//Registering the board to the Cloud by sending a message to the connection topic
if (!uuid){
session.call('stack4things.register', [token, session._id]).then(
function (response) {
res=JSON.parse(response);
logger.debug("Received config:"+JSON.stringify(res.config));
res.config.forEach(function(cfg) {
logger.debug("Received config:"+JSON.stringify(cfg));
change_config(cfg.action, cfg.position, cfg.value);
});
save_config(true);
},
function (error) {
logger.error("Registration failed:", error);
//BACKOFF EXP
}
);
}
else {
session.call('stack4things.register_uuid', [uuid, session._id]).then(
function (response) {
logger.info("Registered on Iotronic command wamp router");
},
function (error) {
logger.error("Registration failed:", error);
process.exit();
}
);
//register callback
session.register('stack4things.'+uuid+'.configure', configure_node).then(
function(result){
logger.debug('[WAMP] - Registered '+'stack4things.'+uuid+'.configure');
}
);
var manageModules = require('./manage-modules');
manageModules.moduleLoader(session);
}
};
function configure_node(response){
res=JSON.parse(response);
logger.debug("Received new config:"+JSON.stringify(res.config));
res.config.forEach(function(cfg) {
logger.debug("Received config:"+cfg);
change_config(cfg.action, cfg.position, cfg.value);
});
save_config(true);
return {'result':0}
}
function change_config(action,configuration,value){
switch(action) {
case 'remove':
logger.info("Removing "+configuration+" with value "+value);
nconf.clear(configuration);
break;
case 'add':
logger.info("Adding "+configuration+" with value "+value);
nconf.set(configuration, value);
break;
case 'modify':
logger.info("Modifing "+configuration+" with value "+value);
nconf.set(configuration, value);
break;
case 'clear':
logger.info("Clearing configuration");
nconf.set('config', value);
break;
}
}
function save_config(reboot){
nconf.save(function (err) {
if (err) {
logger.error(err.message);
return;
}
logger.debug('Configuration saved successfully.');
if (reboot){
logger.info('Rebooting...');
process.exit(3);
}
});
}