Cleansing, formatting, consistency

This commit is contained in:
Dominic Bosch 2014-04-05 03:09:40 +02:00
parent 745dddf04f
commit f070184329
26 changed files with 1277 additions and 1132 deletions

View file

@ -69,19 +69,17 @@ exports.addRuleListener = ( eh ) =>
###
Processes a user request coming through the request-handler.
- `user` is the user object as it comes from the DB.
- `oReq` is the request object that contains:
- `command` as a string
- `payload` an optional stringified JSON object
The callback function `callback( obj )` will receive an object
containing the HTTP response code and a corresponding message.
@public processRequest ( *user, oReq, callback* )
@param {Object} user
@param {Object} oReq
@param {function} callback
###
exports.processRequest = ( user, oReq, callback ) ->
if not oReq.payload
oReq.payload = '{}'
@ -92,12 +90,21 @@ exports.processRequest = ( user, oReq, callback ) ->
code: 404
message: 'You had a strange payload in your request!'
if commandFunctions[oReq.command]
# If the command function was registered we invoke it
commandFunctions[oReq.command] user, dat, callback
else
callback
code: 404
message: 'What do you want from me?'
###
Checks whether all required parameters are present in the payload.
@private hasRequiredParams ( *arrParams, oPayload* )
@param {Array} arrParams
@param {Object} oPayload
###
hasRequiredParams = ( arrParams, oPayload ) ->
answ =
code: 400
@ -107,6 +114,15 @@ hasRequiredParams = ( arrParams, oPayload ) ->
answ.message = 'All required properties found'
answ
###
Fetches all available modules and return them together with the available functions.
@private getModules ( *user, oPayload, dbMod, callback* )
@param {Object} user
@param {Object} oPayload
@param {Object} dbMod
@param {function} callback
###
getModules = ( user, oPayload, dbMod, callback ) ->
dbMod.getAvailableModuleIds user.username, ( err, arrNames ) ->
oRes = {}
@ -218,6 +234,7 @@ commandFunctions =
message: 'OK!'
# A rule needs to be in following format:
# - id
# - event
# - conditions

View file

@ -41,13 +41,6 @@ exports = module.exports = ( args ) =>
@strPublicKey = cryptico.publicKeyString @oPrivateRSAkey
@log.info "DM | Public Key generated: #{ @strPublicKey }"
# plainText = "Matt, I need you to help me with my Starcraft strategy."
# oEncrypted = cryptico.encrypt plainText, strPublicKey
# console.log oEncrypted.cipher
# oDecrypted = cryptico.decrypt oEncrypted.cipher, oPrivateRSAkey
# console.log oDecrypted.plaintext
module.exports

View file

@ -22,21 +22,22 @@ jsonQuery = require 'js-select'
###
This is ging to have a structure like:
An object of users with their active rules and the required action modules
"user-1":
"rule-1":
"rule": oRule-1
"actions":
"action-1": oAction-1
"action-2": oAction-2
"rule-2":
"rule": oRule-2
"actions":
"action-1": oAction-1
"user-2":
"rule-3":
"rule": oRule-3
"actions":
"action-3": oAction-3
"user-1":
"rule-1":
"rule": oRule-1
"actions":
"action-1": oAction-1
"action-2": oAction-2
"rule-2":
"rule": oRule-2
"actions":
"action-1": oAction-1
"user-2":
"rule-3":
"rule": oRule-3
"actions":
"action-3": oAction-3
###
listUserRules = {}
isRunning = false
@ -61,10 +62,11 @@ exports = module.exports = ( args ) =>
###
This is a helper function for the unit tests so we can verify that action
modules are loaded correctly
#TODO we should change this to functions returning true or false rather than returning
#the whole list
@public getListUserRules ()
###
#TODO we should change this to functions returning true or false rather than returning
#the whole list
exports.getListUserRules = () ->
listUserRules

View file

@ -100,16 +100,15 @@ initRouting = ( port ) =>
@shutDownSystem()
# ###
#
# Shuts down the http listener.
# There's no way to gracefully stop express from running, thus we
# call process.exit() at the very end of our existance.
# ... but process.exit cancels the unit tests ...
# thus we do it in the main module and use a cli flag for the unit tests
# @public shutDown()
# ###
#
# exports.shutDown = () =>
# @log?.warn 'HL | Shutting down HTTP listener'
# log?.warn 'HL | Shutting down HTTP listener'
# console.log 'exiting...'
# process.exit()

View file

@ -277,7 +277,7 @@ objects.*
exports.handleAdmin = ( req, resp ) ->
if not req.session.user
page = 'login'
# TODO isAdmin should come from the db role
#TODO isAdmin should come from the db role
else if req.session.user.isAdmin isnt "true"
page = 'login'
msg = 'You need to be admin!'

View file

@ -70,7 +70,8 @@ opt =
'm':
alias : 'log-mode',
describe: 'Specify a log mode: [development|productive]'
# `-i`, `--log-io-level`: Specify the log level for the I/O
# `-i`, `--log-io-level`: Specify the log level for the I/O. in development expensive origin
# lookups are made and added to the log entries
'i':
alias : 'log-io-level',
describe: 'Specify the log level for the I/O'
@ -151,17 +152,19 @@ init = =>
# Start the event poller. The module manager will emit events for it
@log.info 'RS | Forking a child process for the event poller'
# Grab all required log config fields
cliArgs = [
# the log mode: [development|productive]
args.logconf['mode']
# the I/O log level, refer to logging.coffee for the different levels
args.logconf['io-level']
# the file log level, refer to logging.coffee for the different levels
args.logconf['file-level']
# the optional path to the log file
args.logconf['file-path']
# whether a log file shall be written at all: null else
args.logconf['nolog']
# - the log mode: [development|productive], in development expensive origin
# lookups are made and added to the log entries
args.logconf[ 'mode' ]
# - the I/O log level, refer to logging.coffee for the different levels
args.logconf[ 'io-level' ]
# - the file log level, refer to logging.coffee for the different levels
args.logconf[ 'file-level' ]
# - the optional path to the log file
args.logconf[ 'file-path' ]
# - whether a log file shall be written at all: null else
args.logconf[ 'nolog' ]
]
poller = cp.fork path.resolve( __dirname, nameEP ), cliArgs

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, eventEmitter, events, exports, forgeModule, fs, getModuleParams, getModules, hasRequiredParams, path,
_this = this;
var commandFunctions, db, dynmod, eventEmitter, events, exports, forgeModule, fs, getModuleParams, getModules, hasRequiredParams, path;
db = require('./persistence');
@ -25,77 +24,81 @@ Components Manager
eventEmitter = new events.EventEmitter();
/*
Module call
-----------
Initializes the Components Manager and constructs a new Event Emitter.
@param {Object} args
*/
*/
exports = module.exports = (function(_this) {
return function(args) {
_this.log = args.logger;
db(args);
dynmod(args);
return module.exports;
};
})(this);
exports = module.exports = function(args) {
_this.log = args.logger;
db(args);
dynmod(args);
return module.exports;
};
/*
Add an event handler (eh) that listens for rules.
@public addRuleListener ( *eh* )
@param {function} eh
*/
*/
exports.addRuleListener = function(eh) {
eventEmitter.addListener('rule', eh);
return db.getAllActivatedRuleIdsPerUser(function(err, objUsers) {
var fGoThroughUsers, rules, user, _results;
fGoThroughUsers = function(user, rules) {
var fFetchRule, rule, _i, _len, _results;
fFetchRule = function(rule) {
var _this = this;
return db.getRule(rule, function(err, oRule) {
return eventEmitter.emit('rule', {
event: 'init',
user: user,
rule: JSON.parse(oRule)
});
});
exports.addRuleListener = (function(_this) {
return function(eh) {
eventEmitter.addListener('rule', eh);
return db.getAllActivatedRuleIdsPerUser(function(err, objUsers) {
var fGoThroughUsers, rules, user, _results;
fGoThroughUsers = function(user, rules) {
var fFetchRule, rule, _i, _len, _results;
fFetchRule = function(rule) {
return db.getRule(rule, (function(_this) {
return function(err, oRule) {
return eventEmitter.emit('rule', {
event: 'init',
user: user,
rule: JSON.parse(oRule)
});
};
})(this));
};
_results = [];
for (_i = 0, _len = rules.length; _i < _len; _i++) {
rule = rules[_i];
_results.push(fFetchRule(rule));
}
return _results;
};
_results = [];
for (_i = 0, _len = rules.length; _i < _len; _i++) {
rule = rules[_i];
_results.push(fFetchRule(rule));
for (user in objUsers) {
rules = objUsers[user];
_results.push(fGoThroughUsers(user, rules));
}
return _results;
};
_results = [];
for (user in objUsers) {
rules = objUsers[user];
_results.push(fGoThroughUsers(user, rules));
}
return _results;
});
};
});
};
})(this);
/*
Processes a user request coming through the request-handler.
- `user` is the user object as it comes from the DB.
- `oReq` is the request object that contains:
- `command` as a string
- `payload` an optional stringified JSON object
The callback function `callback( obj )` will receive an object
containing the HTTP response code and a corresponding message.
@public processRequest ( *user, oReq, callback* )
@param {Object} user
@param {Object} oReq
@param {function} callback
*/
*/
exports.processRequest = function(user, oReq, callback) {
var dat, err;
@ -121,6 +124,15 @@ Components Manager
}
};
/*
Checks whether all required parameters are present in the payload.
@private hasRequiredParams ( *arrParams, oPayload* )
@param {Array} arrParams
@param {Object} oPayload
*/
hasRequiredParams = function(arrParams, oPayload) {
var answ, param, _i, _len;
answ = {
@ -138,10 +150,20 @@ Components Manager
return answ;
};
/*
Fetches all available modules and return them together with the available functions.
@private getModules ( *user, oPayload, dbMod, callback* )
@param {Object} user
@param {Object} oPayload
@param {Object} dbMod
@param {function} callback
*/
getModules = function(user, oPayload, dbMod, callback) {
return dbMod.getAvailableModuleIds(user.username, function(err, arrNames) {
var answReq, fGetFunctions, id, oRes, sem, _i, _len, _results,
_this = this;
var answReq, fGetFunctions, id, oRes, sem, _i, _len, _results;
oRes = {};
answReq = function() {
return callback({
@ -153,16 +175,18 @@ Components Manager
if (sem === 0) {
return answReq();
} else {
fGetFunctions = function(id) {
return dbMod.getModule(id, function(err, oModule) {
if (oModule) {
oRes[id] = JSON.parse(oModule.functions);
}
if (--sem === 0) {
return answReq();
}
});
};
fGetFunctions = (function(_this) {
return function(id) {
return dbMod.getModule(id, function(err, oModule) {
if (oModule) {
oRes[id] = JSON.parse(oModule.functions);
}
if (--sem === 0) {
return answReq();
}
});
};
})(this);
_results = [];
for (_i = 0, _len = arrNames.length; _i < _len; _i++) {
id = arrNames[_i];
@ -186,44 +210,46 @@ Components Manager
}
};
forgeModule = function(user, oPayload, dbMod, callback) {
var answ;
answ = hasRequiredParams(['id', 'params', 'lang', 'data'], oPayload);
if (answ.code !== 200) {
return callback(answ);
} else {
return dbMod.getModule(oPayload.id, function(err, mod) {
var src;
if (mod) {
answ.code = 409;
answ.message = 'Module name already existing: ' + oPayload.id;
return callback(answ);
} else {
src = oPayload.data;
return dynmod.compileString(src, user.username, 'dummyRule', oPayload.id, oPayload.lang, null, function(cm) {
var funcs, id, name, _ref;
answ = cm.answ;
if (answ.code === 200) {
funcs = [];
_ref = cm.module;
for (name in _ref) {
id = _ref[name];
funcs.push(name);
}
_this.log.info("CM | Storing new module with functions " + (funcs.join()));
answ.message = "Event Poller module successfully stored! Found following function(s): " + funcs;
oPayload.functions = JSON.stringify(funcs);
dbMod.storeModule(user.username, oPayload);
if (oPayload["public"] === 'true') {
dbMod.publish(oPayload.id);
}
}
forgeModule = (function(_this) {
return function(user, oPayload, dbMod, callback) {
var answ;
answ = hasRequiredParams(['id', 'params', 'lang', 'data'], oPayload);
if (answ.code !== 200) {
return callback(answ);
} else {
return dbMod.getModule(oPayload.id, function(err, mod) {
var src;
if (mod) {
answ.code = 409;
answ.message = 'Module name already existing: ' + oPayload.id;
return callback(answ);
});
}
});
}
};
} else {
src = oPayload.data;
return dynmod.compileString(src, user.username, 'dummyRule', oPayload.id, oPayload.lang, null, function(cm) {
var funcs, id, name, _ref;
answ = cm.answ;
if (answ.code === 200) {
funcs = [];
_ref = cm.module;
for (name in _ref) {
id = _ref[name];
funcs.push(name);
}
_this.log.info("CM | Storing new module with functions " + (funcs.join()));
answ.message = "Event Poller module successfully stored! Found following function(s): " + funcs;
oPayload.functions = JSON.stringify(funcs);
dbMod.storeModule(user.username, oPayload);
if (oPayload["public"] === 'true') {
dbMod.publish(oPayload.id);
}
}
return callback(answ);
});
}
});
}
};
})(this);
commandFunctions = {
get_public_key: function(user, oPayload, callback) {

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.getKeygenPassphrase = function() {
return fetchProp('keygen-passphrase');

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 cryptico, cs, db, exports, issueApiCall, needle, vm,
_this = this;
var cryptico, cs, db, exports, issueApiCall, needle, vm;
db = require('./persistence');
@ -22,53 +21,60 @@ Dynamic Modules
cryptico = require('my-cryptico');
/*
Module call
-----------
Initializes the dynamic module handler.
@param {Object} args
*/
*/
exports = module.exports = function(args) {
var numBits, passPhrase;
_this.log = args.logger;
if (!_this.strPublicKey && args['keygen']) {
db(args);
passPhrase = args['keygen'];
numBits = 1024;
_this.oPrivateRSAkey = cryptico.generateRSAKey(passPhrase, numBits);
_this.strPublicKey = cryptico.publicKeyString(_this.oPrivateRSAkey);
_this.log.info("DM | Public Key generated: " + _this.strPublicKey);
}
return module.exports;
};
exports.getPublicKey = function() {
return _this.strPublicKey;
};
issueApiCall = function(method, url, credentials, cb) {
var err, func;
try {
if (method === 'get') {
func = needle.get;
} else {
func = needle.post;
exports = module.exports = (function(_this) {
return function(args) {
var numBits, passPhrase;
_this.log = args.logger;
if (!_this.strPublicKey && args['keygen']) {
db(args);
passPhrase = args['keygen'];
numBits = 1024;
_this.oPrivateRSAkey = cryptico.generateRSAKey(passPhrase, numBits);
_this.strPublicKey = cryptico.publicKeyString(_this.oPrivateRSAkey);
_this.log.info("DM | Public Key generated: " + _this.strPublicKey);
}
return func(url, credentials, function(err, resp, body) {
if (!err) {
return cb(body);
return module.exports;
};
})(this);
exports.getPublicKey = (function(_this) {
return function() {
return _this.strPublicKey;
};
})(this);
issueApiCall = (function(_this) {
return function(method, url, credentials, cb) {
var err, func;
try {
if (method === 'get') {
func = needle.get;
} else {
return cb();
func = needle.post;
}
});
} catch (_error) {
err = _error;
return _this.log.info('DM | Error even before calling!');
}
};
return func(url, credentials, function(err, resp, body) {
if (!err) {
return cb(body);
} else {
return cb();
}
});
} catch (_error) {
err = _error;
return _this.log.info('DM | Error even before calling!');
}
};
})(this);
/*
Try to run a JS module from a string, together with the
@ -80,71 +86,72 @@ Dynamic Modules
@param {String} id
@param {Object} params
@param {String} lang
*/
*/
exports.compileString = function(src, userId, ruleId, modId, lang, dbMod, cb) {
var answ, err, fTryToLoad, logFunction;
answ = {
code: 200,
message: 'Successfully compiled'
};
if (lang === 'CoffeeScript') {
try {
src = cs.compile(src);
} catch (_error) {
err = _error;
answ.code = 400;
answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line;
}
}
logFunction = function(uId, rId, mId) {
return function(msg) {
return db.appendLog(uId, rId, mId, msg);
exports.compileString = (function(_this) {
return function(src, userId, ruleId, modId, lang, dbMod, cb) {
var answ, err, fTryToLoad, logFunction;
answ = {
code: 200,
message: 'Successfully compiled'
};
};
db.resetLog(userId, ruleId);
fTryToLoad = function(params) {
var oDecrypted, sandbox;
if (params) {
if (lang === 'CoffeeScript') {
try {
oDecrypted = cryptico.decrypt(params, _this.oPrivateRSAkey);
params = JSON.parse(oDecrypted.plaintext);
src = cs.compile(src);
} catch (_error) {
err = _error;
_this.log.warn("DM | Error during parsing of user defined params for " + userId + ", " + ruleId + ", " + modId);
answ.code = 400;
answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line;
}
}
logFunction = function(uId, rId, mId) {
return function(msg) {
return db.appendLog(uId, rId, mId, msg);
};
};
db.resetLog(userId, ruleId);
fTryToLoad = function(params) {
var oDecrypted, sandbox;
if (params) {
try {
oDecrypted = cryptico.decrypt(params, _this.oPrivateRSAkey);
params = JSON.parse(oDecrypted.plaintext);
} catch (_error) {
err = _error;
_this.log.warn("DM | Error during parsing of user defined params for " + userId + ", " + ruleId + ", " + modId);
params = {};
}
} else {
params = {};
}
} else {
params = {};
}
sandbox = {
id: userId + '.' + modId + '.vm',
params: params,
apicall: issueApiCall,
log: logFunction(userId, ruleId, modId),
exports: {}
sandbox = {
id: userId + '.' + modId + '.vm',
params: params,
apicall: issueApiCall,
log: logFunction(userId, ruleId, modId),
exports: {}
};
try {
vm.runInNewContext(src, sandbox, sandbox.id);
} catch (_error) {
err = _error;
console.log(err);
answ.code = 400;
answ.message = 'Loading Module failed: ' + err.message;
}
return cb({
answ: answ,
module: sandbox.exports
});
};
try {
vm.runInNewContext(src, sandbox, sandbox.id);
} catch (_error) {
err = _error;
console.log(err);
answ.code = 400;
answ.message = 'Loading Module failed: ' + err.message;
if (dbMod) {
return dbMod.getUserParams(modId, userId, function(err, obj) {
return fTryToLoad(obj);
});
} else {
return fTryToLoad();
}
return cb({
answ: answ,
module: sandbox.exports
});
};
if (dbMod) {
return dbMod.getUserParams(modId, userId, function(err, obj) {
return fTryToLoad(obj);
});
} else {
return fTryToLoad();
}
};
})(this);
}).call(this);

View file

@ -1,4 +1,5 @@
// Generated by CoffeeScript 1.6.3
// Generated by CoffeeScript 1.7.1
/*
Engine
@ -6,12 +7,10 @@ Engine
> The heart of the WebAPI ECA System. The engine loads action invoker modules
> corresponding to active rules actions and invokes them if an appropriate event
> is retrieved.
*/
*/
(function() {
var db, dynmod, exports, isRunning, jsonQuery, listUserRules, pollQueue, processEvent, updateActionModules, validConditions,
_this = this;
var db, dynmod, exports, isRunning, jsonQuery, listUserRules, pollQueue, processEvent, updateActionModules, validConditions;
db = require('./persistence');
@ -19,94 +18,99 @@ Engine
jsonQuery = require('js-select');
/*
This is ging to have a structure like:
An object of users with their active rules and the required action modules
"user-1":
"rule-1":
"rule": oRule-1
"actions":
"action-1": oAction-1
"action-2": oAction-2
"rule-2":
"rule": oRule-2
"actions":
"action-1": oAction-1
"user-2":
"rule-3":
"rule": oRule-3
"actions":
"action-3": oAction-3
*/
"user-1":
"rule-1":
"rule": oRule-1
"actions":
"action-1": oAction-1
"action-2": oAction-2
"rule-2":
"rule": oRule-2
"actions":
"action-1": oAction-1
"user-2":
"rule-3":
"rule": oRule-3
"actions":
"action-3": oAction-3
*/
listUserRules = {};
isRunning = false;
/*
Module call
-----------
Initializes the Engine and starts polling the event queue for new events.
@param {Object} args
*/
*/
exports = module.exports = (function(_this) {
return function(args) {
if (!isRunning) {
isRunning = true;
_this.log = args.logger;
db(args);
dynmod(args);
setTimeout(pollQueue, 10);
return module.exports;
}
};
})(this);
exports = module.exports = function(args) {
if (!isRunning) {
isRunning = true;
_this.log = args.logger;
db(args);
dynmod(args);
setTimeout(pollQueue, 10);
return module.exports;
}
};
/*
This is a helper function for the unit tests so we can verify that action
modules are loaded correctly
#TODO we should change this to functions returning true or false rather than returning
#the whole list
@public getListUserRules ()
*/
*/
exports.getListUserRules = function() {
return listUserRules;
};
/*
An event associated to rules happened and is captured here. Such events
are basically CRUD on rules.
@public internalEvent ( *evt* )
@param {Object} evt
*/
*/
exports.internalEvent = (function(_this) {
return function(evt) {
var oRule, oUser;
if (!listUserRules[evt.user] && evt.event !== 'del') {
listUserRules[evt.user] = {};
}
oUser = listUserRules[evt.user];
oRule = evt.rule;
if (evt.event === 'new' || (evt.event === 'init' && !oUser[oRule.id])) {
oUser[oRule.id] = {
rule: oRule,
actions: {}
};
updateActionModules(oRule.id);
}
if (evt.event === 'del' && oUser) {
delete oUser[evt.ruleId];
}
if (JSON.stringify(oUser) === "{}") {
return delete listUserRules[evt.user];
}
};
})(this);
exports.internalEvent = function(evt) {
var oRule, oUser;
if (!listUserRules[evt.user] && evt.event !== 'del') {
listUserRules[evt.user] = {};
}
oUser = listUserRules[evt.user];
oRule = evt.rule;
if (evt.event === 'new' || (evt.event === 'init' && !oUser[oRule.id])) {
oUser[oRule.id] = {
rule: oRule,
actions: {}
};
updateActionModules(oRule.id);
}
if (evt.event === 'del' && oUser) {
delete oUser[evt.ruleId];
}
if (JSON.stringify(oUser) === "{}") {
return delete listUserRules[evt.user];
}
};
/*
As soon as changes were made to the rule set we need to ensure that the aprropriate action
@ -114,8 +118,7 @@ Engine
@private updateActionModules ( *updatedRuleId* )
@param {Object} updatedRuleId
*/
*/
updateActionModules = function(updatedRuleId) {
var fAddRequired, fRemoveNotRequired, name, oUser, userName, _results;
@ -157,7 +160,7 @@ Engine
return db.actionInvokers.getModule(moduleName, function(err, obj) {
return dynmod.compileString(obj.data, userName, oMyRule.rule.id, moduleName, obj.lang, db.actionInvokers, function(result) {
if (!result.answ === 200) {
this.log.error("EN | Compilation of code failed! " + userName + ", " + oMyRule.rule.id + ", " + moduleName);
this.log.error("EN | Compilation of code failed! " + userName + ", " + oMyRule.rule.id + ", " + moduleName);
}
return oMyRule.actions[moduleName] = result.module;
});
@ -198,14 +201,14 @@ Engine
}
};
/*
Checks whether all conditions of the rule are met by the event.
@private validConditions ( *evt, rule* )
@param {Object} evt
@param {Object} rule
*/
*/
validConditions = function(evt, rule) {
var prop, _i, _len, _ref;
@ -222,64 +225,66 @@ Engine
return true;
};
/*
Handles retrieved events.
@private processEvent ( *evt* )
@param {Object} evt
*/
*/
processEvent = function(evt) {
var action, arr, fSearchAndInvokeAction, oMyRule, oUser, ruleName, userName, _results;
fSearchAndInvokeAction = function(node, arrPath, evt, depth) {
var err;
if (!node) {
this.log.error("EN | Didn't find property in user rule list: " + arrPath.join(', ' + " at depth " + depth));
return;
}
if (depth === arrPath.length) {
try {
return node(evt.payload);
} catch (_error) {
err = _error;
return this.log.info("EN | ERROR IN ACTION INVOKER: " + err.message);
processEvent = (function(_this) {
return function(evt) {
var action, arr, fSearchAndInvokeAction, oMyRule, oUser, ruleName, userName, _results;
fSearchAndInvokeAction = function(node, arrPath, evt, depth) {
var err;
if (!node) {
this.log.error("EN | Didn't find property in user rule list: " + arrPath.join(', ' + " at depth " + depth));
return;
}
} else {
return fSearchAndInvokeAction(node[arrPath[depth]], arrPath, evt, depth + 1);
}
};
_this.log.info('EN | processing event: ' + evt.event + '(' + evt.eventid + ')');
_results = [];
for (userName in listUserRules) {
oUser = listUserRules[userName];
_results.push((function() {
var _results1;
_results1 = [];
for (ruleName in oUser) {
oMyRule = oUser[ruleName];
if (evt.event === oMyRule.rule.event && validConditions(evt, oMyRule.rule)) {
this.log.info('EN | EVENT FIRED: ' + evt.event + '(' + evt.eventid + ') for rule ' + ruleName);
_results1.push((function() {
var _i, _len, _ref, _results2;
_ref = oMyRule.rule.actions;
_results2 = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
action = _ref[_i];
arr = action.split(' -> ');
_results2.push(fSearchAndInvokeAction(listUserRules, [userName, ruleName, 'actions', arr[0], arr[1]], evt, 0));
}
return _results2;
})());
} else {
_results1.push(void 0);
if (depth === arrPath.length) {
try {
return node(evt.payload);
} catch (_error) {
err = _error;
return this.log.info("EN | ERROR IN ACTION INVOKER: " + err.message);
}
} else {
return fSearchAndInvokeAction(node[arrPath[depth]], arrPath, evt, depth + 1);
}
return _results1;
}).call(_this));
}
return _results;
};
};
_this.log.info('EN | processing event: ' + evt.event + '(' + evt.eventid + ')');
_results = [];
for (userName in listUserRules) {
oUser = listUserRules[userName];
_results.push((function() {
var _results1;
_results1 = [];
for (ruleName in oUser) {
oMyRule = oUser[ruleName];
if (evt.event === oMyRule.rule.event && validConditions(evt, oMyRule.rule)) {
this.log.info('EN | EVENT FIRED: ' + evt.event + '(' + evt.eventid + ') for rule ' + ruleName);
_results1.push((function() {
var _i, _len, _ref, _results2;
_ref = oMyRule.rule.actions;
_results2 = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
action = _ref[_i];
arr = action.split(' -> ');
_results2.push(fSearchAndInvokeAction(listUserRules, [userName, ruleName, 'actions', arr[0], arr[1]], evt, 0));
}
return _results2;
})());
} else {
_results1.push(void 0);
}
}
return _results1;
}).call(_this));
}
return _results;
};
})(this);
exports.shutDown = function() {
return isRunning = false;

View file

@ -1,12 +1,12 @@
// 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 db, dynmod, fLoadModule, isRunning, listUserModules, log, logconf, logger, pollLoop;
@ -77,7 +77,7 @@ Dynamic Modules
} else {
return dynmod.compileString(obj.data, msg.user, msg.rule.id, arrName[0], obj.lang, db.eventPollers, function(result) {
if (!result.answ === 200) {
log.error("EP | Compilation of code failed! " + msg.user + ", " + msg.rule.id + ", " + arrName[0]);
log.error("EP | Compilation of code failed! " + msg.user + ", " + msg.rule.id + ", " + arrName[0]);
}
if (!listUserModules[msg.user]) {
listUserModules[msg.user] = {};
@ -87,7 +87,7 @@ Dynamic Modules
pollfunc: arrName[1],
module: result.module
};
return log.info("EP | New event module loaded! " + msg.user + ", " + msg.rule.id + ", " + arrName[0]);
return log.info("EP | New event module loaded! " + msg.user + ", " + msg.rule.id + ", " + arrName[0]);
});
}
});
@ -97,12 +97,12 @@ Dynamic Modules
}
};
/*
This function will loop infinitely every 10 seconds until isRunning is set to false
@private pollLoop()
*/
*/
pollLoop = function() {
var err, fPoll, fRegisterModuleReference, myRule, oRules, ruleName, userName;

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;
@ -102,6 +103,7 @@ Request Handler
});
};
/*
Associates the user object with the session if login is successful.
@ -111,32 +113,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
@ -148,8 +152,7 @@ Request Handler
objects.*
@public handleLogout( *req, resp* )
*/
*/
exports.handleLogout = function(req, resp) {
if (req.session) {
@ -158,25 +161,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;
@ -184,13 +187,13 @@ Request Handler
return fs.readFileSync(pth, 'utf8');
};
/*
Fetches a script.
@private getScript( *name* )
@param {String} name
*/
*/
getScript = function(name) {
var pth;
@ -198,13 +201,13 @@ Request Handler
return fs.readFileSync(pth, 'utf8');
};
/*
Fetches remote scripts snippets.
@private getRemoteScripts( *name* )
@param {String} name
*/
*/
getRemoteScripts = function(name) {
var pth;
@ -212,6 +215,7 @@ Request Handler
return fs.readFileSync(pth, 'utf8');
};
/*
Renders a page, with helps of mustache, depending on the user session and returns it.
@ -219,8 +223,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;
@ -259,6 +262,7 @@ Request Handler
return resp.send(code, mustache.render(page, data));
};
/*
Present the desired forge page to the user.
@ -268,8 +272,7 @@ Request Handler
objects.*
@public handleForge( *req, resp* )
*/
*/
exports.handleForge = function(req, resp) {
var page;
@ -280,6 +283,7 @@ Request Handler
return renderPage(page, req, resp);
};
/*
Handles the user command requests.
@ -289,27 +293,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.
@ -320,8 +326,7 @@ Request Handler
objects.*
@public handleForge( *req, resp* )
*/
*/
exports.handleAdmin = function(req, resp) {
var msg, page;
@ -336,6 +341,7 @@ Request Handler
return renderPage(page, req, resp, msg);
};
/*
Handles the admin command requests.
@ -345,31 +351,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, logconf, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage,
_this = this;
var argv, cm, conf, cp, db, engine, fs, http, init, logconf, 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';
@ -130,72 +129,76 @@ WebAPI-ECA Engine
this.log.info('RS | STARTING SERVER');
/*
This function is invoked right after the module is loaded and starts the server.
@private init()
*/
*/
init = function() {
var args;
args = {
logger: _this.log,
logconf: logconf
init = (function(_this) {
return function() {
var args;
args = {
logger: _this.log,
logconf: logconf
};
args['http-port'] = parseInt(argv.w || conf.getHttpPort());
args['db-port'] = parseInt(argv.d || conf.getDbPort());
args['keygen'] = conf.getKeygenPassphrase();
_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.addRuleListener(engine.internalEvent);
cm.addRuleListener(function(evt) {
return poller.send(evt);
});
_this.log.info('RS | Initialzing http listener');
args['request-service'] = cm.processRequest;
args['shutdown-function'] = shutDown;
return http(args);
}
});
};
args['http-port'] = parseInt(argv.w || conf.getHttpPort());
args['db-port'] = parseInt(argv.d || conf.getDbPort());
args['keygen'] = conf.getKeygenPassphrase();
_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.addRuleListener(engine.internalEvent);
cm.addRuleListener(function(evt) {
return poller.send(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();
}
engine.shutDown();
return process.exit();
};
})(this);
shutDown = function() {
_this.log.warn('RS | Received shut down command!');
if (db != null) {
db.shutDown();
}
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

@ -10,16 +10,16 @@ try
catch err
console.log 'Error fetching standard objects file: ' + err.message
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
log = logger.getLogger
nolog: true
opts =
logger: log
cm = require path.join '..', 'js-coffee', 'components-manager'
cm = require path.join '..', 'js', 'components-manager'
cm opts
db = require path.join '..', 'js-coffee', 'persistence'
db = require path.join '..', 'js', 'persistence'
db opts
oUser = objects.users.userOne

View file

@ -1,8 +1,8 @@
path = require 'path'
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
log = logger.getLogger
nolog: true
conf = require path.join '..', 'js-coffee', 'config'
conf = require path.join '..', 'js', 'config'
conf
logger: log

View file

@ -16,20 +16,20 @@ try
catch err
console.log 'Error fetching standard objects file: ' + err.message
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
log = logger.getLogger
nolog: true
opts =
logger: log
keygen: passPhrase
db = require path.join '..', 'js-coffee', 'persistence'
db = require path.join '..', 'js', 'persistence'
db opts
engine = require path.join '..', 'js-coffee', 'engine'
engine = require path.join '..', 'js', 'engine'
engine opts
dm = require path.join '..', 'js-coffee', 'dynamic-modules'
dm = require path.join '..', 'js', 'dynamic-modules'
dm opts
oUser = objects.users.userOne

View file

@ -10,16 +10,16 @@ try
catch err
console.log 'Error fetching standard objects file: ' + err.message
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
log = logger.getLogger
nolog: true
opts =
logger: log
engine = require path.join '..', 'js-coffee', 'engine'
engine = require path.join '..', 'js', 'engine'
engine opts
db = require path.join '..', 'js-coffee', 'persistence'
db = require path.join '..', 'js', 'persistence'
db opts
listRules = engine.getListUserRules()

View file

@ -23,7 +23,7 @@ exports.testsGoInWebAPI_ECA_Module = ( test ) ->
# path = require 'path'
# http = require 'http'
# needle = require 'needle'
# logger = require path.join '..', 'js-coffee', 'logging'
# logger = require path.join '..', 'js', 'logging'
# log = logger.getLogger
# nolog: true
@ -32,7 +32,7 @@ exports.testsGoInWebAPI_ECA_Module = ( test ) ->
# pathFile = path.resolve 'webpages', 'public', 'style.css'
# fl = fs.readFileSync pathFile, 'utf-8'
# hl = require path.join '..', 'js-coffee', 'http-listener'
# hl = require path.join '..', 'js', 'http-listener'
# fWaitForTestEnd = () =>
# console.log 'hl end?'
# process.kill()
@ -59,7 +59,7 @@ exports.testsGoInWebAPI_ECA_Module = ( test ) ->
# exports.testWrongPort = ( test ) =>
# test.expect 1
# hl = require path.join '..', 'js-coffee', 'http-listener'
# hl = require path.join '..', 'js', 'http-listener'
# fWaitForTestEnd = () =>
# console.log 'hl end?'
# process.kill()

View file

@ -1,7 +1,7 @@
path = require 'path'
fs = require 'fs'
stdPath = path.resolve __dirname, '..', 'logs', 'server.log'
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
getLog = ( strPath, cb ) ->
fWait = ->

View file

@ -9,10 +9,10 @@ try
catch err
console.log 'Error fetching standard objects file: ' + err.message
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
log = logger.getLogger
nolog: true
db = require path.join '..', 'js-coffee', 'persistence'
db = require path.join '..', 'js', 'persistence'
opts =
logger: log
opts[ 'db-port' ] = 6379

View file

@ -14,16 +14,16 @@ try
console.log 'Error parsing standard objects file: ' + err.message
catch err
console.log 'Error fetching standard objects file: ' + err.message
logger = require path.join '..', 'js-coffee', 'logging'
logger = require path.join '..', 'js', 'logging'
log = logger.getLogger
nolog: true
opts =
logger: log
opts[ 'db-port' ] = 6379
db = require path.join '..', 'js-coffee', 'persistence'
db = require path.join '..', 'js', 'persistence'
db opts
rh = require path.join '..', 'js-coffee', 'request-handler'
rh = require path.join '..', 'js', 'request-handler'
opts[ 'request-service' ] = ( usr, obj, cb ) ->
test.ok false, 'testEvent should not cause a service request call'
opts[ 'shutdown-function' ] = () ->

View file

@ -9,7 +9,7 @@ exports.testShutDown = ( test ) ->
test.expect 1
isRunning = true
pth = path.resolve 'js-coffee', 'webapi-eca'
pth = path.resolve 'js', 'webapi-eca'
engine = cp.fork pth, [ '-n', '-w', '8640' ] # [ '-i' , 'warn' ]
engine.on 'error', ( err ) ->
@ -35,7 +35,7 @@ exports.testShutDown = ( test ) ->
exports.testKill = ( test ) ->
test.expect 1
pth = path.resolve 'js-coffee', 'webapi-eca'
pth = path.resolve 'js', 'webapi-eca'
engine = cp.fork pth, [ '-n', '-w', '8641' ] # [ '-i' , 'warn' ]
engine.on 'error', ( err ) ->
console.log err
@ -54,7 +54,7 @@ exports.testKill = ( test ) ->
exports.testHttpPortAlreadyUsed = ( test ) =>
test.expect 1
isRunning = true
pth = path.resolve 'js-coffee', 'webapi-eca'
pth = path.resolve 'js', 'webapi-eca'
# Strange! why can't we make these variables local without
# the tests failing in one of the next tests...
@ -89,7 +89,7 @@ exports.testHttpPortInvalid = ( test ) ->
test.expect 1
isRunning = true
pth = path.resolve 'js-coffee', 'webapi-eca'
pth = path.resolve 'js', 'webapi-eca'
engine = cp.fork pth, [ '-n', '-w', '1' ] # [ '-i' , 'warn' ]
engine.on 'exit', ( code, signal ) ->
test.ok true, 'Engine stopped'
@ -111,7 +111,7 @@ exports.testDbPortInvalid = ( test ) ->
test.expect 1
isRunning = true
pth = path.resolve 'js-coffee', 'webapi-eca'
pth = path.resolve 'js', 'webapi-eca'
engine = cp.fork pth, [ '-n', '-d', '10'] # [ '-i' , 'warn' ]
engine.on 'error', ( err ) ->
console.log err

View file

@ -3,7 +3,7 @@ process.chdir( __dirname );
var fs = require( 'fs' ),
path = require( 'path' ),
nodeunit = require( 'nodeunit' ),
db = require( './js-coffee/persistence' ),
db = require( './js/persistence' ),
args = process.argv.slice( 2 ),
fEnd = function() {
console.log( 'Shutting down DB from unit_test.sh script...' );