-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlrsConfigWatcher.js
More file actions
112 lines (100 loc) · 2.81 KB
/
lrsConfigWatcher.js
File metadata and controls
112 lines (100 loc) · 2.81 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
// [Use Strict JS]
"use strict";
// [Requires]
// Node.js Modules
var fs = require('fs')
, http = require('http')
, timers = require('timers')
, events = require('events')
, util = require('util')
, mgmtRest = require('lrsManagementRest');
function ConfigWatcher() {
this.mgmt = new mgmtRest.Client();
this.intervalMs = 5000.00 // 5 second default timer, just in case
}
util.inherits(ConfigWatcher, events.EventEmitter);
ConfigWatcher.prototype.start = function(options) {
var self = this;
var mgmt = self.mgmt;
function watchFileByName(path, cb) {
fs.watchFile(path,
{ persistent: true, interval: 1 },
function(event, file) {
process.nextTick(cb);
});
}
function pollForRunningConfigChange(mgmt, cb) {
var path = '/status/system/config/modified';
mgmt.getJSON(path,
function(resp) {
if(resp.statusCode != 200) {
self.emit(new
Error("Could not get config status: " +
resp.statusCode));
}
var jsonObj = "";
resp.on('data',
function(data) {
jsonObj += data;
});
resp.on('end', function() {
process.nextTick(function() {
cb(JSON.parse(jsonObj)[path]);
});
});
});
}
function watchForRunningConfigChange(mgmt, cb) {
var oldModified = 0;
function myCb(interval) {
pollForRunningConfigChange(mgmt,
function(modified) {
if(modified.data && !oldModified) {
process.nextTick(cb);
}
oldModified = modified.data;
});
}
myCb(undefined);
timers.setInterval(myCb, self.intervalMs);
}
function startWatch(mgmt) {
watchFileByName('/home/linerate/data/startup-config',
function() {
self.emit('startup-config-changed');
});
watchForRunningConfigChange(self.mgmt,
function() {
self.emit('running-config-modified');
});
}
var safeOpts = options || {};
var localOptions = {
host : safeOpts.host || '127.0.0.1',
port : safeOpts.port || 3001,
path : safeOpts.path || '/login',
username : safeOpts.username,
password : safeOpts.password,
interval : safeOpts.interval || 5
};
self.intervalMs = localOptions.interval * 1000;
mgmt.on('error', function(err) { self.emit('error', err); });
mgmt.on('loginFailure',
function(loginResponse, body) {
var err = new Error("Could not login: " +
loginResponse.statusCode);
err.body = body;
self.emit('error', err);
});
mgmt.on('loginRequestFailure',
function(error) {
self.emit('error',
new Error("Unable to connect to rest server: " +
error));
});
mgmt.on('login', function() {
startWatch(mgmt);
});
mgmt.logIn(localOptions);
}
exports.ConfigWatcher = ConfigWatcher