diff --git a/bin/server b/bin/server index 52551cf..de40b8e 100755 --- a/bin/server +++ b/bin/server @@ -29,7 +29,7 @@ nconf.file ({file: IotronicHome + '/settings.json'}); var wampR_url = nconf.get('config:wamp:url')+":"+nconf.get('config:wamp:port'); var wamp_realm = nconf.get('config:wamp:realm'); -console.log(wampR_url); +//console.log(wampR_url); var server = new iotronic.server; server.start(wampR_url, wamp_realm); diff --git a/docs/installation_ubuntu_14.04.md b/docs/installation_ubuntu_14.04.md index 452aeec..03225a6 100644 --- a/docs/installation_ubuntu_14.04.md +++ b/docs/installation_ubuntu_14.04.md @@ -148,6 +148,7 @@ if you would like to use HTTPS to expose them you have to specify the "https" se ``` "db":{ "host":"localhost", + "port":3306, "user":"root", "password":"", "db_name": "s4t-iotronic" @@ -160,9 +161,13 @@ if you would like to use HTTPS to expose them you have to specify the "https" se "email": { "address": "", "password": "" + "smtp":{ + "smtp_server": """, + "smtp_port": """, + "smtp_secure": "[ true | false ]" + } }, "enable_notify":"[ true | false ]", - "retry": } ``` @@ -177,7 +182,7 @@ node /usr/lib/node_modules/@mdslab/iotronic-standalone/utils/createAdminToken.js "encryptKey": "", "adminToken": "", "backend": "iotronic", - "expire_time": 60 + "expire_time": "30m" } ``` The "encryptKey" field is a user-defined keyword/password used to encrypt/decrypt the users passwords during authentication procedures. @@ -244,57 +249,115 @@ RESPONSE: ## API documentation management -IoTronic releases its APIs documentation by means of Swagger framework. In particular we used ["swagger-jsdoc"](https://www.npmjs.com/package/swagger-jsdoc) and ["swagger-ui"](https://swagger.io/swagger-ui/) respectively to describe each RESTful API in the source code and publish the produced documentation. +IoTronic releases its APIs documentation by means of Swagger framework. In particular we used ["swagger-jsdoc"](https://www.npmjs.com/package/swagger-jsdoc) and ["swagger-ui"](https://swagger.io/swagger-ui/) +respectively to describe each RESTful API in the source code and publish the produced documentation. -To use swagger-ui we need to clone the git repository from [here](https://github.com/swagger-api/swagger-ui) - and move the "dist" folder where you prefer and specify it inside the "settings.json" configuration file - as showed below: +Iotronic is able to expose the documentation: + 1. embedded mode: generate and expose runtime the API documentation + 2. exposed mode: only specify the URLs of the web-server that is exposing the documentation +In both cases we need to get the "swagger-ui" cloning the git repository from [here](https://github.com/swagger-api/swagger-ui) + and rename the "dist/" folder in "iotronic-api-docs/". + +#### 1. Embedded mode ``` "docs": { - "enable": [ true | false ], - "path": "" + + "embedded":{ + "enable": true, + "path": "" + }, + "exposed":{ + "enable": false, + "url":"", + "url_spec":"" + } } + ``` +We have to move the "iotronic-api-docs/" folder in the "/var/lib/iotronic/docs/" and we need to specify it inside the +"settings.json" configuration file, as showed above, in the "path" section substituting "" variable +and setting to "true" the "enable" flag in the "embedded" section. -You have to edit the "index.html" in as described in the [official guide](https://swagger.io/docs/swagger-tools/#download-33): +The API documentation will be available at: ``` -window.swaggerUi = new SwaggerUi({ - url: , -… -}); +http(s)://:/v1/iotronic-api-docs/ () ``` -where +and the location of the Swagger JSON file will be: ``` - = http(s)://://iotronic-swagger.json +http(s)://:/v1/iotronic-swagger.json () ``` -[Link to Official guide](https://swagger.io/docs/swagger-tools/#download-33) -#### Embedded API management -Enabling the above flag ("enable":true) IoTronic will generate end expose the API documentation. +#### 2. Exposed mode +``` +"docs": { -The docs will be available at: + "embedded":{ + "enable": false, + "path": "" + }, + "exposed":{ + "enable": true, + "url":"", + "url_spec":"" + } + +} + +``` +In this case we have to +1. move the "iotronic-api-docs/" folder in the web-server public folder to expose the "swagger-ui" (e.g. in Apache we +have to move "iotronic-api-docs/" in "/var/www/html/"); +2. generate the swagger json file "iotronic-swagger.json" executing the the script "iotronic-docs-gen.js" provided +by Iotronic in the "docs/" folder; e.g.: +``` +node iotronic-docs-gen.js --iotronic=$NODE_PATH"/@mdslab/iotronic-standalone/" -e false -w /var/www/html/iotronic-api-docs/ ``` - = http(s)://:/v1/iotronic-api-docs/ +For more information see the below section "Standalone API management". + +3. configure the "settings.json" configuration file: +- set to "true" the "enable" flag in the "exposed" section; +- specify the urls of the documentation () and the url that exposes the "iotronic-swagger.json" file +(); + +The API documentation will be available at: +``` +http(s):///iotronic-api-docs/ () ``` and the location of the Swagger JSON file will be: ``` - = http(s)://:/v1/iotronic-swagger.json +http(s):///iotronic-api-docs/iotronic-swagger.json () +``` + + +In both the cases you have to edit the "index.html" in as described in the +[official guide](https://swagger.io/docs/swagger-tools/#download-33): +``` +window.swaggerUi = new SwaggerUi({ + url: , +… +}); ``` +[Link to Official guide](https://swagger.io/docs/swagger-tools/#download-33) + + + #### Standalone API management -We also provided a NodeJS script ([iotronic-docs-gen.js](iotronic-docs-gen.js)) to do that without using directly IoTronic (we need to set "enable" to false). This script will generate the documentation and will publish it by means of "swagger-ui". +We also provided a NodeJS script ([iotronic-docs-gen.js](iotronic-docs-gen.js)) to do that without using directly +IoTronic or a web-server. This script will generate the documentation and will publish it by means of "swagger-ui". Script usage: ``` -node iotronic-docs-gen.js --iotronic="" -e [true|false] [ -p ] +node iotronic-docs-gen.js --iotronic="" -e [true|false] [ -p ] [ -w ] ``` options: - -i, --iotronic IoTronic suorce code path. (e.g. "/usr/lib/node_modules/@mdslab/iotronic-standalone/") - -e, --embedded true | false to spawn API webpage documentation; if "false" the "iotronic-swagger.json" will be created in the folder specified in the "settings.json" file in the "docs" section. - -p, --port [only with --embedded=true] Listening port. (this port has to be different from the ports used by IoTronic "http(s)_port") + - -w, --web Web server path: where will be created the swagger json file "iotronic-swagger.json". The docs will be available at: ``` diff --git a/docs/installation_ubuntu_16.04.md b/docs/installation_ubuntu_16.04.md index df5812d..4882474 100644 --- a/docs/installation_ubuntu_16.04.md +++ b/docs/installation_ubuntu_16.04.md @@ -64,6 +64,7 @@ git clone git://github.com/MDSLab/s4t-iotronic-standalone.git mv s4t-iotronic-standalone/ iotronic-standalone cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/systemd/system/iotronic-standalone.service /etc/systemd/system/ +sed -i "s|ExecStart=|ExecStart=$NODE_PATH/@mdslab/iotronic-standalone/bin/server|g" /etc/systemd/system/iotronic-standalone.service chmod +x /etc/systemd/system/iotronic-standalone.service systemctl daemon-reload systemctl enable iotronic-standalone.service @@ -152,6 +153,7 @@ if you would like to use HTTPS to expose them you have to specify the "https" se ``` "db":{ "host":"localhost", + "port":3306, "user":"root", "password":"", "db_name": "s4t-iotronic" @@ -164,6 +166,11 @@ if you would like to use HTTPS to expose them you have to specify the "https" se "email": { "address": "", "password": "" + "smtp":{ + "smtp_server": """, + "smtp_port": """, + "smtp_secure": "[ true | false ]" + } }, "enable_notify":"[ true | false ]", } @@ -180,7 +187,7 @@ node /usr/lib/node_modules/@mdslab/iotronic-standalone/utils/createAdminToken.js "encryptKey": "", "adminToken": "", "backend": "iotronic", - "expire_time": 60 + "expire_time": "30m" } ``` The "encryptKey" field is a user-defined keyword/password used to encrypt/decrypt the users passwords during authentication procedures. @@ -249,57 +256,115 @@ RESPONSE: ## API documentation management -IoTronic releases its APIs documentation by means of Swagger framework. In particular we used ["swagger-jsdoc"](https://www.npmjs.com/package/swagger-jsdoc) and ["swagger-ui"](https://swagger.io/swagger-ui/) respectively to describe each RESTful API in the source code and publish the produced documentation. +IoTronic releases its APIs documentation by means of Swagger framework. In particular we used ["swagger-jsdoc"](https://www.npmjs.com/package/swagger-jsdoc) and ["swagger-ui"](https://swagger.io/swagger-ui/) +respectively to describe each RESTful API in the source code and publish the produced documentation. -To use swagger-ui we need to clone the git repository from [here](https://github.com/swagger-api/swagger-ui) - and move the "dist" folder where you prefer and specify it inside the "settings.json" configuration file - as showed below: +Iotronic is able to expose the documentation: + 1. embedded mode: generate and expose runtime the API documentation + 2. exposed mode: only specify the URLs of the web-server that is exposing the documentation +In both cases we need to get the "swagger-ui" cloning the git repository from [here](https://github.com/swagger-api/swagger-ui) + and rename the "dist/" folder in "iotronic-api-docs/". + +#### 1. Embedded mode ``` "docs": { - "enable": [ true | false ], - "path": "" + + "embedded":{ + "enable": true, + "path": "" + }, + "exposed":{ + "enable": false, + "url":"", + "url_spec":"" + } } + ``` +We have to move the "iotronic-api-docs/" folder in the "/var/lib/iotronic/docs/" and we need to specify it inside the +"settings.json" configuration file, as showed above, in the "path" section substituting "" variable +and setting to "true" the "enable" flag in the "embedded" section. -You have to edit the "index.html" in as described in the [official guide](https://swagger.io/docs/swagger-tools/#download-33): +The API documentation will be available at: ``` -window.swaggerUi = new SwaggerUi({ - url: , -… -}); +http(s)://:/v1/iotronic-api-docs/ () ``` -where +and the location of the Swagger JSON file will be: ``` - = http(s)://://iotronic-swagger.json +http(s)://:/v1/iotronic-swagger.json () ``` -[Link to Official guide](https://swagger.io/docs/swagger-tools/#download-33) -#### Embedded API management -Enabling the above flag ("enable":true) IoTronic will generate end expose the API documentation. +#### 2. Exposed mode +``` +"docs": { -The docs will be available at: + "embedded":{ + "enable": false, + "path": "" + }, + "exposed":{ + "enable": true, + "url":"", + "url_spec":"" + } + +} + +``` +In this case we have to +1. move the "iotronic-api-docs/" folder in the web-server public folder to expose the "swagger-ui" (e.g. in Apache we +have to move "iotronic-api-docs/" in "/var/www/html/"); +2. generate the swagger json file "iotronic-swagger.json" executing the the script "iotronic-docs-gen.js" provided +by Iotronic in the "docs/" folder; e.g.: +``` +node iotronic-docs-gen.js --iotronic=$NODE_PATH"/@mdslab/iotronic-standalone/" -e false -w /var/www/html/iotronic-api-docs/ ``` - = http(s)://:/v1/iotronic-api-docs/ +For more information see the below section "Standalone API management". + +3. configure the "settings.json" configuration file: +- set to "true" the "enable" flag in the "exposed" section; +- specify the urls of the documentation () and the url that exposes the "iotronic-swagger.json" file +(); + +The API documentation will be available at: +``` +http(s):///iotronic-api-docs/ () ``` and the location of the Swagger JSON file will be: ``` - = http(s)://:/v1/iotronic-swagger.json +http(s):///iotronic-api-docs/iotronic-swagger.json () +``` + + +In both the cases you have to edit the "index.html" in as described in the +[official guide](https://swagger.io/docs/swagger-tools/#download-33): +``` +window.swaggerUi = new SwaggerUi({ + url: , +… +}); ``` +[Link to Official guide](https://swagger.io/docs/swagger-tools/#download-33) + + + #### Standalone API management -We also provided a NodeJS script ([iotronic-docs-gen.js](iotronic-docs-gen.js)) to do that without using directly IoTronic (we need to set "enable" to false). This script will generate the documentation and will publish it by means of "swagger-ui". +We also provided a NodeJS script ([iotronic-docs-gen.js](iotronic-docs-gen.js)) to do that without using directly +IoTronic or a web-server. This script will generate the documentation and will publish it by means of "swagger-ui". Script usage: ``` -node iotronic-docs-gen.js --iotronic="" -e [true|false] [ -p ] +node iotronic-docs-gen.js --iotronic="" -e [true|false] [ -p ] [ -w ] ``` options: - -i, --iotronic IoTronic suorce code path. (e.g. "/usr/lib/node_modules/@mdslab/iotronic-standalone/") - -e, --embedded true | false to spawn API webpage documentation; if "false" the "iotronic-swagger.json" will be created in the folder specified in the "settings.json" file in the "docs" section. - -p, --port [only with --embedded=true] Listening port. (this port has to be different from the ports used by IoTronic "http(s)_port") + - -w, --web Web server path: where will be created the swagger json file "iotronic-swagger.json". The docs will be available at: ``` diff --git a/docs/iotronic-docs-gen.js b/docs/iotronic-docs-gen.js index 1995f30..43b7d36 100644 --- a/docs/iotronic-docs-gen.js +++ b/docs/iotronic-docs-gen.js @@ -25,12 +25,10 @@ var optimist = require('optimist').usage("IoTronic API documentation generator." .string("iotronic").alias('i', "iotronic").describe('i', 'IoTronic suorce code path.') .boolean("embedded").alias('e', "embedded").describe('e', 'true | false to spawn API webpage documentation.') .string("port").alias('p', "port").describe('p', '[only with --embedded=true] Listening port.') - .string("web").alias('w', "web").describe('w', 'Web server path.'); + .string("web").alias('w', "web").describe('w', 'Web server path: where will be created the swagger json file "iotronic-swagger.json".'); var argv = optimist.argv; -//console.log(argv) - /** * @swagger * definitions: @@ -55,10 +53,10 @@ var genApiDocumentation = function (){ var swaggerDefinition = { info: { title: 'IoTronic API', - version: '2.0.0', + version: '2.1.0', description: 'IoTronic-standalone API by Stack4Things.' }, - host: IoTronic_IP+':8443', + host: IoTronic_IP+':'+port, basePath: '/', licence:{ name: 'Apache v2', @@ -90,6 +88,7 @@ var genApiDocumentation = function (){ IOTRONIC_CODE +'lib/management/mng_user.js', IOTRONIC_CODE +'lib/management/mng_layout.js', IOTRONIC_CODE +'lib/management/mng_project.js', + IOTRONIC_CODE +'lib/management/mng_request.js', IOTRONIC_CODE +'lib/modules/service_manager.js', IOTRONIC_CODE +'lib/modules/vnet_iotronic_manager.js', IOTRONIC_CODE +'lib/modules/plugin_manager.js', @@ -129,9 +128,7 @@ var genApiDocumentation = function (){ }); } - - - + }; @@ -234,7 +231,7 @@ if (argv.i != undefined && argv.e != undefined){ https_enable = nconf.get('config:server:https:enable'); https_key = nconf.get('config:server:https:key'); https_cert = nconf.get('config:server:https:cert'); - docs_path = nconf.get('config:server:docs:path'); + docs_path = nconf.get('config:server:docs:embedded:path'); } catch (err) { console.log('[API-DOCS] - ' + err); diff --git a/etc/systemd/system/iotronic-standalone.service b/etc/systemd/system/iotronic-standalone.service index 171e915..540715d 100644 --- a/etc/systemd/system/iotronic-standalone.service +++ b/etc/systemd/system/iotronic-standalone.service @@ -13,8 +13,8 @@ StandardError=journal WorkingDirectory=/usr/lib/node_modules/@mdslab/iotronic-standalone Environment="NODE_PATH=/usr/lib/node_modules" Environment="IOTRONIC_HOME=/var/lib/iotronic" -ExecStart=/usr/lib/node_modules/@mdslab/iotronic-standalone/bin/server -Restart=on-abort +ExecStart= +Restart=always [Install] WantedBy=multi-user.target diff --git a/lib/init_iotronic.js b/lib/init_iotronic.js index 08318f8..27b5b4c 100644 --- a/lib/init_iotronic.js +++ b/lib/init_iotronic.js @@ -128,21 +128,23 @@ var initIoTronicModules = function() { https_cert = nconf.get('config:server:https:cert'); encryptKey = nconf.get('config:server:auth:encryptKey'); auth_backend = nconf.get('config:server:auth:backend'); - - docs_enabled = nconf.get('config:server:docs:enable'); - docs_path = nconf.get('config:server:docs:path'); - docs_url = nconf.get('config:server:docs:url'); + + docs_embedded = nconf.get('config:server:docs:embedded:enable'); + docs_path = nconf.get('config:server:docs:embedded:path'); + docs_exp = nconf.get('config:server:docs:exposed:enable'); + docs_url = nconf.get('config:server:docs:exposed:url'); + docs_url_spec = nconf.get('config:server:docs:expose:url_spec'); wstun_ip = nconf.get('config:wstun:ip'); if(nconf.get('config:wstun:port_range:high') == "env" && nconf.get('config:wstun:port_range:low') == "env"){ wstun_h_port = parseInt(process.env.WSTUN_H_PORT); wstun_l_port = parseInt(process.env.WSTUN_L_PORT); - console.log("- WSTUN ENV ports range:",wstun_h_port, wstun_l_port) + logger.debug("[SYSTEM] - WSTUN port range (env):",wstun_l_port, wstun_h_port); } else { wstun_h_port = parseInt(nconf.get('config:wstun:port_range:high')); wstun_l_port = parseInt(nconf.get('config:wstun:port_range:low')); - console.log("- WSTUN CONF ports range:",wstun_h_port, wstun_l_port) + logger.debug("[SYSTEM] - WSTUN port range (conf):",wstun_l_port, wstun_h_port); } @@ -153,6 +155,7 @@ var initIoTronicModules = function() { vfs_utility = require('./modules/vfs_manager'); gpio_utility = require('./modules/gpio_manager'); nr_utility = require('./modules/nodered_manager'); + board_utility = require('./management/mng_board'); utility = require('./management/utility'); @@ -164,6 +167,7 @@ var initIoTronicModules = function() { notify = require('./management/mng_notify'); docs = require('./management/mng_docs'); wamp = require('./management/mng_wamp'); + request_utility = require('./management/mng_request'); /* @@ -250,6 +254,7 @@ var loadIoTronicModules = function(session, rest) { projects_utils = new project_utility(session, rest); users_utils = new user_utility(session, rest); nr_utils = new nr_utility(session, rest); + requests_utils = new request_utility(session, rest); response.message = "IoTronic modules successfully loaded."; response.result = "SUCCESS"; diff --git a/lib/iotronic_standalone.js b/lib/iotronic_standalone.js index f2db8bb..8219d62 100644 --- a/lib/iotronic_standalone.js +++ b/lib/iotronic_standalone.js @@ -67,19 +67,31 @@ iotronic_standalone.prototype.start = function (wamp_router_url, wamp_realm) { var cors = require('cors'); // API documentation management - if (docs_enabled == "true" || docs_enabled == true){ + if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "false" || docs_exp == false) ){ + logger.info("[API-DOCS] - API documentation system is enabled in embedded mode."); docs.genApiDocs(rest); + }else if ( (docs_embedded == "false" || docs_embedded == false) && (docs_exp == "true" || docs_exp == true) ) { + logger.info("[API-DOCS] - API documentation system is enabled in exposed mode."); + docs.exposeApiDocs(rest, null); + }else if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "true" || docs_exp == true) ) { + logger.warn("[API-DOCS] - API documentation system is disabled: both embedding and exposing system are set as enabled, choose only one of them!") + }else if ( (docs_embedded == "false" || docs_embedded == false) && (docs_exp == "false" || docs_exp == false) ) { + logger.info("[API-DOCS] - API documentation system is disabled!") } rest.get('/', function (req, res) { - if (https_enable == "true"){ - res.status(200).send("
Welcome in Iotronic-standalone!


Please visit API documentation
"); - - }else{ - res.status(200).send("
Welcome in Iotronic-standalone!


Please visit API documentation
"); + if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "false" || docs_exp == false) ){ + if (https_enable == "true"){ + link_docs = "https://" + IoTronic_IP + ":" + https_port + "/v1/iotronic-api-docs/"; + }else{ + link_docs = "http://" + IoTronic_IP + ":" + http_port + "/v1/iotronic-api-docs/"; + } + res.status(200).send("
Welcome in Iotronic-standalone!


Please visit API documentation
"); } + else if ( (docs_embedded == "false" || docs_embedded == false) && (docs_exp == "true" || docs_exp == true) ) + res.status(200).send("
Welcome in Iotronic-standalone!


Please visit API documentation
"); }); @@ -260,7 +272,7 @@ iotronic_standalone.prototype.start = function (wamp_router_url, wamp_realm) { } else { - logger.error("[SYSTEM] - SERVER IP UNDEFINED: please specify a valid network interface in settings.json"); + logger.error("[SYSTEM] - SERVER IP UNDEFINED: please specify a valid network interface or a public IP in settings.json"); logger.info('Bye!'); process.exit(); diff --git a/lib/management/mng_board.js b/lib/management/mng_board.js index f87d06d..b2bd359 100644 --- a/lib/management/mng_board.js +++ b/lib/management/mng_board.js @@ -26,9 +26,12 @@ var fs = require("fs"); var Q = require("q"); var project_utils = require('./mng_project'); +var request_utils = require('./mng_request'); var session_wamp; + + board_utils = function (session, rest) { session_wamp = session; @@ -1067,8 +1070,9 @@ board_utils = function (session, rest) { } else { - execActionOnBoard(board, action, parameters, res); - + var request_id = null; + execActionOnBoard(board, request_id, [action, parameters, res]); + } }); @@ -1139,7 +1143,6 @@ board_utils = function (session, rest) { result: '' }; - checkRequired(ApiRequired, function (check) { if (check.result == "ERROR") { @@ -1148,50 +1151,9 @@ board_utils = function (session, rest) { } else { + var subject = "/projects/"+project+"/boards/action"; - project_utils.getProjectBoards(project).then( - - function (data) { - - if(data.result == "SUCCESS"){ - - var boards_list = data.message; - - for (var i = 0; i < boards_list.length; i++) { - - (function (i) { - - var board_id = boards_list[i]["board_id"]; - - execActionOnBoard(board_id, action, parameters, false); - - if (i === (boards_list.length - 1)) { - - response.result = "SUCCESS"; - response.message = "Action is executing on boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - })(i); - } - - } else{ - - response.result = "WARNING"; - response.message = data.message; - logger.warn("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - - - - } - - ); + request_utils.batchRequest(project, subject, res, execActionOnBoard, [action, parameters, false]); } @@ -1580,9 +1542,10 @@ board_utils = function (session, rest) { checkBoardExists(board, res, function (available) { if (available.result == "SUCCESS") { - - board_utils.injectConf(board, res); - + + var request_id = null; + board_utils.injectConf(board, request_id, [res]); + }else if(available.result == "WARNING") { logger.error("[API] --> " + available.message); res.status(200).send(available); @@ -1631,61 +1594,9 @@ board_utils = function (session, rest) { result: '' }; - project_utils.getProjectBoards(project).then( - - function (data) { - - if(data.result == "SUCCESS"){ - - var boards_list = data.message; - - for (var i = 0; i < boards_list.length; i++) { - - (function (i) { - - var board_id = boards_list[i]["board_id"]; - - checkBoardAvailable(board_id, res, function (available) { - - if (available.result == "SUCCESS") { - - board_utils.injectConf(board_id, false); - - } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); - } - - }); - - - if (i === (boards_list.length - 1)) { - - response.result = "SUCCESS"; - response.message = "Injecting conf on boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - })(i); - } - - } else{ - - response.result = "WARNING"; - response.message = data.message; - logger.warn("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - - - - } - - ); + var subject = "/projects/"+project+"/boards/conf"; + request_utils.batchRequest(project, subject, res, board_utils.injectConf, [false]); }); @@ -1764,18 +1675,22 @@ var addBoardPosition = function (board, latitude, longitude, altitude, res){ }; -var execActionOnBoard = function (board, action, parameters, res) { +var execActionOnBoard = function (board_id, request_id, args) { var response = { message: {}, result: "" }; - checkBoardAvailable(board, res, function (available) { + var action = args[0]; + var parameters = args[1]; + var res = args[2]; + + checkBoardAvailable(board_id, res, function (available) { if (available.result == "SUCCESS") { - session_wamp.call('s4t.' + board + '.board.execAction', [action, parameters]).then( + session_wamp.call('s4t.' + board_id + '.board.execAction', [action, parameters]).then( function (rpc_response) { @@ -1784,23 +1699,28 @@ var execActionOnBoard = function (board, action, parameters, res) { response.message = rpc_response.message; response.result = "ERROR"; if(res != false){ + logger.error("[SYSTEM] --> Action error on board '" + board_id + "': " + response.message); res.status(500).send(response); - logger.error("[SYSTEM] --> Action error on board '" + board + "': " + response.message); } else{ - logger.debug("[SYSTEM] --> Action error on board '" + board + "': " + response.message); + + request_utils.updateResult(request_id, board_id, response.result, response.message); + } }else { + response.message = rpc_response.message; response.result = rpc_response.result; if(res != false){ - logger.info("[SYSTEM] --> Action result on board '" + board + "': " + response.message); + logger.info("[SYSTEM] --> Action result on board '" + board_id + "': " + response.message); res.status(200).send(response); } else{ - logger.debug("[SYSTEM] --> Action result on board '" + board + "': " + response.message); + + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } @@ -1810,8 +1730,20 @@ var execActionOnBoard = function (board, action, parameters, res) { ); - } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); + } + else if (available.result == "WARNING") { + + if(res != false){ + logger.warn("[API] --> " + available.message); + } + else{ + + var result_msg = "board disconnected"; + + request_utils.updateResult(request_id, board_id, available.result, result_msg); + + } + } @@ -1838,13 +1770,13 @@ var checkBoardAvailable = function (board, res, callback) { response.result = data.result; response.message = "DB checkBoardConnected error for board " + board + ": " + data.message; - logger.error("[SYSTEM] --> " + response.message); - if(res != false) + if(res != false){ + logger.error("[SYSTEM] --> " + response.message); res.status(500).send(response); + } } else { - if (data.message.length == 1) { if (data.message[0].status == 'D') { @@ -1864,22 +1796,23 @@ var checkBoardAvailable = function (board, res, callback) { } else { - - logger.error("[API] - Board " + board + " does not exist!"); - + response.result = "ERROR"; response.message = "Board " + board + " doesn't exist!"; - if(res != false) + if(res != false){ + logger.error("[API] - " + response.message); res.status(500).send(response); + } callback(response); + } } - }); + }; var checkBoardExists = function (board, res, callback) { @@ -2095,52 +2028,62 @@ board_utils.prototype.isAlive = function (result) { }; +board_utils.prototype.injectConf = function (board_id, request_id, args){ -board_utils.prototype.injectConf = function (board, res){ - - logger.info("[SYSTEM] - Injecting configuration into board '" + board + "'..."); + logger.info("[SYSTEM] - Injecting configuration into board '" + board_id + "'..."); var response = { message: '', result: '' }; - checkBoardAvailable(board, res, function (available) { + var res = args[0]; + + checkBoardAvailable(board_id, res, function (available) { if (available.result == "SUCCESS") { - createBoardConf(board, function (conf) { + createBoardConf(board_id, function (conf) { if (conf.result == "ERROR") { response.message = "Error getting board info: " + conf.message; response.result = "ERROR"; - logger.error("[SYSTEM] --> " + response.message); - if(res != false) + if(res != false){ + logger.error("[SYSTEM] --> " + response.message); res.status(500).send(response); + } } else { - session_wamp.call('s4t.'+ board + '.board.updateConf', [conf]).then( + session_wamp.call('s4t.'+ board_id + '.board.updateConf', [conf]).then( function (rpc_response) { if(rpc_response.result == "ERROR"){ - response.message = "INJECT configuration into board " + board + " failed: "+rpc_response.message; + response.message = "INJECT configuration into board " + board_id + " failed: "+rpc_response.message; response.result = "ERROR"; - logger.error("[SYSTEM] --> " + response.message); - if(res != false) + if(res != false){ + logger.error("[SYSTEM] --> " + response.message); res.status(500).send(response); + } + else + request_utils.updateResult(request_id, board_id, response.result, response.message); + } else{ - response.message = "Configuration successfully injected into the board" + board; + response.message = "Configuration successfully injected into the board" + board_id; response.result = "SUCCESS"; - logger.info("[SYSTEM] --> " + response.message); - if(res != false) + if(res != false){ + logger.info("[SYSTEM] --> " + response.message); res.status(200).send(response); + } + else + request_utils.updateResult(request_id, board_id, response.result, response.message); + } @@ -2155,7 +2098,18 @@ board_utils.prototype.injectConf = function (board, res){ }); } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); + + if(res != false){ + logger.warn("[API] --> " + available.message); + } + else{ + + var result_msg = "board disconnected"; + + request_utils.updateResult(request_id, board_id, available.result, result_msg); + + } + } }); @@ -2166,7 +2120,6 @@ board_utils.prototype.injectConf = function (board, res){ }; - board_utils.prototype.exportCommands = function (session){ // Register all the module functions as WAMP RPCs diff --git a/lib/management/mng_db.js b/lib/management/mng_db.js index 866c1b4..7f33741 100644 --- a/lib/management/mng_db.js +++ b/lib/management/mng_db.js @@ -1405,7 +1405,6 @@ db_utils.prototype.getProjectBoards = function (project, callback) { }; - //Function to get the IoTronic project's boards db_utils.prototype.getProjectUsers = function (project, callback) { var connection = conn(); @@ -1435,6 +1434,229 @@ db_utils.prototype.getProjectUsers = function (project, callback) { +db_utils.prototype.getGlobalRequestsList = function (callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("SELECT * FROM requests", function (err, result) { + + if (err != null) { + response.message = err; + response.result = "ERROR"; + logger.error(response.result + " - " + err); + disconn(connection); + callback(response); + } + else{ + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + + }); + +}; + + +db_utils.prototype.getRequest = function (request_id, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("SELECT * FROM requests WHERE id_request='"+request_id+"'", function (err, result) { + + if (err != null) { + response.message = err; + response.result = "ERROR"; + logger.error(response.result + " - " + err); + disconn(connection); + callback(response); + } + else{ + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + + }); + +}; + + +db_utils.prototype.getRequestResults = function (request_id, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("SELECT board_id, result, message, timestamp FROM results WHERE request_id='"+request_id+"'", function (err, result) { + + if (err != null) { + response.message = err; + response.result = "ERROR"; + logger.error(response.result + " - " + err); + disconn(connection); + callback(response); + } + else{ + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + + }); + +}; + + +db_utils.prototype.getProjectRequestsList = function (project_id, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("SELECT id_request, subject, result, timestamp FROM requests WHERE project_id='"+project_id+"'", function (err, result) { + + if (err != null) { + response.message = err; + response.result = "ERROR"; + logger.error(response.result + " - " + err); + disconn(connection); + callback(response); + } + else{ + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + + }); + +}; + + +//Function to create a new IoTronic request +db_utils.prototype.insertRequest = function (request_id, project, subject, req_result, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("INSERT INTO requests (id_request, project_id, subject, result) VALUES (" + mysql.escape(request_id) + " ," + mysql.escape(project) + " , " + mysql.escape(subject) + " , " + mysql.escape(req_result) + ")", function (err, result) { + if (err != null) { + response.message = err; + response.result = "ERROR"; + disconn(connection); + callback(response); + } else { + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + }); +}; + + +//Function to insert a new IoTronic request result +db_utils.prototype.insertRequestResult = function (request_id, board_id, result, message, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("INSERT INTO results (request_id, board_id, result, message) VALUES (" + mysql.escape(request_id) + " ," + mysql.escape(board_id) + " , " + mysql.escape(result) + " , " + mysql.escape(message) + ")", function (err, result) { + if (err != null) { + response.message = err; + response.result = "ERROR"; + disconn(connection); + callback(response); + } else { + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + }); +}; + + +//Function to update an IoTronic request +db_utils.prototype.updateRequestStatus = function (request_id, result, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("UPDATE requests SET result = '" + result + "' WHERE id_request ='" + request_id +"'", function (err, result) { + if (err != null) { + response.result = "ERROR"; + response.message = "Error updating request: " + err; + disconn(connection); + callback(response); + } else { + response.result = "SUCCESS"; + response.message = result; + disconn(connection); + callback(response); + } + }) +}; + + +//Function to update an IoTronic request result +db_utils.prototype.updateResultStatus = function (request_id, board_id, result, message, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("UPDATE results SET result = '" + result + "', message = "+mysql.escape(message)+" WHERE request_id ='" + request_id +"' AND board_id ='" + board_id +"'", function (err, result) { + if (err != null) { + response.result = "ERROR"; + response.message = "Error updating request result: " + err; + disconn(connection); + callback(response); + } else { + response.result = "SUCCESS"; + response.message = result; + disconn(connection); + callback(response); + } + }) +}; + +//Function to delete an IoTronic request +db_utils.prototype.deleteRequest = function (request_id, callback) { + var connection = conn(); + var response = { + message: '', + result: '' + }; + connection.query("DELETE FROM requests WHERE id_request='" + request_id +"'", function (err, result) { + if (err != null) { + response.message = err; + response.result = "ERROR"; + disconn(connection); + callback(response); + } else { + response.message = result; + response.result = "SUCCESS"; + disconn(connection); + callback(response); + } + }); +}; + + + /////////////////////////////////////////// // USERS MANAGEMENT // /////////////////////////////////////////// diff --git a/lib/management/mng_docs.js b/lib/management/mng_docs.js index 53cae3d..c9565f3 100644 --- a/lib/management/mng_docs.js +++ b/lib/management/mng_docs.js @@ -87,6 +87,7 @@ var genApiDocumentation = function (rest){ __dirname+'/mng_user.js', __dirname+'/mng_layout.js', __dirname+'/mng_project.js', + __dirname+'/mng_request.js', './lib/modules/service_manager.js', './lib/modules/vnet_iotronic_manager.js', './lib/modules/plugin_manager.js', @@ -110,45 +111,66 @@ var exposeApiDocumentation = function (rest, swaggerSpec){ logger.info("[API-DOCS] - Exposing API documentaion..."); - if (https_enable == "true"){ - link_docs = "https://" + IoTronic_IP + ":" + https_port + "/v1/iotronic-api-docs/"; - }else{ - link_docs = "http://" + IoTronic_IP + ":" + http_port + "/v1/iotronic-api-docs/"; - } + if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "false" || docs_exp == false) ) + if (https_enable == "true"){ + link_docs = "https://" + IoTronic_IP + ":" + https_port + "/v1/iotronic-api-docs/"; + }else{ + link_docs = "http://" + IoTronic_IP + ":" + http_port + "/v1/iotronic-api-docs/"; + } + + // serve swagger rest.get('/v1/iotronic-swagger.json', function(req, res) { + res.setHeader('Content-Type', 'application/json'); - res.status(200).send(swaggerSpec); + + if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "false" || docs_exp == false) ) + res.status(200).send(swaggerSpec); + else if ( (docs_embedded == "false" || docs_embedded == false) && (docs_exp == "true" || docs_exp == true) ) + res.status(200).redirect(docs_url_spec); + + }); rest.get('/v1/', function (req, res) { - if (https_enable == "true"){ - res.status(200).redirect(link_docs); - }else{ - res.status(200).redirect(link_docs); - } + if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "false" || docs_exp == false) ) + if (https_enable == "true"){ + res.status(200).redirect(link_docs); + }else{ + res.status(200).redirect(link_docs); + } + else if ( (docs_embedded == "false" || docs_embedded == false) && (docs_exp == "true" || docs_exp == true) ) + res.status(200).redirect(docs_url); + + - }); - - // swagger-ui web-api VERSION - rest.get('/v1/iotronic-api-docs', function(req, res) { - res.status(200).sendFile(docs_path+"/index.html"); - }); - rest.get('/v1/iotronic-api-docs/swagger-ui.css', function(req, res) { - res.status(200).sendFile(docs_path+"/swagger-ui.css"); - }); - rest.get('/v1/iotronic-api-docs/swagger-ui-bundle.js', function(req, res) { - res.status(200).sendFile(docs_path+"/swagger-ui-bundle.js"); - }); - rest.get('/v1/iotronic-api-docs/swagger-ui-standalone-preset.js', function(req, res) { - res.status(200).sendFile(docs_path+"/swagger-ui-standalone-preset.js"); }); - logger.info("[API-DOCS] --> Documentation available at " + link_docs); + if ( (docs_embedded == "true" || docs_embedded == true) && (docs_exp == "false" || docs_exp == false) ){ + + // swagger-ui web-api VERSION + rest.get('/v1/iotronic-api-docs', function(req, res) { + res.status(200).sendFile(docs_path+"/index.html"); + }); + rest.get('/v1/iotronic-api-docs/swagger-ui.css', function(req, res) { + res.status(200).sendFile(docs_path+"/swagger-ui.css"); + }); + rest.get('/v1/iotronic-api-docs/swagger-ui-bundle.js', function(req, res) { + res.status(200).sendFile(docs_path+"/swagger-ui-bundle.js"); + }); + rest.get('/v1/iotronic-api-docs/swagger-ui-standalone-preset.js', function(req, res) { + res.status(200).sendFile(docs_path+"/swagger-ui-standalone-preset.js"); + }); + logger.info("[API-DOCS] --> Documentation available at " + link_docs); + } + else if ( (docs_embedded == "false" || docs_embedded == false) && (docs_exp == "true" || docs_exp == true) ) + logger.info("[API-DOCS] --> Documentation available at " + docs_url); + + }; diff --git a/lib/management/mng_project.js b/lib/management/mng_project.js index b9864a1..55d4be1 100644 --- a/lib/management/mng_project.js +++ b/lib/management/mng_project.js @@ -28,7 +28,6 @@ board_utility = require('./mng_board'); var uuid = require('node-uuid'); var Q = require("q"); - project_utils = function (session, rest) { @@ -454,8 +453,7 @@ project_utils = function (session, rest) { }); }); - - + //GET IoTronic project's users /** @@ -647,7 +645,6 @@ var getProjectBoards = function (project) { }; - project_utils.prototype.createProject = function (name, description, res) { logger.info("[PROJECT] - Creating IoTronic project: " + name); @@ -841,4 +838,4 @@ project_utils.prototype.updateProject = function (project_id, name, description, module.exports = project_utils; -module.exports.getProjectBoards = getProjectBoards; \ No newline at end of file +module.exports.getProjectBoards = getProjectBoards; diff --git a/lib/management/mng_request.js b/lib/management/mng_request.js new file mode 100644 index 0000000..024fa6a --- /dev/null +++ b/lib/management/mng_request.js @@ -0,0 +1,530 @@ +//############################################################################### +//## +//# Copyright (C) 2017 Nicola Peditto +//## +//# Licensed under the Apache License, Version 2.0 (the "License"); +//# you may not use this file except in compliance with the License. +//# You may obtain a copy of the License at +//## +//# http://www.apache.org/licenses/LICENSE-2.0 +//## +//# Unless required by applicable law or agreed to in writing, software +//# distributed under the License is distributed on an "AS IS" BASIS, +//# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +//# See the License for the specific language governing permissions and +//# limitations under the License. +//## +//############################################################################### + +//service logging configuration: "request_utils" +var logger = log4js.getLogger('mng_request'); +logger.setLevel(loglevel); + +var project_utils = require('./mng_project'); + +var db_utils = require('./mng_db'); +var db = new db_utils; + +var Q = require("q"); +var uuid = require('node-uuid'); + +REQUESTS = {}; + + +request_utils = function (session, rest) { + + + // IoTronic request management APIs + //--------------------------------------------------------------------------------------------------- + + //GET global requests list + /** + * @swagger + * /v1/requests/: + * get: + * tags: + * - Requests + * description: It returns IoTronic requests list + * summary: get Iotronic requests + * produces: + * - application/json + * responses: + * 200: + * description: Requests list of Iotronic + * properties: + * result: + * type: string + * description: "SUCCESS" + * message: + * type: array + * description: "List of requests" + * items: + * title: request info + * type: object + * properties: + * id_request: + * type: string + * description: "The IoTronic request ID" + * project_id: + * type: string + * description: "The IoTronic project ID" + * subject: + * type: string + * description: "Batch API called" + * result: + * type: string + * description: "Request result ['completed' | 'pending']" + * timestamp: + * type: string + * description: "Timestamp of the latest request update" + * 403: + * description: "Wrong, expired or not specified token in request header." + * 500: + * description: "API specific error message." + */ + rest.get('/v1/requests/', function (req, res) { + + logger.info("[API] - Global requests list called - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); + + var response = { + message: '', + result: '' + }; + + db.getGlobalRequestsList(function (data) { + + if (data.result == "ERROR") { + response.message = "Error getting global requests list: " + data.message; + response.result = "ERROR"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } else { + res.status(200).send(data); + } + + }); + + }); + + + //GET IoTronic request results + /** + * @swagger + * /v1/requests/{request}: + * get: + * tags: + * - Requests + * description: It returns IoTronic request results + * summary: get request results + * parameters: + * - in: path + * name: request + * required: true + * schema: + * type: string + * description: "The IoTronic request ID" + * produces: + * - application/json + * responses: + * 200: + * description: "IoTronic request results" + * properties: + * result: + * type: string + * description: "SUCCESS" + * message: + * type: object + * properties: + * board_id: + * type: string + * description: "Batch API called" + * result: + * type: string + * description: "Iotronic request result ['SUCCESS' | 'ERROR' | 'WARNING']" + * message: + * type: string + * description: "Iotronic result message" + * timestamp: + * type: string + * description: "Timestamp of the latest request update" + * 403: + * description: "Wrong, expired or not specified token in request header." + * 500: + * description: "API specific error message." + */ + rest.get('/v1/requests/:request', function (req, res) { + + logger.info("[API] - Get request results - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); + + var response = { + message: '', + result: '' + }; + + var request = req.params.request; + + db.getRequestResults(request, function (data) { + + if (data.message[0] === undefined) { + response.result = "ERROR"; + response.message = "IoTronic request '" + request + "' does not exist!"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } + else { + + if (data.result == "ERROR") { + response.message = "Error getting request results: " + data.message; + response.result = "ERROR"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } else { + response.message = data.message; + response.result = "SUCCESS"; + logger.info("[REQUEST] --> Results of the request '"+request+"': " + JSON.stringify(response.message)); + res.status(200).send(response); + + } + + } + + }); + + }); + + + //GET project requests list + /** + * @swagger + * /v1/projects/{project}/requests: + * get: + * tags: + * - Requests + * description: It returns IoTronic project's requests list + * summary: get project's requests + * produces: + * - application/json + * responses: + * 200: + * description: Requests list of a project + * properties: + * result: + * type: string + * description: "SUCCESS" + * message: + * type: array + * description: "List of requests" + * items: + * title: request info + * type: object + * properties: + * id_request: + * type: string + * description: "The IoTronic request ID" + * subject: + * type: string + * description: "Batch API called" + * result: + * type: string + * description: "Request result ['completed' | 'pending']" + * timestamp: + * type: string + * description: "Timestamp of the latest request update" + * 403: + * description: "Wrong, expired or not specified token in request header." + * 500: + * description: "API specific error message." + */ + rest.get('/v1/projects/:project/requests', function (req, res) { + + logger.info("[API] - Project requests list called - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); + + var project = req.params.project; + + var response = { + message: '', + result: '' + }; + + db.getProjectRequestsList(project, function (data) { + + if (data.result == "ERROR") { + response.message = "Error getting project requests list: " + data.message; + response.result = "ERROR"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } else { + res.status(200).send(data); + } + + }); + + }); + + + //DELETE IoTronic request + /** + * @swagger + * /v1/requests/{request}: + * delete: + * tags: + * - Requests + * description: Delete an IoTronic request + * summary: delete IoTronic request + * parameters: + * - in: path + * name: request + * required: true + * schema: + * type: string + * description: The IoTronic request ID + * produces: + * - application/json + * responses: + * 200: + * $ref: "#/definitions/IoTronicResponse" + * 403: + * description: "Wrong, expired or not specified token in request header." + * 500: + * description: "API specific error message." + */ + rest.delete('/v1/requests/:request', function (req, res) { + + logger.info("[API] - Delete IoTronic request - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); + + var request_id = req.params.request; + + var response = { + message: '', + result: '' + }; + + + db.getRequest(request_id, function (data) { + + if (data.result == "ERROR") { + response.message = "Error getting request details: " + data.message; + response.result = "ERROR"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } else { + + if (data.message[0] === undefined) { + response.result = "ERROR"; + response.message = "IoTronic request with ID '" + request_id + "' does not exist!"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } + else { + + db.deleteRequest(request_id, function (data) { + + if (data.result == "ERROR") { + response.message = "Error deleting request: " + data.message; + response.result = "ERROR"; + logger.error("[REQUEST] --> " + response.message); + res.status(500).send(response); + + } else { + response.message = "Request '"+request_id+"' successfully deleted!"; + response.result = "SUCCESS"; + logger.info("[REQUEST] --> " + response.message); + res.status(200).send(response); + + } + + }); + + } + + } + + }); + + + }); + + + + logger.debug("[REST-EXPORT] - IoTronic requests management APIs exposed!"); + + +}; + + + +var batchRequest = function (project, subject, res, funcAction, funcArgs) { + + var response = { + message: {}, + result: "" + }; + + insertRequest(project, subject).then( + + function (request) { + + if (request.result == "ERROR") { + + res.status(500).send(request); + + } else { + + var request_id = request.message; + + project_utils.getProjectBoards(project).then( + + function (data) { + + if(data.result == "SUCCESS"){ + + var boards_list = data.message; + + REQUESTS[request_id]=boards_list.length; + + for (var i = 0; i < boards_list.length; i++) { + + (function (i) { + + var board_id = boards_list[i]["board_id"]; + + db.insertRequestResult(request_id, board_id, "-", "-", function (data) { + + if (data.result == "ERROR") { + + logger.error("[SYSTEM] --> " + data.message); + + }else{ + + funcAction(board_id, request_id, funcArgs); + + } + + }); + + if (i === (boards_list.length - 1)) { + + response.result = "SUCCESS"; + response.message = "Action on boards of the project '" + project + "' - Request ID: " + request_id; + logger.info("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } + + })(i); + } + + } else{ + + response.result = "WARNING"; + response.message = data.message; + logger.warn("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } + + + } + + ); + + + } + + + } + + ); + + +}; + + +var insertRequest = function (project, subject) { + + var response = { + message: {}, + result: "" + }; + + var d = Q.defer(); + + var request_id = uuid.v4(); + + db.insertRequest(request_id, project, subject, "pending", function (data) { + + if (data.result == "ERROR") { + + response.message = "Error inserting new request: " + data.message; + response.result = "ERROR"; + logger.error("[PROJECT] --> " + response.message); + d.resolve(response); + + } else { + + response.result = "SUCCESS"; + response.message = request_id; //data.message; + + d.resolve(response); + + } + + }); + + + return d.promise; + +}; + + +var updateResult = function (request_id, board_id, result, message) { + + REQUESTS[request_id] = REQUESTS[request_id] - 1; + + db.updateResultStatus(request_id, board_id, result, message, function (data) { + + if (data.result == "ERROR") { + + logger.error("[SYSTEM] --> " + data.message); + + } else { + + logger.debug("[SYSTEM] --> Action result on board '" + board_id + "': " + message); + + if (REQUESTS[request_id] == 0) { + + db.updateRequestStatus(request_id, "completed", function (data) { + + if (data.result == "ERROR") { + + logger.error("[SYSTEM] --> " + data.message); + + } + + delete REQUESTS[request_id]; + + + }); + + } + + } + + }); + +}; + + + + + +module.exports = request_utils; +module.exports.insertRequest = insertRequest; +module.exports.updateResult = updateResult; +module.exports.batchRequest = batchRequest; \ No newline at end of file diff --git a/lib/modules/driver_manager.js b/lib/modules/driver_manager.js index aee82a2..4590ef2 100644 --- a/lib/modules/driver_manager.js +++ b/lib/modules/driver_manager.js @@ -48,7 +48,7 @@ driver_utils = function (session, rest) { * /v1/drivers/: * get: * tags: - * - Drivers + * - Drivers (experimental) * description: It returns IoTronic drivers list * summary: get IoTronic projects list * produces: @@ -120,7 +120,7 @@ driver_utils = function (session, rest) { * /v1/boards/{board}/drivers: * get: * tags: - * - Drivers + * - Drivers (experimental) * description: It returns IoTronic user-drivers list in a board * summary: get IoTronic drivers list in a board * parameters: @@ -202,7 +202,7 @@ driver_utils = function (session, rest) { * /v1/drivers/: * post: * tags: - * - Drivers + * - Drivers (experimental) * description: create new IoTronic user-driver * summary: create IoTronic driver * produces: @@ -274,7 +274,7 @@ driver_utils = function (session, rest) { * /v1/drivers/{driver}: * delete: * tags: - * - Drivers + * - Drivers (experimental) * description: Delete an IoTronic user-driver * summary: delete IoTronic driver * parameters: @@ -311,7 +311,7 @@ driver_utils = function (session, rest) { * /v1/boards/{board}/drivers: * put: * tags: - * - Drivers + * - Drivers (experimental) * description: Injects an IoTronic user-driver ('sync' or 'async' type) in a board * summary: inject driver in a board * parameters: @@ -398,7 +398,7 @@ driver_utils = function (session, rest) { * /v1/boards/{board}/drivers/{driver}: * delete: * tags: - * - Drivers + * - Drivers (experimental) * description: Remove an IoTronic user-driver from a board * summary: remove driver from board * parameters: @@ -455,7 +455,7 @@ driver_utils = function (session, rest) { * /v1/boards/{board}/drivers/read: * post: * tags: - * - Drivers + * - Drivers (experimental) * description: Execute driver read operation on a board * summary: execute driver read operations on a board * produces: @@ -553,7 +553,7 @@ driver_utils = function (session, rest) { * /v1/boards/{board}/drivers/write: * post: * tags: - * - Drivers + * - Drivers (experimental) * description: Execute driver write operation on a board * summary: execute driver write operations on a board * produces: @@ -655,7 +655,7 @@ driver_utils = function (session, rest) { * /v1/boards/{board}/drivers/{driver}/action: * post: * tags: - * - Drivers + * - Drivers (experimental) * description: Execute driver operations on a board * summary: execute driver operations on a board * produces: diff --git a/lib/modules/nodered_manager.js b/lib/modules/nodered_manager.js index 798234b..550b86f 100644 --- a/lib/modules/nodered_manager.js +++ b/lib/modules/nodered_manager.js @@ -25,6 +25,7 @@ var fs = require('fs'); var db_utils = require('./../management/mng_db'); var db = new db_utils; var board_utility = require('./../management/mng_board'); +var project_utils = require('./../management/mng_project'); var session_wamp; @@ -117,6 +118,151 @@ nodered_utils = function (session, rest) { + rest.get('/v1/boards/:board/nodered/flows', function (req, res) { + + var board = req.params.board; + + logger.info("[API] - Node-RED board flows - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); + + board_utility.checkBoardAvailable(board, res, function (available) { + + if (available.result == "SUCCESS") { + + var response = { + message: {}, + result: "" + }; + + session_wamp.call('s4t.' + board + '.nodered.getFlows').then( + function (rpc_response) { + + if (rpc_response.result == "ERROR") { + + response.message = rpc_response.message; + response.result = "ERROR"; + res.status(500).send(response); + logger.error("[SYSTEM] --> Get flows result on board '" + board + "': " + response.message); + + } else { + response.message = rpc_response.message; + response.result = rpc_response.result; + res.status(200).send(response); + logger.info("[SYSTEM] --> Get flows result on board '" + board + "': " + response.message); + + } + + } + + ); + + + }else if(available.result == "WARNING") { + logger.error("[API] --> " + available.message); + res.status(200).send(available); + } + + + }); + + + + + }); + + + + rest.get('/v1/projects/:project/nodered/flows', function (req, res) { + + logger.info("[API] - BATCH Get Node-RED flows - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); + + var project = req.params.project; + + var response = { + message: '', + result: '' + }; + + project_utils.getProjectBoards(project).then( + + function (data) { + + if(data.result == "SUCCESS"){ + + var boards_list = data.message; + + for (var i = 0; i < boards_list.length; i++) { + + (function (i) { + + var board_id = boards_list[i]["board_id"]; + + board_utility.checkBoardAvailable(board_id, res, function (available) { + + if (available.result == "SUCCESS") { + + session_wamp.call('s4t.' + board_id + '.nodered.getFlows').then( + function (rpc_response) { + + if (rpc_response.result == "ERROR") { + + response.message = rpc_response.message; + response.result = "ERROR"; + //res.status(500).send(response); + logger.error("[SYSTEM] --> Get flows result on board '" + board_id + "': " + response.message); + + } else { + response.message = rpc_response.message; + response.result = rpc_response.result; + //res.status(200).send(response); + logger.info("[SYSTEM] --> Get flows result on board '" + board_id + "': " + response.message); + + } + + } + + ); + + } else if (available.result == "WARNING") { + logger.warn("[API] --> " + available.message); + } + + + }); + + + if (i === (boards_list.length - 1)) { + + response.result = "SUCCESS"; + response.message = "Getting Node-RED flows from boards of the project '" + project + "'!"; + logger.info("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } + + })(i); + } + + } else{ + + response.result = "WARNING"; + response.message = data.message; + logger.warn("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } + + + + + } + + ); + + + + }); + + logger.debug("[REST-EXPORT] - Node-RED's APIs exposed!"); //--------------------------------------------------------------------------------------------------- diff --git a/lib/modules/plugin_manager.js b/lib/modules/plugin_manager.js index d4f9963..83c11e3 100644 --- a/lib/modules/plugin_manager.js +++ b/lib/modules/plugin_manager.js @@ -27,7 +27,8 @@ var md5 = require('md5'); var db_utils = require('./../management/mng_db'); var db = new db_utils; var board_utility = require('./../management/mng_board'); -var project_utils = require('./../management/mng_project'); +var request_utils = require('./../management/mng_request'); + var session_wamp; @@ -580,6 +581,11 @@ plugin_utils = function (session, rest) { var board = req.params.board; + var response = { + message: '', + result: '' + }; + board_utility.checkBoardAvailable(board, res, function (available){ if(available.result == "SUCCESS"){ @@ -588,21 +594,36 @@ plugin_utils = function (session, rest) { var onboot = req.body.onboot; var force = req.body.force; - var ApiRequired= {"plugin":plugin, "onboot":onboot}; + if ( (onboot != "true" && onboot != "false") || (force != "true" && force != "false")){ - board_utility.checkRequired(ApiRequired, function (check){ + response.message = "Check 'onboot' and 'force' paramters [ true | false ]"; + response.result = "ERROR"; + logger.error("[PLUGIN] --> " + response.message); + res.status(500).send(response); - if(check.result == "ERROR"){ - res.status(500).send(check); + }else{ - }else { + var ApiRequired= {"plugin":plugin, "onboot":onboot}; + + board_utility.checkRequired(ApiRequired, function (check){ + + if(check.result == "ERROR"){ + + res.status(500).send(check); + + }else { + + //plugin_utils.injectPlugin(board, plugin, onboot, force, res); + plugin_utils.injectPlugin(board, null, [plugin, onboot, force, res]); + + } + + }); + + } - plugin_utils.injectPlugin(board, plugin, onboot, force, res); - - } - }); }else if(available.result == "WARNING") { @@ -676,120 +697,75 @@ plugin_utils = function (session, rest) { var onboot = req.body.onboot; var force = req.body.force; - var ApiRequired= {"plugin":plugin, "onboot":onboot}; + if ( (onboot != "true" && onboot != "false") || (force != "true" && force != "false")){ - board_utility.checkRequired(ApiRequired, function (check){ + response.message = "Check 'onboot' and 'force' paramters [ true | false ]"; + response.result = "ERROR"; + logger.error("[PLUGIN] --> " + response.message); + res.status(500).send(response); - if(check.result == "ERROR"){ - res.status(500).send(check); + }else{ - }else { + var ApiRequired = {"plugin":plugin, "onboot":onboot}; - //I need to read the name of the plugin from the DB - db.getPlugin(plugin, function (data) { + board_utility.checkRequired(ApiRequired, function (check){ - if (data.result == "ERROR") { - response.message = data.message; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - res.status(500).send(response); + if(check.result == "ERROR"){ - } else { + res.status(500).send(check); - console.log(data) + }else { - if (data.message[0] === undefined) { - response.message = "Plugin '" + plugin + "' does not exist in Iotronic!"; + //I need to read the name of the plugin from the DB + db.getPlugin(plugin, function (data) { + + if (data.result == "ERROR") { + response.message = data.message; response.result = "ERROR"; logger.warn("[PLUGIN] --> " + response.message); res.status(500).send(response); - } - else { - - var pluginTag = data.message[0].tag; - - if (pluginTag == "released") { - - - project_utils.getProjectBoards(project).then( - - function (data) { - - if(data.result == "SUCCESS"){ - - var boards_list = data.message; - - for (var i = 0; i < boards_list.length; i++) { - - (function (i) { - - var board_id = boards_list[i]["board_id"]; - - board_utility.checkBoardAvailable(board_id, res, function (available) { - - if (available.result == "SUCCESS") { - - plugin_utils.injectPlugin(board_id, plugin, onboot, force, false); - - } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); - } - - - }); + } else { - if (i === (boards_list.length - 1)) { - - response.result = "SUCCESS"; - response.message = "Injecting plugin "+plugin+" on boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - })(i); - } - - } else{ - - response.result = "WARNING"; - response.message = data.message; - logger.warn("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } + if (data.message[0] === undefined) { + response.message = "Plugin '" + plugin + "' does not exist in Iotronic!"; + response.result = "ERROR"; + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else { + var pluginTag = data.message[0].tag; + if (pluginTag == "released") { + var subject = "/projects/"+project+"/plugins/"+plugin; - } + request_utils.batchRequest(project, subject, res, plugin_utils.injectPlugin, [plugin, onboot, force, false]); - ); + } + else{ - } - else{ + response.message = "Plugin not released yet!"; + response.result = "ERROR"; + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); - response.message = "Plugin not released yet!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - res.status(500).send(response); + } } - } - } - - }); + }); - } - }); + } + }); + } }); @@ -855,6 +831,11 @@ plugin_utils = function (session, rest) { var board = req.params.board; + var response = { + message: "", + result: "" + }; + logger.info("[API] - Plugin Operation - " + Object.keys( req.route.methods ) + " - " + req.route.path + " - " + req.IotronicUser); board_utility.checkBoardAvailable(board, res, function (available){ @@ -864,7 +845,7 @@ plugin_utils = function (session, rest) { var plugin = req.params.plugin; var parameters = req.body.parameters; //OPTIONAL: run | call only - var operation = req.body.operation; // run | call | stop + var operation = req.body.operation; // run | call | kill | restart var ApiRequired = {"operation":operation}; @@ -875,16 +856,33 @@ plugin_utils = function (session, rest) { res.status(500).send(check); }else { - - logger.info("[PLUGIN] - Plugin operation on board "+ board +": " + operation + " plugin '" + plugin +"'"); - plugin_utils.managePlugins(board, plugin, parameters, operation, res); + if(operation != "run" && operation != "kill" && operation != "call" && operation != "restart" ){ + + response.message = "Plugin operation '" + operation + "' not supported!"; + response.result = 'ERROR'; + + logger.error("[PLUGIN] - " + response.message); + res.status(500).send(response); + + }else{ + + logger.info("[PLUGIN] - Plugin operation on board "+ board +": " + operation + " plugin '" + plugin +"'"); + + plugin_utils.managePlugins(board, null, [plugin, parameters, operation, res]); + + } + } }); + + + + }else if(available.result == "WARNING") { logger.error("[API] --> " + available.message); res.status(200).send(available); @@ -965,7 +963,7 @@ plugin_utils = function (session, rest) { var project = req.params.project; var plugin = req.params.plugin; var parameters = req.body.parameters; //OPTIONAL: run | call only - var operation = req.body.operation; // run | call | stop + var operation = req.body.operation; // run | call | stop | restart var ApiRequired = {"operation":operation}; @@ -977,77 +975,29 @@ plugin_utils = function (session, rest) { }else { - logger.info("[PLUGIN] - BATCH plugin operation on boards of the project "+ project +": " + operation + " plugin '" + plugin +"'"); - - project_utils.getProjectBoards(project).then( - - function (data) { - - if(data.result == "SUCCESS"){ - - var boards_list = data.message; - - for (var i = 0; i < boards_list.length; i++) { - - (function (i) { - - var board_id = boards_list[i]["board_id"]; - - board_utility.checkBoardAvailable(board_id, res, function (available) { - - if (available.result == "SUCCESS") { - - plugin_utils.managePlugins(board_id, plugin, parameters, operation, false); - //logger.info("[PLUGIN] --> Plugin operation on board "+ board_id); - - - } else if (available.result == "WARNING") { - logger.warn("[PLUGIN] --> " + available.message); - } - - - }); - - - if (i === (boards_list.length - 1)) { - - response.result = "SUCCESS"; - response.message = "Executing plugin operation on boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - })(i); - } - - } else{ - - response.result = "WARNING"; - response.message = data.message; - logger.warn("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } + if(operation != "run" && operation != "kill" && operation != "call" && operation != "restart" ){ + response.message = "Plugin operation '" + operation + "' not supported!"; + response.result = 'ERROR'; + logger.error("[PLUGIN] - " + response.message); + res.status(500).send(response); + }else{ - } - ); + logger.info("[PLUGIN] - BATCH plugin operation on boards of the project "+ project +": " + operation + " plugin '" + plugin +"'"); + var subject = "/projects/"+project+"/plugins/"+plugin; + request_utils.batchRequest(project, subject, res, plugin_utils.managePlugins, [plugin, parameters, operation, false]); + } } }); - - - - }); //REMOVE plugin from board @@ -1093,7 +1043,7 @@ plugin_utils = function (session, rest) { if(available.result == "SUCCESS"){ - plugin_utils.removePlugin(board, plugin, res); + plugin_utils.removePlugin(board, null, [plugin, res]); }else if(available.result == "WARNING") { logger.error("[API] --> " + available.message); @@ -1149,62 +1099,10 @@ plugin_utils = function (session, rest) { result: '' }; - project_utils.getProjectBoards(project).then( - - function (data) { - - if(data.result == "SUCCESS"){ - - var boards_list = data.message; - - for (var i = 0; i < boards_list.length; i++) { - (function (i) { - - var board_id = boards_list[i]["board_id"]; - - board_utility.checkBoardAvailable(board_id, res, function (available) { - - if (available.result == "SUCCESS") { - - plugin_utils.removePlugin(board_id, plugin, false); - - } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); - } - - - }); - - - if (i === (boards_list.length - 1)) { - - response.result = "SUCCESS"; - response.message = "Removing plugin "+plugin+" from boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - })(i); - } - - } else{ - - response.result = "WARNING"; - response.message = data.message; - logger.warn("[PROJECT] --> " + response.message); - res.status(200).send(response); - - } - - - - - } - - ); + var subject = "/projects/"+project+"/plugins/"+plugin; + request_utils.batchRequest(project, subject, res, plugin_utils.removePlugin, [plugin, false]); }); @@ -1302,7 +1200,6 @@ plugin_utils = function (session, rest) { }); - //TAG plugin /** * @swagger @@ -1815,828 +1712,1017 @@ plugin_utils.prototype.destroyPlugin = function (plugin, res) { }; - -plugin_utils.prototype.injectPlugin = function (board, plugin, autostart, force, res) { - - logger.info("[PLUGIN] - Injecting plugin '" + plugin + "' into the board '" + board + "'..."); +//plugin_utils.prototype.injectPlugin = function (board, plugin, autostart, force, res) { +plugin_utils.prototype.injectPlugin = function (board, request_id, args) { var response = { message: '', result: '' }; - //I need to read the name of the plugin from the DB - db.getPlugin(plugin, function (data) { - - if (data.result == "ERROR") { - response.message = data.message; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + var plugin = args[0]; + var autostart = args[1]; + var force = args[2]; + var res = args[3]; - } else { - if (data.message[0] === undefined) { - response.message = "Plugin '"+plugin+"' does not exist in Iotronic!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); - } - else { + board_utility.checkBoardAvailable(board, res, function (available) { - var pluginId = data.message[0].id; + if (available.result == "SUCCESS") { - var pluginName = data.message[0].name; - var pluginCode = data.message[0].code; + if(res != false) + logger.info("[PLUGIN] - Injecting plugin '" + plugin + "' into the board '" + board + "'..."); - var pluginChecksum = data.message[0].checksum; - var pluginTag = data.message[0].tag; - var pluginParameters = data.message[0].defaults; + //I need to read the name of the plugin from the DB + db.getPlugin(plugin, function (data) { - var pluginBundle = data.message[0]; + if (data.result == "ERROR") { + response.message = data.message; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - if(pluginTag == "released"){ + } else { - var checksum = md5(pluginCode); + if (data.message[0] === undefined) { + response.message = "Plugin '"+plugin+"' does not exist in Iotronic!"; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + } + else { - if(pluginChecksum === checksum){ + var pluginId = data.message[0].id; - //check if the plugin is still injected - db.getInjectedPlugin(pluginId, board, function (data) { + var pluginName = data.message[0].name; + var pluginCode = data.message[0].code; - if (data.result == "ERROR") { + var pluginChecksum = data.message[0].checksum; + var pluginTag = data.message[0].tag; + var pluginParameters = data.message[0].defaults; - response.message = data.message; - response.result = "ERROR"; - logger.error("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + var pluginBundle = data.message[0]; - } else { + if(pluginTag == "released"){ - if(data.message.length != 0 && (force == false || force == "false")){ + var checksum = md5(pluginCode); - if(res != false){ + if(pluginChecksum === checksum){ - response.message = "Plugin " + pluginName + " already injected!"; - response.result = "WARNING"; - logger.warn("[PLUGIN] --> " + response.message); - res.status(200).send(response); + //check if the plugin is still injected + db.getInjectedPlugin(pluginId, board, function (data) { - } else{ + if (data.result == "ERROR") { - response.message = "Plugin '" + pluginName + "' already injected in "+board+" board!"; - response.result = "WARNING"; - logger.warn("[PLUGIN] --> " + response.message); + response.message = data.message; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - } + } else { + if(data.message.length != 0 && (force == false || force == "false")){ - }else{ + if(res != false){ - if(res != false) - logger.debug("[PLUGIN] --> Calling injectplugin RPC with name = '" + pluginName + "' onboot = '" + autostart + "' - force = '" + force + "' code: \n" + pluginCode + - "\n\nwith the following default parameters:\n"+pluginParameters); + response.message = "Plugin " + pluginName + " already injected!"; + response.result = "WARNING"; + logger.warn("[PLUGIN] --> " + response.message); + res.status(200).send(response); - //Now I can perform the RPC call - session_wamp.call('s4t.'+ board + '.plugin.inject', [JSON.stringify(pluginBundle) , autostart, force]).then( + } else{ - function (rpc_response) { + response.message = "Plugin '" + pluginName + "' already injected in "+board+" board!"; + response.result = "WARNING"; + request_utils.updateResult(request_id, board, response.result, response.message); - if(rpc_response.result == "ERROR"){ - response.message = "INJECT plugin " + pluginName + " failed: "+rpc_response.message; - response.result = "ERROR"; - logger.error("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); } - else{ - - - if( data.message.length != 0 && (force == true || force == "true") ){ - - //logger.warn("[PLUGIN] --> Plugin '" + pluginName + "' overwritten ! Updating..."); - db.updatePluginStatus(board, pluginName, "injected", function (out) { - if(out.result=="ERROR"){ - response.message = "Plugin '" + pluginName + "' updating error: "+out.message; - response.result = "ERROR"; - logger.error("[PLUGIN] ----> " + response.message); - if(res != false) - res.status(500).send(response); - }else{ - if(res != false){ - - response.message = "Plugin '" + pluginName+"' successfully overwritten!"; - response.result = "SUCCESS"; - logger.info("[PLUGIN] ----> " + response.message); - res.status(200).send(response); + }else{ - } else{ + if(res != false) + logger.debug("[PLUGIN] --> Calling injectplugin RPC with name = '" + pluginName + "' onboot = '" + autostart + "' - force = '" + force + "' code: \n" + pluginCode + + "\n\nwith the following default parameters:\n"+pluginParameters); - response.message = "Plugin '" + pluginName + "' successfully overwritten on "+board+" board!"; - response.result = "SUCCESS"; - logger.info("[PLUGIN] --> " + response.message); + //Now I can perform the RPC call + session_wamp.call('s4t.'+ board + '.plugin.inject', [JSON.stringify(pluginBundle) , autostart, force]).then( - } + function (rpc_response) { + if(rpc_response.result == "ERROR"){ + response.message = "INJECT plugin " + pluginName + " failed: "+rpc_response.message; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); } + } + else{ - }); - }else if(data.message.length == 0 ){ + if( data.message.length != 0 && (force == true || force == "true") ){ - db.insertInjectedPlugin(board, pluginName, function (out) { + //logger.warn("[PLUGIN] --> Plugin '" + pluginName + "' overwritten ! Updating..."); - if(out.result=="ERROR"){ - response.message = "Plugin '" + pluginName + "' injection failed: "+out.message; - response.result = "ERROR"; - logger.error("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); - }else{ + db.updatePluginStatus(board, pluginName, "injected", function (out) { + if(out.result=="ERROR"){ + response.message = "Plugin '" + pluginName + "' updating error: "+out.message; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] ----> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - if(res != false){ + }else{ - response.message = "Plugin '" + pluginName + "' successfully injected!"; - response.result = "SUCCESS"; - logger.info("[PLUGIN] --> " + response.message); - res.status(200).send(response); + if(res != false){ - } else{ + response.message = "Plugin '" + pluginName+"' successfully overwritten!"; + response.result = "SUCCESS"; + logger.info("[PLUGIN] ----> " + response.message); + res.status(200).send(response); - response.message = "Plugin '" + pluginName + "' successfully injected on "+board+" board!"; - response.result = "SUCCESS"; - logger.info("[PLUGIN] --> " + response.message); + } else{ - } + response.message = "Plugin '" + pluginName + "' successfully overwritten on "+board+" board!"; + response.result = "SUCCESS"; + request_utils.updateResult(request_id, board, response.result, response.message); + + } + + } + + }); + }else if(data.message.length == 0 ){ + + db.insertInjectedPlugin(board, pluginName, function (out) { + + if(out.result=="ERROR"){ + response.message = "Plugin '" + pluginName + "' injection failed: "+out.message; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + }else{ + + if(res != false){ + + response.message = "Plugin '" + pluginName + "' successfully injected!"; + response.result = "SUCCESS"; + logger.info("[PLUGIN] --> " + response.message); + res.status(200).send(response); + + } else{ + + response.message = "Plugin '" + pluginName + "' successfully injected on "+board+" board!"; + response.result = "SUCCESS"; + request_utils.updateResult(request_id, board, response.result, response.message); + + } + + + } + + }); } - }); - } + } - - } - + + } + ); + } - ); + } + }); + }else{ + + response.message = "Plugin checksum mismatch!"; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); } } - }); - - + }else{ + response.message = "Plugin not released yet!"; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - }else{ + } - response.message = "Plugin checksum mismatch!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); } - }else{ - - response.message = "Plugin not released yet!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - res.status(500).send(response); - } + }); + } else if (available.result == "WARNING") { + if(res != false){ + logger.warn("[PLUGIN] --> " + available.message); + } + else{ + var result_msg = "board disconnected"; - + request_utils.updateResult(request_id, board, available.result, result_msg); } + + } }); + + + + + }; -plugin_utils.prototype.managePlugins = function (board, plugin, pluginjson, plugin_operation, res) { +//plugin_utils.prototype.managePlugins = function (board, plugin, pluginjson, plugin_operation, res) { +plugin_utils.prototype.managePlugins = function (board, request_id, args) { var response = { message: '', result: '' }; - db.getPlugin(plugin, function (data) { - - if (data.result == "ERROR") { - response.message = data.message; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + var plugin = args[0]; + var pluginjson = args[1]; + var plugin_operation = args[2]; + var res = args[3]; - } else { + board_utility.checkBoardAvailable(board, res, function (available) { + if (available.result == "SUCCESS") { - if (data.message[0] === undefined) { + db.getPlugin(plugin, function (data) { - response.result = "ERROR"; - response.message = "Plugin does not exist in Iotronic!"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); - } - else { + if (data.result == "ERROR") { + response.message = data.message; + response.result = "ERROR"; - var plugin_name = data.message[0].name; - var plugin_checksum = data.message[0].checksum; - var plugin_type = data.message[0].type; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } - var plugin_defaults = data.message[0].defaults; + } else { - db.getInjectedPlugin(plugin, board, function (data) { + if (data.message[0] === undefined) { - var response = { - message: '', - result: '' - }; + response.result = "ERROR"; + response.message = "Plugin does not exist in Iotronic!"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } - if(data.result=="ERROR"){ + } + else { - response.message = data.message; - response.result = "ERROR"; + var plugin_name = data.message[0].name; + var plugin_checksum = data.message[0].checksum; + var plugin_type = data.message[0].type; - logger.error("[PLUGIN] --> " + JSON.stringify(response.message)); - if(res != false) - res.status(500).send(response); + var plugin_defaults = data.message[0].defaults; - }else{ + db.getInjectedPlugin(plugin, board, function (data) { + var response = { + message: '', + result: '' + }; - if(data.message.length == 0){ + if(data.result=="ERROR"){ - response.message = "Plugin '"+plugin_name+"' is not injected in the board '"+board+"' !"; - response.result = "ERROR"; - logger.error("[PLUGIN] --> " + JSON.stringify(response.message)); - if(res != false) - res.status(500).send(response); + response.message = data.message; + response.result = "ERROR"; + + if(res != false){ + logger.error("[PLUGIN] --> " + JSON.stringify(response.message)); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } + }else{ - }else{ - try { + if(data.message.length == 0){ - if(plugin_operation != "kill" && plugin_operation != "restart") + response.message = "Plugin '"+plugin_name+"' is not injected in the board '"+board+"' !"; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] --> " + JSON.stringify(response.message)); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } - if (pluginjson != "" && pluginjson != undefined){ - JSON.parse(pluginjson); + }else{ - }else{ + try { - if(res != false) - logger.debug("[PLUGIN] - Plugin parameters not specified, retrieving default parameters from DB...."); + if(plugin_operation != "kill" && plugin_operation != "restart") - pluginjson = plugin_defaults; + if (pluginjson != "" && pluginjson != undefined){ - } + JSON.parse(pluginjson); + }else{ - switch (plugin_operation) { + if(res != false) + logger.debug("[PLUGIN] - Plugin parameters not specified, retrieving default parameters from DB...."); - case 'run': + pluginjson = plugin_defaults; - if(res != false) - logger.debug("[PLUGIN] - STARTING ASYNC PLUGIN '" + plugin_name + "'..."); + } - if (pluginjson == "" || pluginjson == undefined) { - response.message = "WARNING - ASYNC PLUGIN '" + plugin_name + "' has not parameters!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); - } - else { + switch (plugin_operation) { - if(res != false) - logger.debug("[PLUGIN] --> Plugin '" + plugin_name + "' parameters:\n " + pluginjson); + case 'run': - //I need to read the category of the plugin from the DB - db.getPluginCategory(plugin_name, function (data) { + if(res != false) + logger.debug("[PLUGIN] - STARTING ASYNC PLUGIN '" + plugin_name + "'..."); + + if (pluginjson == "" || pluginjson == undefined) { - if (data.result == "ERROR") { - response.message = data.message; + response.message = "WARNING - ASYNC PLUGIN '" + plugin_name + "' has not parameters!"; response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - } else { + } + else { - var plugincategory = data.message[0].category; if(res != false) - logger.debug("[PLUGIN] --> Plugin category: " + plugincategory); + logger.debug("[PLUGIN] --> Plugin '" + plugin_name + "' parameters:\n " + pluginjson); - if (plugincategory === "async") { + //I need to read the category of the plugin from the DB + db.getPluginCategory(plugin_name, function (data) { - session_wamp.call('s4t.'+ board + '.plugin.run', [plugin_name, pluginjson, plugin_checksum]).then( + if (data.result == "ERROR") { + response.message = data.message; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - function (rpc_response) { - if (rpc_response.result == "ERROR") { + } else { - response.message = rpc_response.message; - response.result = "ERROR"; + var plugincategory = data.message[0].category; + if(res != false) + logger.debug("[PLUGIN] --> Plugin category: " + plugincategory); - if(res != false){ - logger.warn("[PLUGIN] --> Start plugin error for '" + plugin_name + "': " + JSON.stringify(response.message, null, "\t")); - res.status(500).send(response); - }else{ - logger.info("[PLUGIN] --> Start '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); - } + if (plugincategory === "async") { - db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if(res != false) - logger.info("[PLUGIN] ----> " + out.message); - }); + session_wamp.call('s4t.'+ board + '.plugin.run', [plugin_name, pluginjson, plugin_checksum]).then( - }else if (rpc_response.result == "SUCCESS"){ + function (rpc_response) { - response.message = rpc_response.message; - response.result = "SUCCESS"; + if (rpc_response.result == "ERROR") { - if(res != false){ - logger.info("[PLUGIN] --> Start plugin result for '" + plugin_name + "': " + response.message); - res.status(200).send(response); - }else{ - logger.info("[PLUGIN] --> Start '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); - } + response.message = rpc_response.message; + response.result = "ERROR"; + + db.updatePluginStatus(board, plugin_name, "failed", function (out) { + + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.warn("[PLUGIN] --> Start plugin error for '" + plugin_name + "': " + JSON.stringify(response.message, null, "\t")); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + }); + + + }else if (rpc_response.result == "SUCCESS"){ + + response.message = rpc_response.message; + response.result = "SUCCESS"; + + db.updatePluginStatus(board, plugin_name, "running", function (out) { + + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.info("[PLUGIN] --> Start plugin result for '" + plugin_name + "': " + response.message); + res.status(200).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + }); + + + }else { + + response.message = rpc_response.message; + response.result = rpc_response.result; + if(res != false){ + logger.warn("[PLUGIN] --> Running warning result for '" + plugin_name + "' plugin: " + response.message); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + } + + + }, + function (error) { - db.updatePluginStatus(board, plugin_name, "running", function (out) { + response.message = error.args[0].message; + response.result = "ERROR"; if(res != false) - logger.debug("[PLUGIN] ----> " + out.message); - }); + logger.error("[PLUGIN] --> Plugin error '" + plugin_name + "': " + JSON.stringify(response.message)); - }else { + db.updatePluginStatus(board, plugin_name, "failed", function (out) { - response.message = rpc_response.message; - response.result = rpc_response.result; - logger.warn("[PLUGIN] --> Running warning result for '" + plugin_name + "' plugin: " + response.message); - if(res != false) - res.status(500).send(response); + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.info("[PLUGIN] --> Error starting plugin '" + plugin_name + "': " + response.message); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - } + }); + } + ); - }, - function (error) { + } else { - response.message = error.args[0].message; + response.message = "Operation 'run' not supported for this plugin category!"; response.result = "ERROR"; - logger.error("[PLUGIN] --> Plugin error '" + plugin_name + "': " + JSON.stringify(response.message)); - if(res != false) + if(res != false){ + logger.warn("[PLUGIN] ----> " + response.message); res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if(res != false) - logger.info("[PLUGIN] ----> " + out.message); - }); } - ); - } else { - response.message = "Operation 'run' not supported for this plugin category!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] ----> " + response.message); - if(res != false) - res.status(500).send(response); - } + } + + + + }); } + break; - }); + case 'call': - } + if(res != false) + logger.debug("[PLUGIN] - STARTING SYNC PLUGIN '" + plugin_name + "'..."); - break; + if (pluginjson == "" || pluginjson == undefined) { + response.message = "WARNING - SYNC PLUGIN '" + plugin_name + "' has not parameters!"; + response.result = "ERROR"; - case 'call': + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - if(res != false) - logger.debug("[PLUGIN] - STARTING SYNC PLUGIN '" + plugin_name + "'..."); + } + else { - if (pluginjson == "" || pluginjson == undefined) { + if(res != false) + logger.debug("[PLUGIN] --> Plugin '" + plugin_name + "' parameters:\n " + pluginjson); - response.message = "WARNING - SYNC PLUGIN '" + plugin_name + "' has not parameters!"; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + //I need to read the category of the plugin from the DB + db.getPluginCategory(plugin_name, function (data) { - } - else { + var plugincategory = data.message[0].category; + if(res != false) + logger.debug("[PLUGIN] --> Plugin category: " + plugincategory); - if(res != false) - logger.debug("[PLUGIN] --> Plugin '" + plugin_name + "' parameters:\n " + pluginjson); + if (plugincategory === "sync") { - //I need to read the category of the plugin from the DB - db.getPluginCategory(plugin_name, function (data) { + session_wamp.call('s4t.'+ board + '.plugin.call', [plugin_name, pluginjson, plugin_checksum], {}, {receive_progress: true}).then( - var plugincategory = data.message[0].category; - if(res != false) - logger.debug("[PLUGIN] --> Plugin category: " + plugincategory); + function (rpc_response) { - if (plugincategory === "sync") { + if (rpc_response.result == "ERROR") { - session_wamp.call('s4t.'+ board + '.plugin.call', [plugin_name, pluginjson, plugin_checksum], {}, {receive_progress: true}).then( + response.message = rpc_response.message; + response.result = "ERROR"; - function (rpc_response) { + db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if (rpc_response.result == "ERROR") { + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.error("[PLUGIN] --> Executing error for '" + plugin_name + "' plugin: " + JSON.stringify(response.message, null, "\t")); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - response.message = rpc_response.message; - response.result = "ERROR"; - if(res != false){ - logger.error("[PLUGIN] --> Executing error for '" + plugin_name + "' plugin: " + JSON.stringify(response.message, null, "\t")); - res.status(500).send(response); - }else{ - logger.info("[PLUGIN] --> Executing error for '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); - } + }); + }else{ + response.message = rpc_response; + response.result = "SUCCESS"; - db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if(res != false) - logger.info("[PLUGIN] ----> " + out.message); - }); + db.updatePluginStatus(board, plugin_name, "executed", function (out) { - }else{ - response.message = rpc_response; - response.result = "SUCCESS"; + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.info("[PLUGIN] --> Executing result for '" + plugin_name + "' plugin:\n" + JSON.stringify(rpc_response, null, "\t")); + res.status(200).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - if(res != false){ - logger.info("[PLUGIN] --> Executing result for '" + plugin_name + "' plugin:\n" + JSON.stringify(rpc_response, null, "\t")); - res.status(200).send(response); - }else{ - logger.info("[PLUGIN] --> Executing result for '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); - } + }); - db.updatePluginStatus(board, plugin_name, "executed", function (out) { - if(res != false) - logger.debug("[PLUGIN] ----> " + out.message); - }); - } + } - }, - function (error) { + }, + function (error) { - response.message = error.args[0].message; - response.result = "ERROR"; + response.message = error.args[0].message; + response.result = "ERROR"; + + db.updatePluginStatus(board, plugin_name, "failed", function (out) { + + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.error("[PLUGIN] --> Executing RPC error for '" + plugin_name + "' plugin: " + JSON.stringify(response.message)); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + }); + }, + function (progress) { + logger.debug("[PLUGIN] --> Executing RPC progress result for '" + plugin_name + "' plugin: " + JSON.stringify(progress)); + } + + ); + + } else { + response.message = "Operation 'call' not supported for this plugin category!"; + response.result = "ERROR"; if(res != false){ - logger.error("[PLUGIN] --> Executing RPC error for '" + plugin_name + "' plugin: " + JSON.stringify(response.message)); + logger.warn("[PLUGIN] ----> " + response.message); res.status(500).send(response); }else{ - logger.info("[PLUGIN] --> Executing RPC error for '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); + request_utils.updateResult(request_id, board, response.result, response.message); } - - db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if(res != false) - logger.info("[PLUGIN] ----> " + out.message); - }); - - }, - function (progress) { - logger.debug("[PLUGIN] --> Executing RPC progress result for '" + plugin_name + "' plugin: " + JSON.stringify(progress)); } + }); - ); - } else { - response.message = "Operation 'call' not supported for this plugin category!"; - response.result = "ERROR"; - if(res != false) - res.status(500).send(response); - logger.warn("[PLUGIN] ----> " + response.message); } - }); + break; - } - break; + case 'kill': + if(res != false) + logger.debug("[PLUGIN] - KILLING PLUGIN '" + plugin_name + "'..."); - case 'kill': + session_wamp.call('s4t.'+ board + '.plugin.kill', [plugin_name]).then( - if(res != false) - logger.debug("[PLUGIN] - KILLING PLUGIN '" + plugin_name + "'..."); + function (rpc_response) { - session_wamp.call('s4t.'+ board + '.plugin.kill', [plugin_name]).then( + if (rpc_response.result == "ERROR") { - function (rpc_response) { + response.message = rpc_response.message; + response.result = "ERROR"; - if (rpc_response.result == "ERROR") { + if(res != false){ + logger.warn("[PLUGIN] --> Stop plugin result for '" + plugin_name + "': " + JSON.stringify(response.message, null, "\t")); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - response.message = rpc_response.message; - response.result = "ERROR"; + }else{ - if(res != false){ - logger.warn("[PLUGIN] --> Stop plugin result for '" + plugin_name + "': " + JSON.stringify(response.message, null, "\t")); - res.status(500).send(response); - }else{ - logger.info("[PLUGIN] --> Stop '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); - } + response.message = rpc_response.message; + response.result = rpc_response.result; - }else{ - response.message = rpc_response.message; - response.result = rpc_response.result; + db.updatePluginStatus(board, plugin_name, "killed", function (out) { - if(res != false){ - logger.info("[PLUGIN] --> Stop plugin result for '" + plugin_name + "': " + response.message); - res.status(200).send(response); - }else{ - logger.info("[PLUGIN] --> Stop '" + plugin_name + "' plugin result on board '"+board+"': " + response.message); - } + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.info("[PLUGIN] --> Stop plugin result for '" + plugin_name + "': " + response.message); + res.status(200).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + }); - db.updatePluginStatus(board, plugin_name, "killed", function (out) { - if(res != false) - logger.debug("[PLUGIN] ----> " + out.message); - }); - } + } - }); + }); - break; + break; - case 'restart': + case 'restart': - if(res != false) - logger.debug("[PLUGIN] - RESTARTING PLUGIN '" + plugin_name + "'..."); + if(res != false) + logger.debug("[PLUGIN] - RESTARTING PLUGIN '" + plugin_name + "'..."); - session_wamp.call('s4t.'+ board + '.plugin.restart', [plugin_name, plugin_checksum]).then( + session_wamp.call('s4t.'+ board + '.plugin.restart', [plugin_name, plugin_checksum]).then( - function (rpc_response) { + function (rpc_response) { - if (rpc_response.result == "ERROR") { + if (rpc_response.result == "ERROR") { - response.message = rpc_response.message; - response.result = "ERROR"; + response.message = rpc_response.message; + response.result = "ERROR"; + + db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if(res != false){ - logger.error("[PLUGIN] --> Restart error for '" + plugin_name + "' plugin: " + JSON.stringify(response.message, null, "\t")); - res.status(500).send(response); - }else{ - logger.info("[PLUGIN] --> Restart plugin result on board '"+board+"': " + response.message); - } + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.error("[PLUGIN] --> Restart error for '" + plugin_name + "' plugin: " + JSON.stringify(response.message, null, "\t")); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - db.updatePluginStatus(board, plugin_name, "failed", function (out) { - if(res != false) - logger.info("[PLUGIN] ----> " + out.message); - }); + }); - }else{ + }else{ - response.message = rpc_response.message; - response.result = rpc_response.result; + response.message = rpc_response.message; + response.result = rpc_response.result; - if(res != false){ - logger.info("[PLUGIN] --> Restart result for '" + plugin_name + "' plugin: " + response.message); - res.status(200).send(response); - }else{ - logger.info("[PLUGIN] --> Restart plugin result on board '"+board+"': " + response.message); + db.updatePluginStatus(board, plugin_name, "restarted", function (out) { - } + if(res != false){ + logger.debug("[PLUGIN] ----> " + out.message); + logger.info("[PLUGIN] --> Restart result for '" + plugin_name + "' plugin: " + response.message); + res.status(200).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + }); + } - db.updatePluginStatus(board, plugin_name, "restarted", function (out) { - if(res != false) - logger.debug("[PLUGIN] ----> " + out.message); }); + break; + + default: + + var response = { + message: "", + result: "" + }; + response.message = "Plugin operation '" + plugin_operation + "' not supported!"; + response.result = 'ERROR'; + + if(res != false){ + logger.error("[PLUGIN] - " + response.message); + res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); } - }); + break; - break; - default: + } - var response = { - message: "", - result: "" - }; - response.message = "Plugin operation '" + plugin_operation + "' not supported!"; - response.result = 'ERROR'; - logger.error("[PLUGIN] - " + response.message); - if(res != false) + } + catch (err) { + response.message = "Plugin config is not a JSON: " + err; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] --> " + response.message); res.status(500).send(response); + }else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - break; - + } } - } - catch (err) { - response.message = "Plugin config is not a JSON: " + err; - response.result = "ERROR"; - logger.error("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + + } - } + }); + + } - }); + } + }); + + } else if (available.result == "WARNING") { + + if(res != false){ + logger.warn("[PLUGIN] --> " + available.message); } + else{ - } + var result_msg = "board disconnected"; + request_utils.updateResult(request_id, board, available.result, result_msg); + } + + + } }); + + }; +//plugin_utils.prototype.removePlugin = function (board, plugin, res) { +plugin_utils.prototype.removePlugin = function (board, request_id, args) { -plugin_utils.prototype.removePlugin = function (board, plugin, res) { + var plugin = args[0]; + var res = args[1]; - logger.info("[PLUGIN] - REMOVING plugin '" + plugin + "' from board " + board); + if(res != false) + logger.info("[PLUGIN] - REMOVING plugin '" + plugin + "' from board " + board); var response = { message: '', result: '' }; - var pluginId; - var pluginName; - - db.getPlugin(plugin, function (data) { - - if (data.result == "ERROR") { - response.message = data.message; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); - - } else { + board_utility.checkBoardAvailable(board, res, function (available) { - if (data.message[0] === undefined) { + if (available.result == "SUCCESS") { - response.result = "ERROR"; - response.message = "Plugin does not exist in Iotronic!"; - logger.error("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + var pluginId; + var pluginName; - } - else { + db.getPlugin(plugin, function (data) { - pluginId = data.message[0].id; - pluginName = data.message[0].name; + if (data.result == "ERROR") { + response.message = data.message; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - //check if the plugin is still injected - db.getInjectedPlugin(pluginId, board, function (data) { + } else { - if (data.result == "ERROR") { + if (data.message[0] === undefined) { - response.message = data.message; response.result = "ERROR"; - logger.error("[PLUGIN] --> " + response.message); - if(res != false) + response.message = "Plugin does not exist in Iotronic!"; + if(res != false){ + logger.error("[PLUGIN] --> " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - } else { + } + else { - if(data.message.length == 0){ + pluginId = data.message[0].id; + pluginName = data.message[0].name; + //check if the plugin is still injected + db.getInjectedPlugin(pluginId, board, function (data) { - if(res != false){ + if (data.result == "ERROR") { - response.message = "Plugin '" + pluginName + "' already removed!"; - response.result = "WARNING"; - logger.warn("[PLUGIN] --> " + response.message); - res.status(200).send(response); + response.message = data.message; + response.result = "ERROR"; + if(res != false){ + logger.error("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - } else{ + } else { - response.message = "Plugin '" + pluginName + "' already removed from "+board+" board!"; - response.result = "WARNING"; - logger.warn("[PLUGIN] --> " + response.message); + if(data.message.length == 0){ - } + response.message = "Plugin '" + pluginName + "' already removed!"; + response.result = "WARNING"; - }else{ + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(200).send(response); + } else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - session_wamp.call('s4t.' + board + '.plugin.remove', [pluginName]).then( + }else{ - function (rpc_remove) { + session_wamp.call('s4t.' + board + '.plugin.remove', [pluginName]).then( - if(rpc_remove.result == "SUCCESS"){ + function (rpc_remove) { - db.deleteInjectedPlugin(board, pluginId, function (data_p) { + if(rpc_remove.result == "SUCCESS"){ - if (data_p.result == "ERROR") { - response.message = data_p.message; - response.result = "ERROR"; - logger.warn("[PLUGIN] --> " + response.message); - if(res != false) - res.status(500).send(response); + db.deleteInjectedPlugin(board, pluginId, function (data_p) { - } else { + if (data_p.result == "ERROR") { + response.message = data_p.message; + response.result = "ERROR"; + if(res != false){ + logger.warn("[PLUGIN] --> " + response.message); + res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } - if(res != false){ + } else { - response.result = "SUCCESS"; - response.message = rpc_remove.message; - logger.info("[PLUGIN] ----> " + response.message); - res.status(200).send(response); + response.result = "SUCCESS"; + response.message = rpc_remove.message; + + if(res != false){ + logger.info("[PLUGIN] ----> " + response.message); + res.status(200).send(response); + } else{ + request_utils.updateResult(request_id, board, response.result, response.message); + } + + } - } else{ - response.message = "Plugin '" + pluginName + "' successfully removed from "+board+" board!"; - response.result = "SUCCESS"; - logger.info("[PLUGIN] --> " + response.message); + }); + }else{ + + if(res != false){ + logger.warn("[PLUGIN] --> " + rpc_remove.message); + res.status(200).send(rpc_remove); } + else + request_utils.updateResult(request_id, board, rpc_remove.result, rpc_remove.message); + } + } - }); + ); - }else{ - logger.warn("[PLUGIN] --> " + rpc_remove.message); - if(res != false) - res.status(200).send(rpc_remove); + } - } - } + } - ); + }); - } } + } - }); + + }); + } else if (available.result == "WARNING") { + if(res != false){ + logger.warn("[PLUGIN] --> " + available.message); } + else{ + + var result_msg = "board disconnected"; + + request_utils.updateResult(request_id, board, available.result, result_msg); + + } + } }); + + }; @@ -2712,6 +2798,7 @@ plugin_utils.prototype.exportCommands = function (session){ }; +/* // Function used to delete all driver files during driver removing from the board function deleteFolderRecursive(path){ @@ -2730,6 +2817,7 @@ function deleteFolderRecursive(path){ } } +*/ module.exports = plugin_utils; diff --git a/lib/modules/service_manager.js b/lib/modules/service_manager.js index 09c4d23..5ad28e4 100644 --- a/lib/modules/service_manager.js +++ b/lib/modules/service_manager.js @@ -24,6 +24,8 @@ var db_utils = require('./../management/mng_db'); var db = new db_utils; var board_utility = require('./../management/mng_board'); var project_utils = require('./../management/mng_project'); +var request_utils = require('./../management/mng_request'); + var Q = require("q"); @@ -166,13 +168,9 @@ services_utils = function (session, rest) { board_utility.checkRequired(ApiRequired, function (check){ if(check.result == "ERROR"){ - res.status(500).send(check); - }else { - services_utils.createService(service_name, port, protocol, res); - } }); @@ -239,13 +237,9 @@ services_utils = function (session, rest) { board_utility.checkRequired(ApiRequired, function (check){ if(check.result == "ERROR"){ - res.status(500).send(check); - }else { - services_utils.updateService(service, service_name, port, protocol, res); - } }); @@ -358,13 +352,9 @@ services_utils = function (session, rest) { board_utility.checkRequired(ApiRequired, function (check) { if (check.result == "ERROR") { - res.status(500).send(check); - } else { - - services_utils.manageService(board, service, service_action, res); - + services_utils.manageService(board, service, service_action, res, null); } }); @@ -446,7 +436,6 @@ services_utils = function (session, rest) { var service_action = req.body.service_action; // enable | disable - if (service_action == "enable" || service_action == "disable" || service_action == "restore") { var ApiRequired = {"service_action": service_action}; @@ -454,147 +443,211 @@ services_utils = function (session, rest) { board_utility.checkRequired(ApiRequired, function (check) { if (check.result == "ERROR") { - res.status(500).send(check); - } else { + + var subject = "/projects/"+project+"/services/"+service+"/action"; - project_utils.getProjectBoards(project).then( + request_utils.insertRequest(project, subject).then( - function (data) { + function (request) { - if(data.result == "SUCCESS"){ + if (request.result == "ERROR") { - var boards_list = data.message; + res.status(500).send(request); - if(service_action == "enable"){ + } else { - db.getTunnels(function (data) { + var request_id = request.message; - if (data.result == "ERROR") { + project_utils.getProjectBoards(project).then( - response.message = "DB getTunnels error: " + data.message; - response.result = "ERROR"; - logger.error("[SERVICE] --> " + response.message); - res.status(500).send(response); + function (data) { - } else { + if(data.result == "SUCCESS"){ - var num_tun = data.message[0].num_tun; - var n_ports = (wstun_h_port - wstun_l_port + 1); - var free_ports = n_ports - num_tun; + var boards_list = data.message; - if(boards_list.length < free_ports ){ + REQUESTS[request_id]=boards_list.length; - for (var i = 0; i < boards_list.length; i++) { + if(service_action == "enable"){ - (function (i) { + db.getTunnels(function (data) { - var board_id = boards_list[i]["board_id"]; + if (data.result == "ERROR") { - board_utility.checkBoardAvailable(board_id, res, function (available) { + response.message = "DB getTunnels error: " + data.message; + response.result = "ERROR"; + logger.error("[SERVICE] --> " + response.message); + res.status(500).send(response); - if (available.result == "SUCCESS") { + request_utils.updateResult(request_id, board_id, response.result, response.message); - setTimeout(function(){ + } else { - services_utils.manageService(board_id, service, service_action, false); + var num_tun = data.message[0].num_tun; + var n_ports = (wstun_h_port - wstun_l_port + 1); + var free_ports = n_ports - num_tun; - }, i*200); + if(boards_list.length < free_ports ){ + for (var i = 0; i < boards_list.length; i++) { - } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); - } + (function (i) { - }); + var board_id = boards_list[i]["board_id"]; + db.insertRequestResult(request_id, board_id, "-", "-", function (data) { - if (i === (boards_list.length - 1)) { + if (data.result == "ERROR") { - response.result = "SUCCESS"; - response.message = "Performing "+ service_action +" action for service "+service+" on boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); + logger.error("[SYSTEM] --> " + data.message); + + }else{ + + + board_utility.checkBoardAvailable(board_id, res, function (available) { + + if (available.result == "SUCCESS") { + + setTimeout(function(){ + + services_utils.manageService(board_id, service, service_action, false, request_id); + + }, i*200); + + + } else if (available.result == "WARNING") { + + var result_msg = "board disconnected"; + //logger.warn("[API] --> " + available.message); + request_utils.updateResult(request_id, board_id, available.result, result_msg); + + } + }); + + } + + }); + + + if (i === (boards_list.length - 1)) { + + response.result = "SUCCESS"; + response.message = "Performing "+ service_action +" action for service "+service+" on boards of the project '" + project + "' - Request ID: " + request_id; + logger.info("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } + + })(i); + } + + }else{ + response.message = "No more ports available!"; + response.result = "ERROR"; + logger.error("[SERVICE] --> " + response.message); + res.status(500).send(response); } - })(i); - } - }else{ - response.message = "No more ports available!"; - response.result = "ERROR"; - logger.error("[SERVICE] --> " + response.message); - res.status(500).send(response); + } + + }); + + } + else{ + for (var i = 0; i < boards_list.length; i++) { - } + (function (i) { - }); + var board_id = boards_list[i]["board_id"]; + db.insertRequestResult(request_id, board_id, "-", "-", function (data) { - }else{ + if (data.result == "ERROR") { - for (var i = 0; i < boards_list.length; i++) { + logger.error("[SYSTEM] --> " + data.message); - (function (i) { + }else{ - var board_id = boards_list[i]["board_id"]; + board_utility.checkBoardAvailable(board_id, res, function (available) { - board_utility.checkBoardAvailable(board_id, res, function (available) { + if (available.result == "SUCCESS") { - if (available.result == "SUCCESS") { + setTimeout(function(){ - setTimeout(function(){ + services_utils.manageService(board_id, service, service_action, false, request_id); - services_utils.manageService(board_id, service, service_action, false); + }, i*200); - }, i*200); + } else if (available.result == "WARNING") { + var result_msg = "board disconnected"; + //logger.warn("[API] --> " + available.message); + request_utils.updateResult(request_id, board_id, available.result, result_msg); - } else if (available.result == "WARNING") { - logger.warn("[API] --> " + available.message); - } + } - }); + }); + + + } + + }); + + + if (i === (boards_list.length - 1)) { + response.result = "SUCCESS"; + response.message = "Performing "+ service_action +" action for service "+service+" on boards of the project '" + project + "' - Request ID: "+ request_id; + logger.info("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } - if (i === (boards_list.length - 1)) { + })(i); - response.result = "SUCCESS"; - response.message = "Performing "+ service_action +" action for service "+service+" on boards of the project '" + project + "'!"; - logger.info("[PROJECT] --> " + response.message); - res.status(200).send(response); + } } - })(i); - + + } else{ + + response.result = "WARNING"; + response.message = data.message; + logger.warn("[PROJECT] --> " + response.message); + res.status(200).send(response); + + } + + + + } - } + ); - } else{ - response.result = "WARNING"; - response.message = data.message; - logger.warn("[PROJECT] --> " + response.message); - res.status(200).send(response); - } + } + + } ); - + } }); @@ -968,7 +1021,7 @@ services_utils.prototype.deleteService = function (service_name, res) { }; -services_utils.prototype.manageService = function (board_id, service, service_action, res) { +services_utils.prototype.manageService = function (board_id, service, service_action, res, request_id) { var response = { message: '', @@ -984,10 +1037,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac getServiceInfo(service, function (service_info) { if (service_info.result == "ERROR") { - - logger.error("[SERVICE] --> getServiceInfo error: " + service_info.message); - if(res != false) + + if(res != false){ + logger.error("[SERVICE] --> getServiceInfo error: " + service_info.message); res.status(500).send(service_info.message); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { @@ -999,7 +1056,8 @@ services_utils.prototype.manageService = function (board_id, service, service_ac case 'restore': - logger.info("[SERVICE] - Restoring tunnel of '" + service_name + "' service of the board " + board_id + "..."); + if(res != false) + logger.info("[SERVICE] - Restoring tunnel of '" + service_name + "' service of the board " + board_id + "..."); db.getActiveService(service_id, board_id, function (data_p) { @@ -1007,9 +1065,13 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.result = data_p.result; response.message = "DB getActiveService error for " + service_name + ": " + data_p.message; - logger.error("[SERVICE] --> " + response.message); - if(res != false) + if(res != false){ + logger.error("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { @@ -1032,9 +1094,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac if (check_result.result == "ERROR") { response.result = check_result.result; response.message = check_result.message; - logger.error("[SERVICE] --> DB updateTunnel error for board " + board_id + ": " + response.message); - if(res != false) + + if(res != false){ + logger.error("[SERVICE] --> DB updateTunnel error for board " + board_id + ": " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { @@ -1045,9 +1112,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.message = service_msg; response.result = "SUCCESS"; - logger.info("[SERVICE] --> " + service_result.message); - if(res != false) + + if(res != false){ + logger.info("[SERVICE] --> " + service_result.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, JSON.stringify(response.message)); + } } @@ -1056,19 +1128,28 @@ services_utils.prototype.manageService = function (board_id, service, service_ac } else if (service_result.result === "WARNING") { - - logger.warn("[SERVICE] --> " + service_result.message); - if(res != false) + + if(res != false){ + logger.warn("[SERVICE] --> " + service_result.message); res.status(500).send(service_result); + } + else{ + request_utils.updateResult(request_id, board_id, service_result.result, service_result.message); + } } else { response.result = "ERROR"; response.message = "Problem exposing service: " + service_result.message; - logger.error("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.error("[SERVICE] --> " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } @@ -1079,9 +1160,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.result = "WARNING"; response.message = "The '" + service_name + "' service is not enabled!"; - logger.warn("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.warn("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } @@ -1095,7 +1181,8 @@ services_utils.prototype.manageService = function (board_id, service, service_ac case 'enable': - logger.info("[SERVICE] - Exposing '" + service_name + "' service of the board " + board_id + "..."); + if(res != false) + logger.info("[SERVICE] - Exposing '" + service_name + "' service of the board " + board_id + "..."); db.getActiveService(service_id, board_id, function (data_p) { @@ -1103,9 +1190,15 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.result = data_p.result; response.message = "DB getActiveService error for " + service_name + ": " + data_p.message; - logger.error("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.error("[SERVICE] --> " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } + } else { @@ -1123,9 +1216,15 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.message = "Service " + service_name + " already exposed!"; response.result = "WARNING"; - logger.warn("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.warn("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } + } @@ -1143,17 +1242,27 @@ services_utils.prototype.manageService = function (board_id, service, service_ac if (check_result.result == "ERROR") { response.result = check_result.result; response.message = check_result.message; - logger.error("[SERVICE] --> DB removeTunnel error for board " + board_id + ": " + response.message); - if(res != false) + if(res != false){ + logger.error("[SERVICE] --> DB removeTunnel error for board " + board_id + ": " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } + } else { response.message = service_name + " service status of board " + board_id + " updated! Please try enabling the service again!"; response.result = "SUCCESS"; - logger.info("[SERVICE] --> " + response.message); - if(res != false) + if(res != false){ + logger.info("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } + } @@ -1178,13 +1287,19 @@ services_utils.prototype.manageService = function (board_id, service, service_ac if (publicPort.result == "ERROR") { - logger.error("[SERVICE] --> getServiceInfo error: " + publicPort.message); - if(res != false) + if(res != false){ + logger.error("[SERVICE] --> getServiceInfo error: " + publicPort.message); res.status(500).send(publicPort); + } + else{ + request_utils.updateResult(request_id, board_id, publicPort.result, publicPort.message); + } + } else { - logger.debug("[SERVICE] --> Public port generated: " + publicPort.message); + if(res != false) + logger.debug("[SERVICE] --> Public port generated: " + publicPort.message); var restore = false; @@ -1200,9 +1315,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac if (check_result.result == "ERROR") { response.result = check_result.result; response.message = check_result.message; - logger.error("[SERVICE] --> DB registerTunnel error for board " + board_id + ": " + response.message); - if(res != false) + + if(res != false){ + logger.error("[SERVICE] --> DB registerTunnel error for board " + board_id + ": " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { @@ -1217,9 +1337,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.message = service_msg; response.result = "SUCCESS"; - logger.info("[SERVICE] --> " + service_result.message); - if(res != false) + + if(res != false){ + logger.info("[SERVICE] --> " + service_result.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } @@ -1231,9 +1356,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.result = "ERROR"; response.message = "Problem exposing service: " + service_result.message; - logger.info("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.info("[SERVICE] --> " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } @@ -1260,7 +1390,8 @@ services_utils.prototype.manageService = function (board_id, service, service_ac case 'disable': - logger.info("[SERVICE] - Disabling tunnel for service " + service_name + " in the board " + board_id +" ( local port = "+localport+" )"); + if(res != false) + logger.info("[SERVICE] - Disabling tunnel for service " + service_name + " in the board " + board_id +" ( local port = "+localport+" )"); db.getActiveService(service_id, board_id, function (data_p) { @@ -1268,20 +1399,28 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.result = data_p.result; response.message = "DB getActiveService error for " + service_name + ": " + data_p.message; - logger.error("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.error("[SERVICE] --> " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { - if (data_p.message[0] == undefined) { response.message = "Service " + service_name + " not exposed for the board " + board_id; response.result = "WARNING"; - logger.warn("[SERVICE] --> " + response.message); - if(res != false) + if(res != false){ + logger.warn("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { @@ -1299,17 +1438,25 @@ services_utils.prototype.manageService = function (board_id, service, service_ac if (check_result.result == "ERROR") { response.result = check_result.result; response.message = check_result.message; - logger.error("[SERVICE] --> DB removeTunnel error for board " + board_id + ": " + response.message); - if(res != false) + if(res != false){ + logger.error("[SERVICE] --> DB removeTunnel error for board " + board_id + ": " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { response.message = "Tunnel for service " + service_name + " disabled on board " + board_id + " (public port = "+publicPort+")"; response.result = "SUCCESS"; - logger.info("[SERVICE] --> " + response.message); - if(res != false) + if(res != false){ + logger.info("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } @@ -1323,9 +1470,13 @@ services_utils.prototype.manageService = function (board_id, service, service_ac response.result = "ERROR"; response.message = "Problem exposing service: " + service_result.message; - logger.info("[SERVICE] --> " + response.message); - if(res != false) + if(res != false){ + logger.info("[SERVICE] --> " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } }else if (service_result.result === "WARNING"){ @@ -1339,17 +1490,26 @@ services_utils.prototype.manageService = function (board_id, service, service_ac if (check_result.result == "ERROR") { response.result = check_result.result; response.message = check_result.message; - logger.error("[SERVICE] --> DB removeTunnel error for board " + board_id + ": " + response.message); - if(res != false) + if(res != false){ + logger.error("[SERVICE] --> DB removeTunnel error for board " + board_id + ": " + response.message); res.status(500).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } } else { response.result = "WARNING"; response.message = service_result.message.message + " - Database updated!"; - logger.info("[SERVICE] --> " + response.message); - if(res != false) + if(res != false){ + logger.info("[SERVICE] --> " + response.message); res.status(200).send(response); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } + } }); @@ -1377,9 +1537,14 @@ services_utils.prototype.manageService = function (board_id, service, service_ac default: response.result = "ERROR"; response.message = "Service action " + service_action + " is not supported! [ 'enable' | 'disable' | 'restore' ]"; - logger.warn("[SERVICE] --> " + response.message); - if(res != false) + + if(res != false){ + logger.warn("[SERVICE] --> " + response.message); res.status(500).send(response.message); + } + else{ + request_utils.updateResult(request_id, board_id, response.result, response.message); + } break; @@ -1440,7 +1605,7 @@ services_utils.prototype.restoreServices = function (result) { setTimeout(function(){ //function (board_id, service_name, service_id, service_action, res) - services_utils.manageService(board_id, data.message[key].service_id, "restore", false); + services_utils.manageService(board_id, data.message[key].service_id, "restore", false, null); }, key*500); diff --git a/lib/modules/vfs_manager.js b/lib/modules/vfs_manager.js index 23faa46..d78c27d 100644 --- a/lib/modules/vfs_manager.js +++ b/lib/modules/vfs_manager.js @@ -39,7 +39,7 @@ vfs_utils = function (session, rest) { * /v1/vfs/: * get: * tags: - * - VFS + * - VFS (experimental) * description: It returns VFS mountpoints list * summary: get IoTronic mountpoints list * produces: @@ -114,7 +114,7 @@ vfs_utils = function (session, rest) { * /v1/boards/{board}/vfs: * get: * tags: - * - VFS + * - VFS (experimental) * description: It returns mountpoints list of a board * summary: get board mountpoints list * produces: @@ -184,7 +184,7 @@ vfs_utils = function (session, rest) { * /v1/boards/{board}/vfs/mount: * post: * tags: - * - VFS + * - VFS (experimental) * description: It mounts a folder to another board. * summary: mount folder to another board * parameters: @@ -271,7 +271,7 @@ vfs_utils = function (session, rest) { * /v1/boards/{board}/vfs/unmount: * post: * tags: - * - VFS + * - VFS (experimental) * description: It unmounts a mountpoint previously mounted from a board. * summary: unmount folder from a board * parameters: @@ -357,7 +357,7 @@ vfs_utils = function (session, rest) { * /v1/boards/{board}/vfs/force-mount: * post: * tags: - * - VFS + * - VFS (experimental) * description: It forces the mounting of a folder to another board. * summary: force mounting of a folder to another board * parameters: diff --git a/package.json b/package.json index 9ad63aa..b07d318 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@mdslab/iotronic-standalone", - "version": "2.1.0", + "version": "2.1.1", "description": "IoTronic-standalone is the implementation of a personal Cloud to remote manage embedded devices (Arduino YUN/Linino One, Raspberry Pi 2/3, etc)", "main": "lib/iotronic_standalone.js", "scripts": { diff --git a/scripts/postinst b/scripts/postinst index 9e03c77..a561479 100755 --- a/scripts/postinst +++ b/scripts/postinst @@ -10,7 +10,8 @@ if [ "$DISTRO" = "14.04" ]; then # Configure init.d echo " - IoTronic init.d configuration..." - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/init.d/s4t-iotronic /etc/init.d/ + cp $NODE_PATH/@mdslab/iotronic-standalone/etc/init.d/s4t-iotronic /etc/init.d/ + chmod +x /etc/init.d/s4t-iotronic if grep -Fq "s4t-iotronic" /etc/rc.local then @@ -23,7 +24,8 @@ if [ "$DISTRO" = "14.04" ]; then # Configure Crossbar.io echo " - Crossbar.io init.d configuration..." - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/init.d/crossbar /etc/init.d/ + cp $NODE_PATH/@mdslab/iotronic-standalone/etc/init.d/crossbar /etc/init.d/ + chmod +x /etc/init.d/crossbar if grep -Fq "crossbar" /etc/rc.local then @@ -36,7 +38,8 @@ if [ "$DISTRO" = "14.04" ]; then # Configure WSTUN echo " - WSTUN init.d configuration..." - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/init.d/wstun /etc/init.d/ + cp $NODE_PATH/@mdslab/iotronic-standalone/etc/init.d/wstun /etc/init.d/ + chmod +x /etc/init.d/wstun if grep -Fq "wstun" /etc/rc.local then @@ -52,7 +55,8 @@ elif [ "$DISTRO" = "16.04" ]; then # Configure systemctl echo " - systemd configuration..." - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/systemd/system/iotronic-standalone.service /etc/systemd/system/ + cp $NODE_PATH/@mdslab/iotronic-standalone/etc/systemd/system/iotronic-standalone.service /etc/systemd/system/ + sed -i "s|ExecStart=|ExecStart=$NODE_PATH/@mdslab/iotronic-standalone/bin/server|g" /etc/systemd/system/iotronic-standalone.service chmod +x /etc/systemd/system/iotronic-standalone.service systemctl daemon-reload systemctl enable iotronic-standalone.service @@ -60,14 +64,14 @@ elif [ "$DISTRO" = "16.04" ]; then # Configure Crossbar.io echo " - Crossbar.io configuration..." mkdir -p /etc/crossbar - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/systemd/system/crossbar.service /etc/systemd/system/ + cp $NODE_PATH/@mdslab/iotronic-standalone/etc/systemd/system/crossbar.service /etc/systemd/system/ chmod +x /etc/systemd/system/crossbar.service systemctl daemon-reload systemctl enable crossbar.service # Configure WSTUN echo " - WSTUN configuration..." - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/etc/systemd/system/wstun.service /etc/systemd/system/ + cp $NODE_PATH/@mdslab/iotronic-standalone/etc/systemd/system/wstun.service /etc/systemd/system/ chmod +x /etc/systemd/system/wstun.service systemctl daemon-reload @@ -97,7 +101,7 @@ then mkdir -p /var/lib/iotronic/drivers/mountpoints/ cd /var/lib/iotronic/ - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/settings.example.json /var/lib/iotronic/settings.json + cp $NODE_PATH/@mdslab/iotronic-standalone/settings.example.json /var/lib/iotronic/settings.json mkdir -p /var/log/iotronic/ touch /var/log/iotronic/s4t-iotronic.log @@ -108,7 +112,7 @@ then echo "-->" $MYSQL_PW echo -n "MySQL configuring..." - /usr/bin/mysql -u root -p$MYSQL_PW < /usr/lib/node_modules/@mdslab/iotronic-standalone/utils/s4t-db.sql + /usr/bin/mysql -u root -p$MYSQL_PW < $NODE_PATH/@mdslab/iotronic-standalone/utils/s4t-db.sql elif [ "$rm_check" = "yes" ]; then @@ -125,7 +129,7 @@ else mkdir -p /var/lib/iotronic/drivers/mountpoints/ cd /var/lib/iotronic/ - cp /usr/lib/node_modules/@mdslab/iotronic-standalone/settings.example.json /var/lib/iotronic/settings.json + cp $NODE_PATH/@mdslab/iotronic-standalone/settings.example.json /var/lib/iotronic/settings.json mkdir -p /var/log/iotronic/ touch /var/log/iotronic/s4t-iotronic.log @@ -137,7 +141,7 @@ else sed -i "s/\"password\": \"\"/\"password\":\"$MYSQL_PW\"/g" /var/lib/iotronic/settings.json echo -n "MySQL configuring..." - /usr/bin/mysql -u root -p$MYSQL_PW < /usr/lib/node_modules/@mdslab/iotronic-standalone/utils/s4t-db.sql + /usr/bin/mysql -u root -p$MYSQL_PW < $NODE_PATH/@mdslab/iotronic-standalone/utils/s4t-db.sql fi diff --git a/settings.example.json b/settings.example.json index 12a3b15..4e85c87 100644 --- a/settings.example.json +++ b/settings.example.json @@ -29,10 +29,15 @@ "loglevel": "info" }, "docs": { - "enable": false, - "path": "", - "url":"" - + "embedded":{ + "enable": false, + "path": "" + }, + "exposed":{ + "enable": false, + "url":"", + "url_spec":"" + } }, "notifier":{ "email": { diff --git a/utils/v6-s4t-iotronic_20180515.sql b/utils/v6-s4t-iotronic_20180515.sql new file mode 100644 index 0000000..7001919 --- /dev/null +++ b/utils/v6-s4t-iotronic_20180515.sql @@ -0,0 +1,697 @@ +-- MySQL Script generated by MySQL Workbench +-- mar 15 mag 2018 16:33:46 CEST +-- Model: New Model Version: 1.0 +-- MySQL Workbench Forward Engineering + +SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; +SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; +SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; + +-- ----------------------------------------------------- +-- Schema s4t-iotronic +-- ----------------------------------------------------- +DROP SCHEMA IF EXISTS `s4t-iotronic` ; + +-- ----------------------------------------------------- +-- Schema s4t-iotronic +-- ----------------------------------------------------- +CREATE SCHEMA IF NOT EXISTS `s4t-iotronic` DEFAULT CHARACTER SET latin1 ; +USE `s4t-iotronic` ; + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`layouts` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`layouts` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`layouts` ( + `id_layout` INT NOT NULL AUTO_INCREMENT, + `model` VARCHAR(45) NULL, + `manufacturer` VARCHAR(45) NULL, + `image` VARCHAR(45) NULL, + `layout` VARCHAR(45) NOT NULL, + PRIMARY KEY (`id_layout`)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`projects` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`projects` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`projects` ( + `uuid` VARCHAR(36) NOT NULL, + `name` VARCHAR(50) NOT NULL, + `description` VARCHAR(300) NULL DEFAULT NULL, + PRIMARY KEY (`uuid`)) +ENGINE = InnoDB +AUTO_INCREMENT = 2 +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`users` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`users` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`users` ( + `uuid` VARCHAR(36) NOT NULL, + `username` VARCHAR(50) NOT NULL, + `password` VARCHAR(60) NULL DEFAULT NULL, + `email` VARCHAR(50) NOT NULL, + `first_name` VARCHAR(45) NULL DEFAULT NULL, + `last_name` VARCHAR(45) NULL DEFAULT NULL, + `latest_update` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`uuid`), + UNIQUE INDEX `username_UNIQUE` (`username` ASC)) +ENGINE = InnoDB +AUTO_INCREMENT = 2 +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`boards` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`boards` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`boards` ( + `board_id` VARCHAR(36) NOT NULL, + `label` VARCHAR(100) NOT NULL, + `session_id` VARCHAR(250) NULL DEFAULT NULL, + `status` VARCHAR(15) NULL DEFAULT NULL, + `latest_update` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `layout_id` INT NULL, + `description` VARCHAR(300) NULL DEFAULT NULL, + `net_enabled` TINYINT(1) NOT NULL, + `projects_id` VARCHAR(36) NULL, + `users_id` VARCHAR(36) NULL, + `mobile` TINYINT(1) NOT NULL, + `position_refresh_time` INT NULL, + `notify` TINYINT(1) NOT NULL, + `notify_rate` VARCHAR(45) NULL, + `notify_retry` INT NULL, + `extra` VARCHAR(600) NULL, + `state` VARCHAR(45) NOT NULL, + PRIMARY KEY (`board_id`), + INDEX `fk_boards_layout1_idx` (`layout_id` ASC), + INDEX `fk_boards_projects1_idx` (`projects_id` ASC), + INDEX `fk_boards_users1_idx` (`users_id` ASC), + CONSTRAINT `fk_boards_layout1` + FOREIGN KEY (`layout_id`) + REFERENCES `s4t-iotronic`.`layouts` (`id_layout`) + ON DELETE SET NULL + ON UPDATE CASCADE, + CONSTRAINT `fk_boards_projects1` + FOREIGN KEY (`projects_id`) + REFERENCES `s4t-iotronic`.`projects` (`uuid`) + ON DELETE SET NULL + ON UPDATE CASCADE, + CONSTRAINT `fk_boards_users1` + FOREIGN KEY (`users_id`) + REFERENCES `s4t-iotronic`.`users` (`uuid`) + ON DELETE SET NULL + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`plugin_types` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`plugin_types` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`plugin_types` ( + `id` INT NOT NULL, + `type` VARCHAR(45) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `tag_UNIQUE` (`type` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`plugin_tags` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`plugin_tags` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`plugin_tags` ( + `id` INT NOT NULL, + `tag` VARCHAR(45) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `tag_UNIQUE` (`tag` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`plugins` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`plugins` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`plugins` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(20) NOT NULL, + `category` VARCHAR(20) NOT NULL, + `version` VARCHAR(45) NOT NULL, + `checksum` VARCHAR(45) NOT NULL, + `type_id` INT NOT NULL, + `tag_id` INT NOT NULL, + `code` LONGTEXT NOT NULL, + `defaults` LONGTEXT NULL, + `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `created_at` TIMESTAMP NULL DEFAULT NULL, + `description` VARCHAR(300) NULL DEFAULT 'no description', + PRIMARY KEY (`id`, `type_id`, `tag_id`), + UNIQUE INDEX `name-ver-cat-type` (`name` ASC, `version` ASC, `category` ASC, `type_id` ASC), + INDEX `fk_plugins_plugin_type1_idx` (`type_id` ASC), + INDEX `fk_plugins_plugin_tags1_idx` (`tag_id` ASC), + CONSTRAINT `fk_plugins_plugin_type1` + FOREIGN KEY (`type_id`) + REFERENCES `s4t-iotronic`.`plugin_types` (`id`) + ON DELETE NO ACTION + ON UPDATE CASCADE, + CONSTRAINT `fk_plugins_plugin_tags1` + FOREIGN KEY (`tag_id`) + REFERENCES `s4t-iotronic`.`plugin_tags` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION) +ENGINE = InnoDB +AUTO_INCREMENT = 10 +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`plugins_injected` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`plugins_injected` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`plugins_injected` ( + `board_id` VARCHAR(36) NOT NULL, + `plugin_id` INT(11) NOT NULL, + `state` VARCHAR(20) NOT NULL, + `latest_change` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX `fk_plugins_injected_plugins1_idx` (`plugin_id` ASC), + PRIMARY KEY (`plugin_id`, `board_id`), + INDEX `fk_plugins_injected_boards1_idx` (`board_id` ASC), + CONSTRAINT `fk_plugins_injected_plugins1` + FOREIGN KEY (`plugin_id`) + REFERENCES `s4t-iotronic`.`plugins` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_plugins_injected_boards1` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`vlans` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`vlans` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`vlans` ( + `id` INT NOT NULL AUTO_INCREMENT, + `vlan_name` VARCHAR(45) NOT NULL, + `vlan_ip` VARCHAR(45) NOT NULL, + `vlan_mask` VARCHAR(45) NOT NULL, + `net_uuid` VARCHAR(45) NOT NULL, + PRIMARY KEY (`id`)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`socat_connections` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`socat_connections` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`socat_connections` ( + `id` INT NOT NULL AUTO_INCREMENT, + `id_board` VARCHAR(36) NOT NULL, + `port` INT(6) NULL, + `ip_board` VARCHAR(45) NULL, + `ip_server` VARCHAR(45) NULL, + `status` VARCHAR(45) NOT NULL, + PRIMARY KEY (`id`, `id_board`), + INDEX `fk_socat_connections_boards1_idx` (`id_board` ASC), + CONSTRAINT `fk_socat_connections_boards1` + FOREIGN KEY (`id_board`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`vlans_connection` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`vlans_connection` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`vlans_connection` ( + `id` INT NOT NULL AUTO_INCREMENT, + `id_vlan` INT NOT NULL, + `id_socat_connection` INT NOT NULL, + `ip_vlan` VARCHAR(45) NOT NULL, + PRIMARY KEY (`id`), + INDEX `fk_vlans_connection_vlans1_idx` (`id_vlan` ASC), + INDEX `fk_vlans_connection_socat_connections1_idx` (`id_socat_connection` ASC), + CONSTRAINT `fk_vlans_connection_vlans1` + FOREIGN KEY (`id_vlan`) + REFERENCES `s4t-iotronic`.`vlans` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_vlans_connection_socat_connections1` + FOREIGN KEY (`id_socat_connection`) + REFERENCES `s4t-iotronic`.`socat_connections` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`sensors` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`sensors` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`sensors` ( + `id` INT NOT NULL, + `type` VARCHAR(45) NOT NULL, + `unit` VARCHAR(45) NOT NULL, + `fabric_name` VARCHAR(45) NULL, + `model` VARCHAR(45) NULL, + PRIMARY KEY (`id`)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`sensors_on_board` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`sensors_on_board` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`sensors_on_board` ( + `id_sensor` INT NOT NULL, + `id_board` VARCHAR(36) NOT NULL, + PRIMARY KEY (`id_sensor`, `id_board`), + INDEX `fk_sensors_on_board_boards_connected1_idx` (`id_board` ASC), + CONSTRAINT `fk_sensors_on_board_sensors1` + FOREIGN KEY (`id_sensor`) + REFERENCES `s4t-iotronic`.`sensors` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_sensors_on_board_boards1` + FOREIGN KEY (`id_board`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`plugin_sensors` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`plugin_sensors` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`plugin_sensors` ( + `plugins_id` INT(11) NOT NULL, + `sensors_id` INT NOT NULL, + INDEX `fk_plugin_sensors_plugins1_idx` (`plugins_id` ASC), + INDEX `fk_plugin_sensors_sensors1_idx` (`sensors_id` ASC), + PRIMARY KEY (`plugins_id`, `sensors_id`), + CONSTRAINT `fk_plugin_sensors_plugins1` + FOREIGN KEY (`plugins_id`) + REFERENCES `s4t-iotronic`.`plugins` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_plugin_sensors_sensors1` + FOREIGN KEY (`sensors_id`) + REFERENCES `s4t-iotronic`.`sensors` (`id`) + ON DELETE NO ACTION + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`free_addresses` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`free_addresses` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`free_addresses` ( + `ip` VARCHAR(45) NOT NULL, + `vlans_id` INT NOT NULL, + `insert_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX `fk_free_addresses_vlans1_idx` (`vlans_id` ASC), + PRIMARY KEY (`ip`, `vlans_id`), + CONSTRAINT `fk_free_addresses_vlans1` + FOREIGN KEY (`vlans_id`) + REFERENCES `s4t-iotronic`.`vlans` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`drivers` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`drivers` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`drivers` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(20) NOT NULL, + `jsonschema` LONGTEXT NOT NULL, + `code` LONGTEXT NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `name_UNIQUE` (`name` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`drivers_injected` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`drivers_injected` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`drivers_injected` ( + `driver_id` INT NOT NULL, + `board_id` VARCHAR(36) NOT NULL, + `state` VARCHAR(20) NOT NULL, + `latest_change` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`driver_id`, `board_id`), + INDEX `fk_drivers_injected_boards1_idx` (`board_id` ASC), + CONSTRAINT `fk_drivers_injected_drivers1` + FOREIGN KEY (`driver_id`) + REFERENCES `s4t-iotronic`.`drivers` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_drivers_injected_boards_connected1` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`mountpoints` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`mountpoints` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`mountpoints` ( + `src_board` VARCHAR(36) NOT NULL, + `dst_board` VARCHAR(36) NOT NULL, + `src_path` VARCHAR(400) NOT NULL, + `dst_path` VARCHAR(400) NOT NULL, + `status` VARCHAR(45) NOT NULL, + PRIMARY KEY (`src_board`, `dst_board`, `src_path`, `dst_path`), + INDEX `fk_mountpoints_boards_connected1_idx` (`src_board` ASC), + INDEX `fk_mountpoints_boards_connected2_idx` (`dst_board` ASC), + CONSTRAINT `fk_mountpoints_boards1` + FOREIGN KEY (`src_board`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_mountpoints_boards2` + FOREIGN KEY (`dst_board`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`services` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`services` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`services` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(45) NOT NULL, + `port` INT NOT NULL, + `protocol` VARCHAR(10) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `name_UNIQUE` (`name` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`active_services` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`active_services` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`active_services` ( + `service_id` INT NOT NULL, + `board_id` VARCHAR(36) NOT NULL, + `public_port` INT NOT NULL, + `last_update` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `pid` INT NULL, + PRIMARY KEY (`service_id`, `board_id`, `public_port`), + INDEX `fk_active_services_services1_idx` (`service_id` ASC), + INDEX `fk_active_services_boards1_idx` (`board_id` ASC), + UNIQUE INDEX `public_port_UNIQUE` (`public_port` ASC), + CONSTRAINT `fk_active_services_services1` + FOREIGN KEY (`service_id`) + REFERENCES `s4t-iotronic`.`services` (`id`) + ON DELETE NO ACTION + ON UPDATE CASCADE, + CONSTRAINT `fk_active_services_boards1` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`coordinates` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`coordinates` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`coordinates` ( + `coordinates_id` INT NOT NULL AUTO_INCREMENT, + `board_id` VARCHAR(36) NOT NULL, + `altitude` VARCHAR(45) NOT NULL, + `longitude` VARCHAR(45) NOT NULL, + `latitude` VARCHAR(45) NOT NULL, + `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`coordinates_id`), + CONSTRAINT `fk_coordinates_boards1` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`modules` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`modules` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`modules` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(45) NOT NULL, + `description` VARCHAR(300) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `name_UNIQUE` (`name` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`active_modules` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`active_modules` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`active_modules` ( + `module_id` INT NOT NULL, + `board_id` VARCHAR(36) NOT NULL, + `latest_update` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`module_id`, `board_id`), + INDEX `fk_active_services_services1_idx` (`module_id` ASC), + INDEX `fk_active_services_boards1_idx` (`board_id` ASC), + CONSTRAINT `fk_active_services_services10` + FOREIGN KEY (`module_id`) + REFERENCES `s4t-iotronic`.`modules` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_active_services_boards10` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`flows` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`flows` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`flows` ( + `id` INT NOT NULL AUTO_INCREMENT, + `name` VARCHAR(45) NOT NULL, + `description` VARCHAR(300) NULL, + `checksum` VARCHAR(45) NOT NULL, + `code` VARCHAR(45) NOT NULL, + `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `created_at` TIMESTAMP NULL DEFAULT NULL, + PRIMARY KEY (`id`)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`flows_injected` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`flows_injected` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`flows_injected` ( + `flow_id` INT NOT NULL, + `board_id` VARCHAR(36) NOT NULL, + INDEX `fk_flows_injected_flows1_idx` (`flow_id` ASC), + PRIMARY KEY (`flow_id`, `board_id`), + INDEX `fk_flows_injected_boards1_idx` (`board_id` ASC), + CONSTRAINT `fk_flows_injected_flows1` + FOREIGN KEY (`flow_id`) + REFERENCES `s4t-iotronic`.`flows` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT `fk_flows_injected_boards1` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`requests` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`requests` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`requests` ( + `id_request` VARCHAR(36) NOT NULL, + `project_id` VARCHAR(36) NOT NULL, + `subject` VARCHAR(100) NOT NULL, + `result` VARCHAR(45) NULL DEFAULT NULL, + `timestamp` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id_request`), + INDEX `fk_requests_projects1_idx` (`project_id` ASC), + CONSTRAINT `fk_requests_projects1` + FOREIGN KEY (`project_id`) + REFERENCES `s4t-iotronic`.`projects` (`uuid`) + ON DELETE NO ACTION + ON UPDATE NO ACTION) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +-- ----------------------------------------------------- +-- Table `s4t-iotronic`.`results` +-- ----------------------------------------------------- +DROP TABLE IF EXISTS `s4t-iotronic`.`results` ; + +CREATE TABLE IF NOT EXISTS `s4t-iotronic`.`results` ( + `request_id` VARCHAR(36) NOT NULL, + `board_id` VARCHAR(36) NOT NULL, + `result` VARCHAR(45) NULL DEFAULT NULL, + `message` LONGTEXT NULL DEFAULT NULL, + `timestamp` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX `fk_results_requests1_idx` (`request_id` ASC), + INDEX `fk_results_boards1_idx` (`board_id` ASC), + PRIMARY KEY (`request_id`, `board_id`), + UNIQUE INDEX `request_board_UNIQUE` (`request_id` ASC, `board_id` ASC), + CONSTRAINT `fk_results_requests1` + FOREIGN KEY (`request_id`) + REFERENCES `s4t-iotronic`.`requests` (`id_request`) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT `fk_results_boards1` + FOREIGN KEY (`board_id`) + REFERENCES `s4t-iotronic`.`boards` (`board_id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION) +ENGINE = InnoDB +DEFAULT CHARACTER SET = utf8; + + +SET SQL_MODE=@OLD_SQL_MODE; +SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; +SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; + +-- ----------------------------------------------------- +-- Data for table `s4t-iotronic`.`layouts` +-- ----------------------------------------------------- +START TRANSACTION; +USE `s4t-iotronic`; +INSERT INTO `s4t-iotronic`.`layouts` (`id_layout`, `model`, `manufacturer`, `image`, `layout`) VALUES (1, 'YUN', 'Arduino', 'linino', 'arduino_yun'); +INSERT INTO `s4t-iotronic`.`layouts` (`id_layout`, `model`, `manufacturer`, `image`, `layout`) VALUES (2, 'server', 'generic', 'debian-like', 'server'); +INSERT INTO `s4t-iotronic`.`layouts` (`id_layout`, `model`, `manufacturer`, `image`, `layout`) VALUES (3, 'Raspberry Pi 3', 'Raspberry', 'LEDE', 'raspberry_pi'); +INSERT INTO `s4t-iotronic`.`layouts` (`id_layout`, `model`, `manufacturer`, `image`, `layout`) VALUES (4, 'Raspberry Pi 3', 'Raspberry', 'Raspbian', 'raspberry_pi'); + +COMMIT; + + +-- ----------------------------------------------------- +-- Data for table `s4t-iotronic`.`plugin_types` +-- ----------------------------------------------------- +START TRANSACTION; +USE `s4t-iotronic`; +INSERT INTO `s4t-iotronic`.`plugin_types` (`id`, `type`) VALUES (1, 'nodejs'); +INSERT INTO `s4t-iotronic`.`plugin_types` (`id`, `type`) VALUES (2, 'python'); + +COMMIT; + + +-- ----------------------------------------------------- +-- Data for table `s4t-iotronic`.`plugin_tags` +-- ----------------------------------------------------- +START TRANSACTION; +USE `s4t-iotronic`; +INSERT INTO `s4t-iotronic`.`plugin_tags` (`id`, `tag`) VALUES (1, 'released'); +INSERT INTO `s4t-iotronic`.`plugin_tags` (`id`, `tag`) VALUES (2, 'unreleased'); +INSERT INTO `s4t-iotronic`.`plugin_tags` (`id`, `tag`) VALUES (3, 'stable'); +INSERT INTO `s4t-iotronic`.`plugin_tags` (`id`, `tag`) VALUES (4, 'unstable'); + +COMMIT; + + +-- ----------------------------------------------------- +-- Data for table `s4t-iotronic`.`sensors` +-- ----------------------------------------------------- +START TRANSACTION; +USE `s4t-iotronic`; +INSERT INTO `s4t-iotronic`.`sensors` (`id`, `type`, `unit`, `fabric_name`, `model`) VALUES (1, 'temperature', '°C', 'TinkerKit', 'Thermistor'); +INSERT INTO `s4t-iotronic`.`sensors` (`id`, `type`, `unit`, `fabric_name`, `model`) VALUES (2, 'brightness', 'lux', 'TinkerKit', 'LDR'); +INSERT INTO `s4t-iotronic`.`sensors` (`id`, `type`, `unit`, `fabric_name`, `model`) VALUES (3, 'humidity', '%', 'Honeywell', 'HIH-4030'); +INSERT INTO `s4t-iotronic`.`sensors` (`id`, `type`, `unit`, `fabric_name`, `model`) VALUES (4, 'sound_detect', 'db', 'Keyes', 'HY-038'); +INSERT INTO `s4t-iotronic`.`sensors` (`id`, `type`, `unit`, `fabric_name`, `model`) VALUES (5, 'gas', 'ppm', 'Grove', 'MQ9'); +INSERT INTO `s4t-iotronic`.`sensors` (`id`, `type`, `unit`, `fabric_name`, `model`) VALUES (6, 'barometer', 'hPa', 'TinkerKit', 'mpl3115'); + +COMMIT; + + +-- ----------------------------------------------------- +-- Data for table `s4t-iotronic`.`services` +-- ----------------------------------------------------- +START TRANSACTION; +USE `s4t-iotronic`; +INSERT INTO `s4t-iotronic`.`services` (`id`, `name`, `port`, `protocol`) VALUES (1, 'SSH', 22, 'TCP'); + +COMMIT; +