components manager still not done...

This commit is contained in:
Dominic Bosch 2014-03-27 11:41:30 +01:00
parent 512878274c
commit 44b9a1057e
18 changed files with 1192 additions and 1067 deletions

View file

@ -58,18 +58,24 @@ exports.addListener = ( evt, eh ) =>
@ee.emit 'init', rule for id, rule of obj
# cb ( obj ) where obj should contain at least the HTTP response code and a message
exports.processRequest = ( user, obj, cb ) =>
console.log obj
# callback ( answ ) where answ is an object and contains at least the HTTP response code and a message
# obj has a command parameter and an optional payload which is a stringified JSON object
exports.processRequest = ( user, obj, callback ) =>
if commandFunctions[obj.command]
answ = commandFunctions[obj.command] user, obj.payload, cb
try
oPayload = JSON.parse obj.payload
commandFunctions[obj.command] user, oPayload, callback
catch err
callback
code: 400
message: 'Nice try...'
else
cb
callback
code: 404
message: 'Strange request!'
message: 'What do you want from me?'
commandFunctions =
forge_event_poller: ( user, obj, cb ) =>
forge_event_poller: ( user, obj, callback ) =>
answ =
code: 200
if not obj.id or not obj.params
@ -94,9 +100,9 @@ commandFunctions =
db.eventPollers.storeModule obj.id, user.username, obj
if obj.public is 'true'
db.eventPollers.publish obj.id
cb answ
callback answ
get_event_pollers: ( user, obj, cb ) ->
get_event_pollers: ( user, obj, callback ) ->
db.eventPollers.getAvailableModuleIds user.username, ( err, obj ) ->
oRes = {}
sem = obj.length
@ -104,18 +110,18 @@ commandFunctions =
db.eventPollers.getModule id, ( err, obj ) ->
oRes[id] = obj.events
if --sem is 0
cb
callback
code: 200
message: oRes
fGetEvents id for id in obj
get_event_poller_params: ( user, obj, cb ) ->
get_event_poller_params: ( user, obj, callback ) ->
db.eventPollers.getModuleParams obj.id, ( err, obj ) ->
cb
callback
code: 200
message: obj
get_action_invokers: ( user, obj, cb ) ->
get_action_invokers: ( user, obj, callback ) ->
db.actionInvokers.getAvailableModuleIds user.username, ( err, obj ) ->
oRes = {}
sem = obj.length
@ -123,18 +129,18 @@ commandFunctions =
db.actionInvokers.getModule id, ( err, obj ) ->
oRes[id] = obj.actions
if --sem is 0
cb
callback
code: 200
message: oRes
fGetActions id for id in obj
get_action_invoker_params: ( user, obj, cb ) ->
get_action_invoker_params: ( user, obj, callback ) ->
db.actionInvokers.getModuleParams obj.id, ( err, obj ) ->
cb
callback
code: 200
message: obj
forge_action_invoker: ( user, obj, cb ) =>
forge_action_invoker: ( user, obj, callback ) =>
answ =
code: 200
@ -161,9 +167,9 @@ commandFunctions =
db.actionInvokers.storeModule obj.id, user.username, obj
if obj.public is 'true'
db.actionInvokers.publish obj.id
cb answ
callback answ
get_rules: ( user, obj, cb ) ->
get_rules: ( user, obj, callback ) ->
console.log 'CM | Implement get_rules'
# A rule needs to be in following format:
@ -171,19 +177,20 @@ commandFunctions =
# - event
# - conditions
# - actions
forge_rule: ( user, obj, cb ) =>
db.getRule obj.id, ( err, oExisting ) =>
try
if oExisting isnt null
answ =
code: 409
message: 'Rule name already existing!'
else
if not obj.id or not obj.event or
not obj.conditions or not obj.actions
forge_rule: ( user, obj, callback ) =>
obj = JSON.parse obj
if not obj.id or not obj.event or
not obj.conditions or not obj.actions
answ =
code: 400
message: 'Missing properties in rule!'
else
db.getRule obj.id, ( err, oExisting ) =>
try
if oExisting isnt null
answ =
code: 400
message: 'Missing properties in rule!'
code: 409
message: 'Rule name already existing!'
else
rule =
id: obj.id
@ -202,9 +209,9 @@ commandFunctions =
answ =
code: 200
message: 'Rule stored and activated!'
catch err
answ =
code: 400
message: 'bad bad request...'
console.log err
cb answ
catch err
answ =
code: 400
message: 'bad bad request...'
console.log err
callback answ

View file

@ -112,7 +112,10 @@ and the engine fetches the same but modularized code from the npm repository via
this also allows us to send privately stored modules and rules encrypted to the user, which will then see it decrypted after it arrived at the browser
\subsection{Request formats}
\subsubsection{User commands}
object that has a command as string and an optional payload as a stringified JSON
\bibliography{user-manual}

View file

@ -1,4 +1,5 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
Components Manager
@ -6,12 +7,10 @@ Components Manager
> The components manager takes care of the dynamic JS modules and the rules.
> Event Poller and Action Invoker modules are loaded as strings and stored in the database,
> then compiled into node modules and rules and used in the engine and event poller.
*/
*/
(function() {
var commandFunctions, db, dynmod, events, exports, fs, path, vm,
_this = this;
var commandFunctions, db, dynmod, events, exports, fs, path, vm;
db = require('./persistence');
@ -25,22 +24,25 @@ Components Manager
events = require('events');
/*
Module call
-----------
Initializes the HTTP listener and its request handler.
@param {Object} args
*/
*/
exports = module.exports = (function(_this) {
return function(args) {
_this.log = args.logger;
_this.ee = new events.EventEmitter();
db(args);
dynmod(args);
return module.exports;
};
})(this);
exports = module.exports = function(args) {
_this.log = args.logger;
_this.ee = new events.EventEmitter();
db(args);
dynmod(args);
return module.exports;
};
/*
Add an event handler (eh) for a certain event (evt).
@ -52,77 +54,90 @@ Components Manager
@public addListener ( *evt, eh* )
@param {String} evt
@param {function} eh
*/
*/
exports.addListener = (function(_this) {
return function(evt, eh) {
_this.ee.addListener(evt, eh);
if (evt === 'init') {
return db.getRules(function(err, obj) {
var id, rule, _results;
_results = [];
for (id in obj) {
rule = obj[id];
_results.push(_this.ee.emit('init', rule));
}
return _results;
});
}
};
})(this);
exports.addListener = function(evt, eh) {
_this.ee.addListener(evt, eh);
if (evt === 'init') {
return db.getRules(function(err, obj) {
var id, rule, _results;
_results = [];
for (id in obj) {
rule = obj[id];
_results.push(_this.ee.emit('init', rule));
exports.processRequest = (function(_this) {
return function(user, obj, callback) {
var err, oPayload;
if (commandFunctions[obj.command]) {
try {
oPayload = JSON.parse(obj.payload);
return commandFunctions[obj.command](user, oPayload, callback);
} catch (_error) {
err = _error;
return callback({
code: 400,
message: 'Nice try...'
});
}
return _results;
});
}
};
exports.processRequest = function(user, obj, cb) {
var answ;
console.log(obj);
if (commandFunctions[obj.command]) {
return answ = commandFunctions[obj.command](user, obj.payload, cb);
} else {
return cb({
code: 404,
message: 'Strange request!'
});
}
};
} else {
return callback({
code: 404,
message: 'What do you want from me?'
});
}
};
})(this);
commandFunctions = {
forge_event_poller: function(user, obj, cb) {
var answ;
answ = {
code: 200
};
if (!obj.id || !obj.params) {
answ.code = 400;
return answ.message = "Your request didn't contain all necessary fields! id and params required";
} else {
db.eventPollers.getModule(obj.id, function(err, mod) {
var cm, id, name, src, _ref;
if (mod) {
answ.code = 409;
return answ.message = 'Event Poller module name already existing: ' + obj.id;
} else {
src = obj.data;
cm = dynmod.compileString(src, obj.id, {}, obj.lang);
answ = cm.answ;
if (answ.code === 200) {
events = [];
_ref = cm.module;
for (name in _ref) {
id = _ref[name];
events.push(name);
}
_this.log.info("CM | Storing new eventpoller with events " + events);
answ.message = "Event Poller module successfully stored! Found following event(s): " + events;
obj.events = JSON.stringify(events);
db.eventPollers.storeModule(obj.id, user.username, obj);
if (obj["public"] === 'true') {
return db.eventPollers.publish(obj.id);
forge_event_poller: (function(_this) {
return function(user, obj, callback) {
var answ;
answ = {
code: 200
};
if (!obj.id || !obj.params) {
answ.code = 400;
return answ.message = "Your request didn't contain all necessary fields! id and params required";
} else {
db.eventPollers.getModule(obj.id, function(err, mod) {
var cm, id, name, src, _ref;
if (mod) {
answ.code = 409;
return answ.message = 'Event Poller module name already existing: ' + obj.id;
} else {
src = obj.data;
cm = dynmod.compileString(src, obj.id, {}, obj.lang);
answ = cm.answ;
if (answ.code === 200) {
events = [];
_ref = cm.module;
for (name in _ref) {
id = _ref[name];
events.push(name);
}
_this.log.info("CM | Storing new eventpoller with events " + events);
answ.message = "Event Poller module successfully stored! Found following event(s): " + events;
obj.events = JSON.stringify(events);
db.eventPollers.storeModule(obj.id, user.username, obj);
if (obj["public"] === 'true') {
return db.eventPollers.publish(obj.id);
}
}
}
}
});
return cb(answ);
}
},
get_event_pollers: function(user, obj, cb) {
});
return callback(answ);
}
};
})(this),
get_event_pollers: function(user, obj, callback) {
return db.eventPollers.getAvailableModuleIds(user.username, function(err, obj) {
var fGetEvents, id, oRes, sem, _i, _len, _results;
oRes = {};
@ -131,7 +146,7 @@ Components Manager
return db.eventPollers.getModule(id, function(err, obj) {
oRes[id] = obj.events;
if (--sem === 0) {
return cb({
return callback({
code: 200,
message: oRes
});
@ -146,15 +161,15 @@ Components Manager
return _results;
});
},
get_event_poller_params: function(user, obj, cb) {
get_event_poller_params: function(user, obj, callback) {
return db.eventPollers.getModuleParams(obj.id, function(err, obj) {
return cb({
return callback({
code: 200,
message: obj
});
});
},
get_action_invokers: function(user, obj, cb) {
get_action_invokers: function(user, obj, callback) {
return db.actionInvokers.getAvailableModuleIds(user.username, function(err, obj) {
var fGetActions, id, oRes, sem, _i, _len, _results;
oRes = {};
@ -163,7 +178,7 @@ Components Manager
return db.actionInvokers.getModule(id, function(err, obj) {
oRes[id] = obj.actions;
if (--sem === 0) {
return cb({
return callback({
code: 200,
message: oRes
});
@ -178,107 +193,113 @@ Components Manager
return _results;
});
},
get_action_invoker_params: function(user, obj, cb) {
get_action_invoker_params: function(user, obj, callback) {
return db.actionInvokers.getModuleParams(obj.id, function(err, obj) {
return cb({
return callback({
code: 200,
message: obj
});
});
},
forge_action_invoker: function(user, obj, cb) {
var answ;
answ = {
code: 200
};
return db.actionInvokers.getModule(obj.id, function(err, mod) {
var actions, cm, id, name, src, _ref;
if (mod) {
answ.code = 409;
answ.message = 'Action Invoker module name already existing: ' + obj.id;
} else {
src = obj.data;
cm = dynmod.compileString(src, obj.id, {}, obj.lang);
answ = cm.answ;
if (answ.code === 200) {
if (!obj.id || !obj.params) {
answ.code = 400;
answ.message = "Your request didn't contain all necessary fields! id and params required";
} else {
actions = [];
_ref = cm.module;
for (name in _ref) {
id = _ref[name];
actions.push(name);
}
_this.log.info("CM | Storing new eventpoller with actions " + actions);
answ.message = "Action Invoker module successfully stored! Found following action(s): " + actions;
obj.actions = JSON.stringify(actions);
db.actionInvokers.storeModule(obj.id, user.username, obj);
if (obj["public"] === 'true') {
db.actionInvokers.publish(obj.id);
forge_action_invoker: (function(_this) {
return function(user, obj, callback) {
var answ;
answ = {
code: 200
};
return db.actionInvokers.getModule(obj.id, function(err, mod) {
var actions, cm, id, name, src, _ref;
if (mod) {
answ.code = 409;
answ.message = 'Action Invoker module name already existing: ' + obj.id;
} else {
src = obj.data;
cm = dynmod.compileString(src, obj.id, {}, obj.lang);
answ = cm.answ;
if (answ.code === 200) {
if (!obj.id || !obj.params) {
answ.code = 400;
answ.message = "Your request didn't contain all necessary fields! id and params required";
} else {
actions = [];
_ref = cm.module;
for (name in _ref) {
id = _ref[name];
actions.push(name);
}
_this.log.info("CM | Storing new eventpoller with actions " + actions);
answ.message = "Action Invoker module successfully stored! Found following action(s): " + actions;
obj.actions = JSON.stringify(actions);
db.actionInvokers.storeModule(obj.id, user.username, obj);
if (obj["public"] === 'true') {
db.actionInvokers.publish(obj.id);
}
}
}
}
}
return cb(answ);
});
},
get_rules: function(user, obj, cb) {
return callback(answ);
});
};
})(this),
get_rules: function(user, obj, callback) {
return console.log('CM | Implement get_rules');
},
forge_rule: function(user, obj, cb) {
return db.getRule(obj.id, function(err, oExisting) {
var answ, arrParams, id, params, rule, strRule;
try {
if (oExisting !== null) {
answ = {
code: 409,
message: 'Rule name already existing!'
};
} else {
if (!obj.id || !obj.event || !obj.conditions || !obj.actions) {
forge_rule: (function(_this) {
return function(user, obj, callback) {
var answ;
obj = JSON.parse(obj);
if (!obj.id || !obj.event || !obj.conditions || !obj.actions) {
return answ = {
code: 400,
message: 'Missing properties in rule!'
};
} else {
return db.getRule(obj.id, function(err, oExisting) {
var arrParams, id, params, rule, strRule;
try {
if (oExisting !== null) {
answ = {
code: 409,
message: 'Rule name already existing!'
};
} else {
rule = {
id: obj.id,
event: obj.event,
conditions: JSON.parse(obj.conditions),
actions: JSON.parse(obj.actions)
};
strRule = JSON.stringify(rule);
db.storeRule(rule.id, strRule);
db.linkRule(rule.id, user.username);
db.activateRule(rule.id, user.username);
if (obj.event_params) {
db.eventPollers.storeUserParams(ep.module, user.username, obj.event_params);
}
arrParams = JSON.parse(obj.action_params);
for (id in arrParams) {
params = arrParams[id];
db.actionInvokers.storeUserParams(id, user.username, JSON.stringify(params));
}
_this.ee.emit('newRule', strRule);
answ = {
code: 200,
message: 'Rule stored and activated!'
};
}
} catch (_error) {
err = _error;
answ = {
code: 400,
message: 'Missing properties in rule!'
};
} else {
rule = {
id: obj.id,
event: obj.event,
conditions: JSON.parse(obj.conditions),
actions: JSON.parse(obj.actions)
};
strRule = JSON.stringify(rule);
db.storeRule(rule.id, strRule);
db.linkRule(rule.id, user.username);
db.activateRule(rule.id, user.username);
if (obj.event_params) {
db.eventPollers.storeUserParams(ep.module, user.username, obj.event_params);
}
arrParams = JSON.parse(obj.action_params);
for (id in arrParams) {
params = arrParams[id];
db.actionInvokers.storeUserParams(id, user.username, JSON.stringify(params));
}
_this.ee.emit('newRule', strRule);
answ = {
code: 200,
message: 'Rule stored and activated!'
message: 'bad bad request...'
};
console.log(err);
}
}
} catch (_error) {
err = _error;
answ = {
code: 400,
message: 'bad bad request...'
};
console.log(err);
return callback(answ);
});
}
return cb(answ);
});
}
};
})(this)
};
}).call(this);

View file

@ -1,20 +1,20 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
Configuration
=============
> Loads the configuration file and acts as an interface to it.
*/
*/
(function() {
var exports, fetchProp, fs, loadConfigFile, path,
_this = this;
var exports, fetchProp, fs, loadConfigFile, path;
fs = require('fs');
path = require('path');
/*
Module call
-----------
@ -24,21 +24,23 @@ Configuration
be generated) and configPath for a custom configuration file path.
@param {Object} args
*/
*/
exports = module.exports = (function(_this) {
return function(args) {
args = args != null ? args : {};
if (args.nolog) {
_this.nolog = true;
}
if (args.configPath) {
loadConfigFile(args.configPath);
} else {
loadConfigFile(path.join('config', 'system.json'));
}
return module.exports;
};
})(this);
exports = module.exports = function(args) {
args = args != null ? args : {};
if (args.nolog) {
_this.nolog = true;
}
if (args.configPath) {
loadConfigFile(args.configPath);
} else {
loadConfigFile(path.join('config', 'system.json'));
}
return module.exports;
};
/*
Tries to load a configuration file from the path relative to this module's parent folder.
@ -46,97 +48,102 @@ Configuration
@private loadConfigFile
@param {String} configPath
*/
*/
loadConfigFile = function(configPath) {
var confProperties, e, prop, _i, _len;
_this.config = null;
confProperties = ['log', 'http-port', 'db-port'];
try {
_this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', configPath)));
_this.isReady = true;
for (_i = 0, _len = confProperties.length; _i < _len; _i++) {
prop = confProperties[_i];
if (!_this.config[prop]) {
_this.isReady = false;
loadConfigFile = (function(_this) {
return function(configPath) {
var confProperties, e, prop, _i, _len;
_this.config = null;
confProperties = ['log', 'http-port', 'db-port'];
try {
_this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', configPath)));
_this.isReady = true;
for (_i = 0, _len = confProperties.length; _i < _len; _i++) {
prop = confProperties[_i];
if (!_this.config[prop]) {
_this.isReady = false;
}
}
if (!_this.isReady && !_this.nolog) {
return console.error("Missing property in config file, requires:\n" + (" - " + (confProperties.join("\n - "))));
}
} catch (_error) {
e = _error;
_this.isReady = false;
if (!_this.nolog) {
return console.error("Failed loading config file: " + e.message);
}
}
if (!_this.isReady && !_this.nolog) {
return console.error("Missing property in config file, requires:\n" + (" - " + (confProperties.join("\n - "))));
}
} catch (_error) {
e = _error;
_this.isReady = false;
if (!_this.nolog) {
return console.error("Failed loading config file: " + e.message);
}
}
};
};
})(this);
/*
Fetch a property from the configuration
@private fetchProp( *prop* )
@param {String} prop
*/
*/
fetchProp = (function(_this) {
return function(prop) {
var _ref;
return (_ref = _this.config) != null ? _ref[prop] : void 0;
};
})(this);
fetchProp = function(prop) {
var _ref;
return (_ref = _this.config) != null ? _ref[prop] : void 0;
};
/*
***Returns*** true if the config file is ready, else false
@public isReady()
*/
*/
exports.isReady = (function(_this) {
return function() {
return _this.isReady;
};
})(this);
exports.isReady = function() {
return _this.isReady;
};
/*
***Returns*** the HTTP port
@public getHttpPort()
*/
*/
exports.getHttpPort = function() {
return fetchProp('http-port');
};
/*
***Returns*** the DB port*
@public getDBPort()
*/
*/
exports.getDbPort = function() {
return fetchProp('db-port');
};
/*
***Returns*** the log conf object
@public getLogConf()
*/
*/
exports.getLogConf = function() {
return fetchProp('log');
};
/*
***Returns*** the crypto key
@public getCryptoKey()
*/
*/
exports.getCryptoKey = function() {
return fetchProp('crypto-key');

View file

@ -1,16 +1,15 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
Dynamic Modules
===============
> Compiles CoffeeScript modules and loads JS modules in a VM, together
> with only a few allowed node.js modules.
*/
*/
(function() {
var cs, exports, needle, vm,
_this = this;
var cs, exports, needle, vm;
vm = require('vm');
@ -18,19 +17,22 @@ Dynamic Modules
cs = require('coffee-script');
/*
Module call
-----------
Initializes the dynamic module handler.
@param {Object} args
*/
*/
exports = module.exports = (function(_this) {
return function(args) {
_this.log = args.logger;
return module.exports;
};
})(this);
exports = module.exports = function(args) {
_this.log = args.logger;
return module.exports;
};
/*
Try to run a JS module from a string, together with the
@ -42,43 +44,44 @@ Dynamic Modules
@param {String} id
@param {Object} params
@param {String} lang
*/
*/
exports.compileString = function(src, id, params, lang) {
var answ, err, ret, sandbox;
answ = {
code: 200,
message: 'Successfully compiled'
};
if (lang === '0') {
exports.compileString = (function(_this) {
return function(src, id, params, lang) {
var answ, err, ret, sandbox;
answ = {
code: 200,
message: 'Successfully compiled'
};
if (lang === '0') {
try {
src = cs.compile(src);
} catch (_error) {
err = _error;
answ.code = 400;
answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line;
}
}
sandbox = {
id: id,
params: params,
needle: needle,
log: console.log,
exports: {}
};
try {
src = cs.compile(src);
vm.runInNewContext(src, sandbox, id + '.vm');
} catch (_error) {
err = _error;
answ.code = 400;
answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line;
answ.message = 'Loading Module failed: ' + err.message;
}
}
sandbox = {
id: id,
params: params,
needle: needle,
log: console.log,
exports: {}
ret = {
answ: answ,
module: sandbox.exports
};
return ret;
};
try {
vm.runInNewContext(src, sandbox, id + '.vm');
} catch (_error) {
err = _error;
answ.code = 400;
answ.message = 'Loading Module failed: ' + err.message;
}
ret = {
answ: answ,
module: sandbox.exports
};
return ret;
};
})(this);
}).call(this);

View file

@ -1,4 +1,5 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
HTTP Listener
@ -6,12 +7,10 @@ HTTP Listener
> Receives the HTTP requests to the server at the given port. The requests
> (bound to a method) are then redirected to the appropriate handler which
> takes care of the request.
*/
*/
(function() {
var app, exports, express, initRouting, path, qs, requestHandler,
_this = this;
var app, exports, express, initRouting, path, qs, requestHandler;
requestHandler = require('./request-handler');
@ -23,73 +22,77 @@ HTTP Listener
app = express();
/*
Module call
-----------
Initializes the HTTP listener and its request handler.
@param {Object} args
*/
*/
exports = module.exports = (function(_this) {
return function(args) {
_this.log = args.logger;
_this.shutDownSystem = args['shutdown-function'];
requestHandler(args);
initRouting(args['http-port']);
return module.exports;
};
})(this);
exports = module.exports = function(args) {
_this.log = args.logger;
_this.shutDownSystem = args['shutdown-function'];
requestHandler(args);
initRouting(args['http-port']);
return module.exports;
};
/*
Initializes the request routing and starts listening on the given port.
@param {int} port
@private initRouting( *fShutDown* )
*/
*/
initRouting = (function(_this) {
return function(port) {
var server, sess_sec;
app.use(express.cookieParser());
sess_sec = "149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT<Iw";
app.use(express.session({
secret: sess_sec
}));
_this.log.info('HL | no session backbone');
app.use('/', express["static"](path.resolve(__dirname, '..', 'webpages', 'public')));
app.get('/admin', requestHandler.handleAdmin);
app.get('/forge', requestHandler.handleForge);
app.post('/event', requestHandler.handleEvent);
app.post('/login', requestHandler.handleLogin);
app.post('/logout', requestHandler.handleLogout);
app.post('/usercommand', requestHandler.handleUserCommand);
app.post('/admincommand', requestHandler.handleAdminCommand);
server = app.listen(parseInt(port) || 8111);
server.on('listening', function() {
var addr;
addr = server.address();
if (addr.port !== port) {
return _this.shutDownSystem();
}
});
return server.on('error', function(err) {
initRouting = function(port) {
var server, sess_sec;
app.use(express.cookieParser());
sess_sec = "149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT<Iw";
app.use(express.session({
secret: sess_sec
}));
_this.log.info('HL | no session backbone');
app.use('/', express["static"](path.resolve(__dirname, '..', 'webpages', 'public')));
app.get('/admin', requestHandler.handleAdmin);
app.get('/forge', requestHandler.handleForge);
app.post('/event', requestHandler.handleEvent);
app.post('/login', requestHandler.handleLogin);
app.post('/logout', requestHandler.handleLogout);
app.post('/usercommand', requestHandler.handleUserCommand);
app.post('/admincommand', requestHandler.handleAdminCommand);
server = app.listen(parseInt(port) || 8111);
server.on('listening', function() {
var addr;
addr = server.address();
if (addr.port !== port) {
/*
Error handling of the express port listener requires special attention,
thus we have to catch the error, which is issued if the port is already in use.
*/
switch (err.errno) {
case 'EADDRINUSE':
_this.log.error(err, 'HL | http-port already in use, shutting down!');
break;
case 'EACCES':
_this.log.error(err, 'HL | http-port not accessible, shutting down!');
break;
default:
_this.log.error(err, 'HL | Error in server, shutting down!');
}
return _this.shutDownSystem();
}
});
return server.on('error', function(err) {
/*
Error handling of the express port listener requires special attention,
thus we have to catch the error, which is issued if the port is already in use.
*/
switch (err.errno) {
case 'EADDRINUSE':
_this.log.error(err, 'HL | http-port already in use, shutting down!');
break;
case 'EACCES':
_this.log.error(err, 'HL | http-port not accessible, shutting down!');
break;
default:
_this.log.error(err, 'HL | Error in server, shutting down!');
}
return _this.shutDownSystem();
});
};
});
};
})(this);
}).call(this);

View file

@ -1,7 +1,6 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var bunyan, fs, path,
_this = this;
var bunyan, fs, path;
fs = require('fs');
@ -9,64 +8,66 @@
bunyan = require('bunyan');
/*
Returns a bunyan logger according to the given arguments.
@public getLogger( *args* )
@param {Object} args
*/
*/
exports.getLogger = function(args) {
var e, emptylog, opt;
emptylog = {
trace: function() {},
debug: function() {},
info: function() {},
warn: function() {},
error: function() {},
fatal: function() {}
};
args = args != null ? args : {};
if (args.nolog) {
return emptylog;
} else {
try {
opt = {
name: "webapi-eca"
};
if (args['mode'] === 'development') {
opt.src = true;
}
if (args['file-path']) {
_this.logPath = path.resolve(args['file-path']);
} else {
_this.logPath = path.resolve(__dirname, '..', 'logs', 'server.log');
}
exports.getLogger = (function(_this) {
return function(args) {
var e, emptylog, opt;
emptylog = {
trace: function() {},
debug: function() {},
info: function() {},
warn: function() {},
error: function() {},
fatal: function() {}
};
args = args != null ? args : {};
if (args.nolog) {
return emptylog;
} else {
try {
fs.writeFileSync(_this.logPath + '.temp', 'temp');
fs.unlinkSync(_this.logPath + '.temp');
opt = {
name: "webapi-eca"
};
if (args['mode'] === 'development') {
opt.src = true;
}
if (args['file-path']) {
_this.logPath = path.resolve(args['file-path']);
} else {
_this.logPath = path.resolve(__dirname, '..', 'logs', 'server.log');
}
try {
fs.writeFileSync(_this.logPath + '.temp', 'temp');
fs.unlinkSync(_this.logPath + '.temp');
} catch (_error) {
e = _error;
console.error("Log folder '" + _this.logPath + "' is not writable");
return emptylog;
}
opt.streams = [
{
level: args['io-level'],
stream: process.stdout
}, {
level: args['file-level'],
path: _this.logPath
}
];
return bunyan.createLogger(opt);
} catch (_error) {
e = _error;
console.error("Log folder '" + _this.logPath + "' is not writable");
console.error(e);
return emptylog;
}
opt.streams = [
{
level: args['io-level'],
stream: process.stdout
}, {
level: args['file-level'],
path: _this.logPath
}
];
return bunyan.createLogger(opt);
} catch (_error) {
e = _error;
console.error(e);
return emptylog;
}
}
};
};
})(this);
}).call(this);

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,5 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
Request Handler
@ -7,12 +8,10 @@ Request Handler
> the [HTTP Listener](http-listener.html). It will handle user requests for
> pages as well as POST requests such as user login, module storing, event
> invocation and also admin commands.
*/
*/
(function() {
var crypto, db, dirHandlers, exports, fs, getHandlerPath, getRemoteScripts, getScript, getTemplate, mustache, path, qs, renderPage,
_this = this;
var crypto, db, dirHandlers, exports, fs, getHandlerPath, getRemoteScripts, getScript, getTemplate, mustache, path, qs, renderPage;
db = require('./persistence');
@ -28,32 +27,35 @@ Request Handler
dirHandlers = path.resolve(__dirname, '..', 'webpages', 'handlers');
exports = module.exports = function(args) {
var fStoreUser, user, users;
_this.log = args.logger;
_this.userRequestHandler = args['request-service'];
_this.objAdminCmds = {
shutdown: function(obj, cb) {
var data;
data = {
code: 200,
message: 'Shutting down... BYE!'
};
setTimeout(args['shutdown-function'], 500);
return cb(null, data);
exports = module.exports = (function(_this) {
return function(args) {
var fStoreUser, user, users;
_this.log = args.logger;
_this.userRequestHandler = args['request-service'];
_this.objAdminCmds = {
shutdown: function(obj, cb) {
var data;
data = {
code: 200,
message: 'Shutting down... BYE!'
};
setTimeout(args['shutdown-function'], 500);
return cb(null, data);
}
};
db(args);
users = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'config', 'users.json')));
fStoreUser = function(username, oUser) {
oUser.username = username;
return db.storeUser(oUser);
};
for (user in users) {
fStoreUser(user, users[user]);
}
return module.exports;
};
db(args);
users = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'config', 'users.json')));
fStoreUser = function(username, oUser) {
oUser.username = username;
return db.storeUser(oUser);
};
for (user in users) {
fStoreUser(user, users[user]);
}
return module.exports;
};
})(this);
/*
Handles possible events that were posted to this server and pushes them into the
@ -65,8 +67,7 @@ Request Handler
objects.*
@public handleEvent( *req, resp* )
*/
*/
exports.handleEvent = function(req, resp) {
var body;
@ -103,6 +104,7 @@ Request Handler
});
};
/*
Associates the user object with the session if login is successful.
@ -112,32 +114,34 @@ Request Handler
objects.*
@public handleLogin( *req, resp* )
*/
*/
exports.handleLogin = function(req, resp) {
var body;
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
obj = qs.parse(body);
return db.loginUser(obj.username, obj.password, function(err, usr) {
if (err) {
_this.log.warn("RH | AUTH-UH-OH ( " + obj.username + " ): " + err.message);
} else {
req.session.user = usr;
}
if (req.session.user) {
return resp.send('OK!');
} else {
return resp.send(401, 'NO!');
}
exports.handleLogin = (function(_this) {
return function(req, resp) {
var body;
body = '';
req.on('data', function(data) {
return body += data;
});
});
};
return req.on('end', function() {
var obj;
obj = qs.parse(body);
return db.loginUser(obj.username, obj.password, function(err, usr) {
if (err) {
_this.log.warn("RH | AUTH-UH-OH ( " + obj.username + " ): " + err.message);
} else {
req.session.user = usr;
}
if (req.session.user) {
return resp.send('OK!');
} else {
return resp.send(401, 'NO!');
}
});
});
};
})(this);
/*
A post request retrieved on this handler causes the user object to be
@ -149,8 +153,7 @@ Request Handler
objects.*
@public handleLogout( *req, resp* )
*/
*/
exports.handleLogout = function(req, resp) {
if (req.session) {
@ -159,25 +162,25 @@ Request Handler
}
};
/*
Resolves the path to a handler webpage.
@private getHandlerPath( *name* )
@param {String} name
*/
*/
getHandlerPath = function(name) {
return path.join(dirHandlers, name + '.html');
};
/*
Fetches a template.
@private getTemplate( *name* )
@param {String} name
*/
*/
getTemplate = function(name) {
var pth;
@ -185,13 +188,13 @@ Request Handler
return fs.readFileSync(pth, 'utf8');
};
/*
Fetches a script.
@private getScript( *name* )
@param {String} name
*/
*/
getScript = function(name) {
var pth;
@ -199,13 +202,13 @@ Request Handler
return fs.readFileSync(pth, 'utf8');
};
/*
Fetches remote scripts snippets.
@private getRemoteScripts( *name* )
@param {String} name
*/
*/
getRemoteScripts = function(name) {
var pth;
@ -213,6 +216,7 @@ Request Handler
return fs.readFileSync(pth, 'utf8');
};
/*
Renders a page, with helps of mustache, depending on the user session and returns it.
@ -220,8 +224,7 @@ Request Handler
@param {String} name
@param {Object} sess
@param {Object} msg
*/
*/
renderPage = function(name, req, resp, msg) {
var code, content, data, err, menubar, page, pageElements, pathSkel, remote_scripts, script, skeleton;
@ -260,6 +263,7 @@ Request Handler
return resp.send(code, mustache.render(page, data));
};
/*
Present the desired forge page to the user.
@ -269,8 +273,7 @@ Request Handler
objects.*
@public handleForge( *req, resp* )
*/
*/
exports.handleForge = function(req, resp) {
var page;
@ -281,6 +284,7 @@ Request Handler
return renderPage(page, req, resp);
};
/*
Handles the user command requests.
@ -290,27 +294,29 @@ Request Handler
objects.*
@public handleUser( *req, resp* )
*/
*/
exports.handleUserCommand = function(req, resp) {
var body;
if (req.session && req.session.user) {
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
obj = qs.parse(body);
return _this.userRequestHandler(req.session.user, obj, function(obj) {
return resp.send(obj.code, obj);
exports.handleUserCommand = (function(_this) {
return function(req, resp) {
var body;
if (req.session && req.session.user) {
body = '';
req.on('data', function(data) {
return body += data;
});
});
} else {
return resp.send(401, 'Login first!');
}
};
return req.on('end', function() {
var obj;
obj = qs.parse(body);
return _this.userRequestHandler(req.session.user, obj, function(obj) {
return resp.send(obj.code, obj);
});
});
} else {
return resp.send(401, 'Login first!');
}
};
})(this);
/*
Present the admin console to the user if he's allowed to see it.
@ -321,8 +327,7 @@ Request Handler
objects.*
@public handleForge( *req, resp* )
*/
*/
exports.handleAdmin = function(req, resp) {
var msg, page;
@ -337,6 +342,7 @@ Request Handler
return renderPage(page, req, resp, msg);
};
/*
Handles the admin command requests.
@ -346,31 +352,32 @@ Request Handler
objects.*
@public handleAdminCommand( *req, resp* )
*/
*/
exports.handleAdminCommand = function(req, resp) {
var body;
if (req.session && req.session.user && req.session.user.isAdmin === "true") {
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
obj = qs.parse(body);
_this.log.info('RH | Received admin request: ' + obj.command);
if (obj.command && _this.objAdminCmds[obj.command]) {
return _this.objAdminCmds[obj.command](obj, function(err, obj) {
return resp.send(obj.code, obj);
});
} else {
return resp.send(404, 'Command unknown!');
}
});
} else {
return resp.send(401, 'You need to be logged in as admin!');
}
};
exports.handleAdminCommand = (function(_this) {
return function(req, resp) {
var body;
if (req.session && req.session.user && req.session.user.isAdmin === "true") {
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
obj = qs.parse(body);
_this.log.info('RH | Received admin request: ' + obj.command);
if (obj.command && _this.objAdminCmds[obj.command]) {
return _this.objAdminCmds[obj.command](obj, function(err, obj) {
return resp.send(obj.code, obj);
});
} else {
return resp.send(404, 'Command unknown!');
}
});
} else {
return resp.send(401, 'You need to be logged in as admin!');
}
};
})(this);
}).call(this);

View file

@ -1,4 +1,5 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
WebAPI-ECA Engine
@ -9,12 +10,10 @@ WebAPI-ECA Engine
> node webapi-eca [opt]
>
> See below in the optimist CLI preparation for allowed optional parameters `[opt]`.
*/
*/
(function() {
var argv, cm, conf, cp, db, engine, fs, http, init, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage,
_this = this;
var argv, cm, conf, cp, db, engine, fs, http, init, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage;
logger = require('./logging');
@ -40,10 +39,10 @@ WebAPI-ECA Engine
procCmds = {};
/*
Let's prepare the optimist CLI optional arguments `[opt]`:
*/
*/
usage = 'This runs your webapi-based ECA engine';
@ -93,113 +92,117 @@ WebAPI-ECA Engine
process.exit();
}
/*
This function is invoked right after the module is loaded and starts the server.
@private init()
*/
*/
init = function() {
var args, logconf;
conf(argv.c);
if (!conf.isReady()) {
console.error('FAIL: Config file not ready! Shutting down...');
process.exit();
}
logconf = conf.getLogConf();
if (argv.m) {
logconf['mode'] = argv.m;
}
if (argv.i) {
logconf['io-level'] = argv.i;
}
if (argv.f) {
logconf['file-level'] = argv.f;
}
if (argv.p) {
logconf['file-path'] = argv.p;
}
if (argv.n) {
logconf['nolog'] = argv.n;
}
try {
fs.unlinkSync(path.resolve(__dirname, '..', 'logs', logconf['file-path']));
} catch (_error) {}
_this.log = logger.getLogger(logconf);
_this.log.info('RS | STARTING SERVER');
args = {
logger: _this.log,
logconf: logconf
};
args['http-port'] = parseInt(argv.w || conf.getHttpPort());
args['db-port'] = parseInt(argv.d || conf.getDbPort());
_this.log.info('RS | Initialzing DB');
db(args);
return db.isConnected(function(err) {
var cliArgs, poller;
if (err) {
_this.log.error('RS | No DB connection, shutting down system!');
return shutDown();
} else {
_this.log.info('RS | Initialzing engine');
engine(args);
_this.log.info('RS | Forking a child process for the event poller');
cliArgs = [args.logconf['mode'], args.logconf['io-level'], args.logconf['file-level'], args.logconf['file-path'], args.logconf['nolog']];
poller = cp.fork(path.resolve(__dirname, nameEP), cliArgs);
_this.log.info('RS | Initialzing module manager');
cm(args);
cm.addListener('init', function(evt) {
return poller.send({
event: 'init',
data: evt
});
});
cm.addListener('newRule', function(evt) {
return poller.send({
event: 'newRule',
data: evt
});
});
cm.addListener('init', function(evt) {
return engine.internalEvent('init', evt);
});
cm.addListener('newRule', function(evt) {
return engine.internalEvent('newRule', evt);
});
_this.log.info('RS | Initialzing http listener');
args['request-service'] = cm.processRequest;
args['shutdown-function'] = shutDown;
return http(args);
init = (function(_this) {
return function() {
var args, logconf;
conf(argv.c);
if (!conf.isReady()) {
console.error('FAIL: Config file not ready! Shutting down...');
process.exit();
}
});
};
logconf = conf.getLogConf();
if (argv.m) {
logconf['mode'] = argv.m;
}
if (argv.i) {
logconf['io-level'] = argv.i;
}
if (argv.f) {
logconf['file-level'] = argv.f;
}
if (argv.p) {
logconf['file-path'] = argv.p;
}
if (argv.n) {
logconf['nolog'] = argv.n;
}
try {
fs.unlinkSync(path.resolve(__dirname, '..', 'logs', logconf['file-path']));
} catch (_error) {}
_this.log = logger.getLogger(logconf);
_this.log.info('RS | STARTING SERVER');
args = {
logger: _this.log,
logconf: logconf
};
args['http-port'] = parseInt(argv.w || conf.getHttpPort());
args['db-port'] = parseInt(argv.d || conf.getDbPort());
_this.log.info('RS | Initialzing DB');
db(args);
return db.isConnected(function(err) {
var cliArgs, poller;
if (err) {
_this.log.error('RS | No DB connection, shutting down system!');
return shutDown();
} else {
_this.log.info('RS | Initialzing engine');
engine(args);
_this.log.info('RS | Forking a child process for the event poller');
cliArgs = [args.logconf['mode'], args.logconf['io-level'], args.logconf['file-level'], args.logconf['file-path'], args.logconf['nolog']];
poller = cp.fork(path.resolve(__dirname, nameEP), cliArgs);
_this.log.info('RS | Initialzing module manager');
cm(args);
cm.addListener('init', function(evt) {
return poller.send({
event: 'init',
data: evt
});
});
cm.addListener('newRule', function(evt) {
return poller.send({
event: 'newRule',
data: evt
});
});
cm.addListener('init', function(evt) {
return engine.internalEvent('init', evt);
});
cm.addListener('newRule', function(evt) {
return engine.internalEvent('newRule', evt);
});
_this.log.info('RS | Initialzing http listener');
args['request-service'] = cm.processRequest;
args['shutdown-function'] = shutDown;
return http(args);
}
});
};
})(this);
/*
Shuts down the server.
@private shutDown()
*/
*/
shutDown = (function(_this) {
return function() {
_this.log.warn('RS | Received shut down command!');
if (db != null) {
db.shutDown();
}
if (engine != null) {
engine.shutDown();
}
return process.exit();
};
})(this);
shutDown = function() {
_this.log.warn('RS | Received shut down command!');
if (db != null) {
db.shutDown();
}
if (engine != null) {
engine.shutDown();
}
return process.exit();
};
/*
## Process Commands
*# Process Commands
When the server is run as a child process, this function handles messages
from the parent process (e.g. the testing suite)
*/
*/
process.on('message', function(cmd) {
return typeof procCmds[cmd] === "function" ? procCmds[cmd]() : void 0;

View file

@ -31,7 +31,7 @@ exports.testListener = ( test ) =>
db.storeRule 'test-cm-rule', JSON.stringify oRuleOne
request =
command: 'forge_rule'
payload: oRuleTwo
payload: JSON.stringify oRuleTwo
cm.addListener 'newRule', ( evt ) =>
console.log 'got new rule!'
@ -43,10 +43,10 @@ exports.testListener = ( test ) =>
test.deepEqual evt, oRuleOne, 'Event is not the same!'
console.log 'got and checked init'
cm.processRequest oUser, request, ( answ ) =>
console.log answ
if answ.code isnt 200
test.ok false, 'testListener failed: ' + answ.message
test.done()
cm.processRequest oUser, request, ( answ ) =>
console.log answ
if answ.code isnt 200
test.ok false, 'testListener failed: ' + answ.message
test.done()
console.log 'init listener added'

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;

View file

@ -1,4 +1,4 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
(function() {
var fOnLoad;