aboutsummaryrefslogtreecommitdiffstats
path: root/admportal/server/router/routes
diff options
context:
space:
mode:
authorTimoney, Daniel (dt5972) <dtimoney@att.com>2017-02-15 10:37:53 -0500
committerTimoney, Daniel (dt5972) <dtimoney@att.com>2017-02-15 10:40:37 -0500
commit324ee36fe31763e507b422ab0a88e4230045e205 (patch)
treed0b04520f6657601c918ce63fd27575977624187 /admportal/server/router/routes
parentf0c97e8db427481e28c0a16b789bc73801b35e47 (diff)
Initial commit for OpenECOMP SDN-C OA&M
Change-Id: I7ab579fd0d206bf356f36d52dcdf4f71f1fa2680 Signed-off-by: Timoney, Daniel (dt5972) <dtimoney@att.com> Former-commit-id: 2a9f0edd09581f907e62ec4689b5ac94dd5382ba
Diffstat (limited to 'admportal/server/router/routes')
-rwxr-xr-xadmportal/server/router/routes/Odl.js594
-rwxr-xr-xadmportal/server/router/routes/admin.js83
-rw-r--r--admportal/server/router/routes/csp.js84
-rw-r--r--admportal/server/router/routes/dbRoutes.js1192
-rw-r--r--admportal/server/router/routes/gamma.js1667
-rw-r--r--admportal/server/router/routes/helpers.js66
-rw-r--r--admportal/server/router/routes/mobility.js1339
-rw-r--r--admportal/server/router/routes/network.js400
-rw-r--r--admportal/server/router/routes/odl.js258
-rw-r--r--admportal/server/router/routes/preload.js154
-rw-r--r--admportal/server/router/routes/root.js111
-rw-r--r--admportal/server/router/routes/sla.js369
-rw-r--r--admportal/server/router/routes/user.js169
-rw-r--r--admportal/server/router/routes/vnf.js603
14 files changed, 7089 insertions, 0 deletions
diff --git a/admportal/server/router/routes/Odl.js b/admportal/server/router/routes/Odl.js
new file mode 100755
index 00000000..a27d73b3
--- /dev/null
+++ b/admportal/server/router/routes/Odl.js
@@ -0,0 +1,594 @@
+// Odl.js
+var https = require('https');
+var http = require('http');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+
+
+var Odl = function() {
+ // Call ODL page
+ // get(uri,res)
+ // post(uri,data, res)
+
+ var _healthcheck = function(options, callback)
+ {
+ // Setup request to ODL side
+ console.log('options:' + JSON.stringify(options,null,2));
+ var request = https.request(options, function(response) {
+
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ response.on('end', function()
+ {
+ //logger.debug(response_str);
+ if(response.statusCode == 200)
+ {
+ console.log('200 OK');
+ callback(null, response_str);
+ return;
+ }
+ else{
+ console.log('not ok status=' + response.statusCode);
+ callback(response_str, 'statusCode=' + response.statusCode + '\n' + response_str);
+ return;
+ }
+ });
+ });
+ request.end()
+
+ request.on('error', function(err) {
+ console.error('err:' + err);
+ callback(err, err);
+ return;
+ });
+ }
+
+ var _get = function(uri,options,callback,req,res)
+ {
+
+ options.method = "GET";
+ options.path = uri;
+
+ // Setup request to ODL side
+ console.log('options:' + JSON.stringify(options,null,2));
+ var request = https.request(options, function(response) {
+ // console.dir(response);
+ console.log('STATUS: ' + response.statusCode);
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ response.on('end', function()
+ {
+ console.log(response_str);
+
+ if(response.statusCode == 200)
+ {
+ // make sure response starts with JSON string
+ if (response_str && response_str.indexOf('{') == 0) {
+ //console.log("response: ", result);
+
+ req.session.l3sdnPageInfo = undefined;
+ var x=0;
+ var pageList = [];
+ var obj_rows = [];
+ var rows = [];
+ var robj = JSON.parse(response_str);
+
+ if ( typeof robj['services']['layer3-service-list'] != 'undefined' )
+ {
+ for( var i=0; i<robj['services']['layer3-service-list'].length; i++)
+ {
+ obj_rows.push( robj['services']['layer3-service-list'][i] );
+ }
+ }
+ else
+ {
+ res.render('pages/err', {result:{code:'failure', msg:'no data Error: ' + String(err)}, header:process.env.MAIN_MENU});
+ callback(null,response_str,res);
+ return;
+ }
+
+ var rows = [];
+ var l3sdnPageInfo =
+ {
+ 'totalRows' : obj_rows.length,
+ 'pageSize' : 18,
+ 'pageCount' : parseInt(obj_rows.length/18),
+ 'currentPage' : 1
+ }
+
+ while (obj_rows.length > 0){
+ pageList.push(obj_rows.splice(0,l3sdnPageInfo.pageSize));
+ }
+ l3sdnPageInfo.rows = pageList[0]; // first page
+ l3sdnPageInfo.pages = pageList; // all pages
+
+
+ req.session.l3sdnPageInfo = l3sdnPageInfo;
+ var privObj = req.session.loggedInAdmin;
+
+ res.render('odl/listWklst',
+ {
+ pageInfo : l3sdnPageInfo,
+ result : {code:'', msg:''},
+ privilege : privObj, header:process.env.MAIN_MENU
+ });
+
+
+ } else {
+ res.render('pages/err', {result:{code:'failure', msg:'no data Error: ' + String(err)}, header:process.env.MAIN_MENU});
+ }
+ callback(null, response_str, res);
+ }
+ else
+ {
+ callback(response_str,response_str,res);
+ //res.render('pages/err', {result:{code:'failure', msg:'Failed to retrieve worklist. ' + response_str}});
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ callback(err,null, res);
+ });
+ }
+
+ var _getid = function(uri,options,res) {
+ options.method = "GET";
+ options.path = uri;
+
+ // Setup request to ODL side
+ var request = https.request(options, function(response) {
+ // console.dir(response);
+ //console.log('STATUS: ' + response.statusCode);
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ response.on('end', function() {
+ if(response.statusCode == 200){
+ if(response_str){
+ //console.log("response: ", response_str);
+ res.render('odl/view', {response_obj: JSON.parse(response_str), header:process.env.MAIN_MENU});
+ }
+ else{
+ //console.log("no data");
+ res.render('pages/err', {result:{code:'failure', msg:'Failed to retrieve worklist'}, header:process.env.MAIN_MENU});
+ }
+ }
+ else {
+ //console.log("bad status code:", response.statusCode);
+ res.render('pages/err', {result:{code:'failure', msg:'Failed to retrieve worklist. Status Code:' + response.statusCode}, header:process.env.MAIN_MENU});
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ //console.log(err);
+ res.render('pages/err', {result:{code:'failure', msg:'Failed to get worklist item. ' + String(err)}, header:process.env.MAIN_MENU});
+ });
+ }
+
+ var _getvrlan = function(uri,options,callback) {
+ options.method = "GET";
+ options.path = uri;
+
+
+ //callback(null,'');
+ // Setup request to ODL side
+ var request = https.request(options, function(response) {
+ // console.dir(response);
+ //console.log('STATUS: ' + response.statusCode);
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+
+ response.on('end', function() {
+ if(response.statusCode == 200){
+ if(response_str){
+ callback(null,response_str);
+ return;
+ }
+ else{
+ callback('err','no data');
+ return;
+ }
+ }
+ else {
+ callback('error',response.statusCode);
+ return;
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ callback(err,String(err));
+ return;
+ });
+ }
+
+
+ var _getvnf = function(uri,options,req,res) {
+ options.method = "GET";
+ options.path = uri;
+
+ // Setup request to ODL side
+ var request = https.request(options, function(response) {
+ // console.dir(response);
+ //console.log('STATUS: ' + response.statusCode);
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ response.on('end', function() {
+ if(response.statusCode == 200){
+ if(response_str){
+ //console.log("response: ", response_str);
+ res.render('odl/viewvnf', { vnf_obj: JSON.parse(response_str),
+ request_id: req.query['request'], header:process.env.MAIN_MENU });
+ }
+ else{
+ //console.log("no data");
+ res.render('pages/err', {result:{code:'failure', msg:'Failed to retrieve worklist item.'}, header:process.env.MAIN_MENU});
+ }
+ }
+ else {
+ //console.log("bad status code:", response.statusCode);
+ res.render('pages/err', {result:{code:'failure', msg:'Failed to retrieve worklist. Status Code:' + response.statusCode}, header:process.env.MAIN_MENU});
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ //console.log(err);
+ res.render('pages/err', {result:{code:'failure', msg:'Failed getting VNF information. Error: '+ String(err)}, header:process.env.MAIN_MENU});
+ });
+ }
+
+ var _getPreloadVnfData = function(uri,options,res,callback) {
+
+ options.method = "GET";
+ options.path = uri;
+
+
+ // Setup request to ODL side
+ var protocol;
+ if ( process.env.NODE_ENV != 'production' ){
+ protocol = http;
+ }else{
+ protocol = https;
+ }
+
+console.log('NODE_ENV:' + process.env.NODE_ENV);
+console.log('GET: ' + JSON.stringify(options,null,4));
+
+ var request = protocol.request(options, function(response) {
+
+ var response_str = '';
+
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ response.on('end', function() {
+console.log('response_str: ' + response_str);
+console.log('response.statusCode: ' + response.statusCode);
+ if(response.statusCode == 200){
+ if(response_str){
+ callback(null,response_str);
+ return;
+ }
+ else{
+ callback('Error - No data returned.');
+ return;
+ }
+ }
+ else {
+ if ( response.statusCode == 404 )
+ {
+ callback('HTTP Status Code:' + response.statusCode + '. Not Found.');
+ return;
+ }
+ else if ( response_str.length > 0 )
+ {
+ callback('HTTP Status Code:' + response.statusCode + '. ' + response_str);
+ return;
+ }
+ else
+ {
+ callback('HTTP Status Code:' + response.statusCode + '. No data returned.');
+ return;
+ }
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ callback(err);
+ return;
+ });
+ }
+
+var _getClusterStatus = function(options,callback) {
+ //options.method = "GET";
+ //options.path = uri;
+
+ console.log('URI='+options.path);
+
+ // Setup request to ODL side
+ var protocol = properties.odlProtocol;
+console.log('protocol=' + protocol);
+ if ( protocol == 'http' || protocol == 'HTTP' )
+ {
+console.log('http request');
+ var request = http.request(options, function(response) {
+ var response_str = '';
+
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+
+ response.on('end', function() {
+console.log('HTTP StatusCode='+response.statusCode);
+ if(response.statusCode == 200){
+ if(response_str){
+console.log('response_str='+response_str);
+ callback(null,JSON.parse(response_str));
+ return;
+ }
+ else{
+ callback(null,'no data');
+ return;
+ }
+ }
+ else {
+ callback(null,response.statusCode);
+ return;
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ callback(null,String(err));
+ return;
+ });
+ }
+ else {
+ var request = https.request(options, function(response) {
+ var response_str = '';
+
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+
+ response.on('end', function() {
+ if(response.statusCode == 200){
+ if(response_str){
+console.log('response_str='+response_str);
+ callback(null,JSON.parse(response_str));
+ return;
+ }
+ else{
+ callback(null,'no data');
+ return;
+ }
+ }
+ else {
+ callback(null,response.statusCode);
+ return;
+ }
+ });
+ });
+
+ request.end()
+
+ request.on('error', function(err) {
+ callback(null,String(err));
+ return;
+ });
+ }
+}
+
+ var _delete = function(uri,options,res,callback) {
+ options.method = 'DELETE';
+ options.path = uri;
+
+
+ // Setup request to ODL side
+ //var request = https.request(options, function(response) {
+ var request = http.request(options, function(response) {
+ //console.log('STATUS: ' + response.statusCode);
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ response.on('end', function() {
+ if(response.statusCode == 200){
+ callback(null);
+ return;
+ }
+ else {
+ callback('Error:' + response_str);
+ return;
+ }
+ });
+ });
+ request.on('error', function(err) {
+ callback(err);
+ return;
+ });
+ request.end()
+ }
+
+ var _post = function(uri,options,data,res,callback)
+ {
+ options.method = 'POST';
+ options.path = uri;
+
+
+ // Setup request to ODL side
+ var protocol;
+ //if ( process.env.NODE_ENV != 'production' ){
+ protocol = http;
+ //}else{
+ //protocol = https;
+ //}
+ var request = protocol.request(options, function(response)
+ {
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ //logger.debug('chunk:' + chunk);
+ });
+
+ // end of request, check response
+ response.on('end', function() {
+ console.log('post status code:'+response.statusCode);
+ if(response.statusCode == 200 ){
+ try {
+ var respObj = JSON.parse(response_str);
+ console.log('response_str.length:' + response_str.length);
+ if(response_str){
+ console.log("post response-code:" + respObj['output']['response-code']);
+
+ if ( respObj['output']['response-code'] == 200 ){
+ callback(null,response_str);
+ return;
+ }else{
+ callback('Error - response-code:' + respObj['output']['response-code'] + ' response-message:' + respObj['output']['response-message']);
+ return;
+ }
+ }else{
+ // success
+ callback(null);
+ return;
+ }
+ }
+ catch (error) {
+ callback('Error parsing response: ' + error);
+ return;
+ }
+ }
+ else {
+ var respObj = null;
+ if ( response_str.length > 0 ) {
+ console.log('response_str:' + response_str);
+ try {
+ respObj = JSON.parse(response_str);
+ if ( typeof respObj['errors'] != 'undefined' )
+ {
+ console.log('Error' + JSON.stringify(respObj));
+ if ( typeof respObj['errors']['error'][0]['error-message'] != 'undefined' )
+ {
+ callback('HTTP Status Code:' + response.statusCode + '. Message:'
+ + respObj['errors']['error'][0]['error-message']);
+ return;
+ }
+ else
+ {
+ callback('Error - HTTP Status Code:' + response.statusCode + '.');
+ return;
+ }
+ }
+ else
+ {
+ callback('Error - HTTP Status Code:' + response.statusCode + '.');
+ return;
+ }
+ }
+ catch (error) {
+ callback('Error - HTTP Status Code:' + response.statusCode + '.');
+ return;
+ }
+ }
+ else{
+ callback('Error - HTTP Status Code:' + response.statusCode + '.');
+ return;
+ }
+ }
+ });
+ });
+
+ request.on('error', function(err) {
+ callback(err);
+ return;
+ });
+
+ request.write(data);
+ request.end()
+ }
+
+ var _postSubnetAllocated = function(uri,options,data,callback,res) {
+ options.method = 'POST';
+ options.path = uri;
+
+ // Setup request to ODL side
+ var request = https.request(options, function(response) {
+ var response_str = '';
+ // Read the response from ODL side
+ response.on('data', function(chunk) {
+ response_str += chunk;
+ });
+
+ // end of request, check response
+ response.on('end', function() {
+ //console.log("post: response: " + response_str);
+ callback(response_str,null,res);
+ });
+ });
+ request.on('error', function(err) {
+ callback(err,null, res);
+ });
+ request.write(data);
+ request.end()
+ }
+
+ return {
+ GetClusterStatus: _getClusterStatus,
+ Get: _get,
+ GetID: _getid,
+ GetVNF: _getvnf,
+ GetVRlan: _getvrlan,
+ GetPreloadVnfData: _getPreloadVnfData,
+ Post: _post,
+ PostSubnetAllocated: _postSubnetAllocated,
+ Delete: _delete,
+ Healthcheck: _healthcheck
+ };
+}();
+
+module.exports = Odl;
+
diff --git a/admportal/server/router/routes/admin.js b/admportal/server/router/routes/admin.js
new file mode 100755
index 00000000..4b7b8088
--- /dev/null
+++ b/admportal/server/router/routes/admin.js
@@ -0,0 +1,83 @@
+var express = require('express');
+var router = express.Router();
+var exec = require('child_process').exec;
+var util = require('util');
+var fs = require('fs');
+var dbRoutes = require('./dbRoutes');
+var csp = require('./csp');
+var bodyParser = require('body-parser');
+var sax = require('sax'),strict=true,parser = sax.parser(strict);
+var async = require('async');
+
+
+// GET
+router.get('/getParameters', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getParameters(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/deleteParameter', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteParameter(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getParameters(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from PARAMETERS table.');
+ dbRoutes.getParameters(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+// POST
+router.post('/addParameter', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.addParameter(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getParameters(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated PARAMETERS.');
+ dbRoutes.getParameters(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateAicSite
+router.post('/updateParameter', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateParameter(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getParameters(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated PARAMETERS.');
+ dbRoutes.getParameters(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+module.exports = router;
diff --git a/admportal/server/router/routes/csp.js b/admportal/server/router/routes/csp.js
new file mode 100644
index 00000000..435aaf91
--- /dev/null
+++ b/admportal/server/router/routes/csp.js
@@ -0,0 +1,84 @@
+var exec = require('child_process').exec;
+var dbRoutes = require('./dbRoutes');
+var fs = require('fs.extra');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+
+var retURL = "";
+var noCookieUrl = "";
+var logoutUrl = "";
+
+function logout(req,res){
+ console.log("logout");
+ req.session.loggedInAdmin = undefined;
+ res.redirect('/login');
+}
+
+function login (req,res) {
+
+ var loggedInAdmin={};
+ var email = req.body.email;
+ dbRoutes.findAdminUser(email,res,function(adminUser){
+ if(adminUser !== null){
+
+ // make sure correct password is provided
+ if (req.body.password != adminUser.password) {
+ res.render("pages/login",
+ {
+ result:
+ {
+ code:'error',
+ msg:'Invalid password entered.'
+ },
+ header:process.env.MAIN_MENU
+ });
+ return;
+ }
+
+ var loggedInAdmin = {
+ email:adminUser.email,
+ password:adminUser.password,
+ privilege:adminUser.privilege
+ }
+ req.session.loggedInAdmin = loggedInAdmin;
+ console.log("Login Success"+JSON.stringify(loggedInAdmin));
+ res.redirect('sla/listSLA');
+ }else{
+ res.render("pages/err",
+ {
+ result:
+ {
+ code:'error',
+ msg:'User ' + attuid + ' is not in the database. Please see an adminstrator to have them added.'
+ },
+ header:process.env.MAIN_MENU
+ });
+ }
+ });
+}
+
+function checkAuth(req,res,next){
+ var host = req.get('host');
+ var url = req.url;
+ var originalUrl = req.originalUrl;
+
+ console.log("checkAuth");
+
+ var host = req.headers['host'];
+console.log('host=' + host);
+
+ console.log("cookie is not null "+JSON.stringify(req.session.loggedInAdmin));
+ if(req.session == null || req.session == undefined
+ || req.session.loggedInAdmin == null || req.session.loggedInAdmin == undefined)
+ {
+ // nothing else to do but log them back in, or they may
+ // be coming from the graph tool
+ console.log("loggedInAdmin not found.session timed out.");
+ res.render('pages/login');
+ return false;
+ }
+ next();
+}
+
+exports.login = login;
+exports.logout = logout;
+exports.checkAuth = checkAuth;
diff --git a/admportal/server/router/routes/dbRoutes.js b/admportal/server/router/routes/dbRoutes.js
new file mode 100644
index 00000000..d2f40b52
--- /dev/null
+++ b/admportal/server/router/routes/dbRoutes.js
@@ -0,0 +1,1192 @@
+var express = require('express'),
+ app = express();
+var mysql = require('mysql');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+var fs = require('fs.extra');
+var util = require('util');
+var os = require('os');
+var async = require('async');
+var l_ = require('lodash');
+var dns = require('dns');
+var dnsSync = require('dns-sync');
+
+var pool = '';
+var currentDB = '';
+var currentDbName = '';
+var fabricDB = properties.dbFabricServer;
+var dbArray = properties.databases;
+var enckey = properties.passwordKey;
+
+console.log('dbFabric=' + properties.dbFabric);
+
+if ( properties.dbFabric == 'true' )
+{
+ connectFabric();
+}
+else
+{
+ initDB();
+}
+
+
+exports.dbConnect = function(){
+
+ console.log('fabric=' + fabricDB);
+ if ( properties.dbFabric == 'true' )
+ {
+ connectFabric();
+ }
+ else
+ {
+ initDB();
+ }
+}
+
+function setCurrentDbName(){
+
+ function createFunction(dbentry)
+ {
+ return function(callback) { findCurrentDbIP(dbentry,callback); }
+ }
+
+ var tasks = [];
+ for (var x=0; x<dbArray.length; x++){
+ var dbElement = dbArray[x];
+ var dbElementArray = dbElement.split("|");
+
+ tasks.push( createFunction(dbElement) );
+ }
+ async.series(tasks, function(err,result){
+
+ if(err){
+ currentDbName = err;
+ console.log('currentDbName: ' + err);
+ return;
+ }
+ else {
+ console.log('not found');
+ return;
+ }
+ });
+}
+
+
+function findCurrentDbIP(dbElement, callback){
+
+ var dbElementArray = dbElement.split("|");
+
+ dns.lookup( dbElementArray[0], function onLookup(err, addresses, family) {
+
+ if ( currentDB == addresses ){
+ callback(dbElementArray[1]);
+ return;
+ }
+ else {
+ callback(null);
+ return;
+ }
+ });
+}
+
+
+exports.getCurrentDB = function(){
+ return currentDbName;
+}
+
+
+exports.testdb = function(req,res,callback){
+console.log('testdb');
+
+ osObj = {
+ 'hostname' : os.hostname(),
+ 'type' : os.type(),
+ 'platform' : os.platform(),
+ 'arch' : os.arch(),
+ 'release' : os.release(),
+ 'uptime' : os.uptime(),
+ 'totalmem' : os.totalmem(),
+ 'dbhealth' : ''
+ };
+
+ pool.getConnection(function(err,connection)
+ {
+ if(err){
+ callback(err);
+ return;
+ }
+
+ // http://stackoverflow.com/questions/10982281/mysql-connection-validity-test-in-datasource-select-1-or-something-better
+ connection.query("/* pint */ SELECT 1", function(err,result){
+
+ connection.release();
+ if(err) {
+ callback(err);
+ return;
+ }
+ callback(null,'Database Connectivity to ' + currentDB + ' is working.');
+ return;
+ }); //end query
+ }); // end getConnection
+}
+
+/*
+exports.checkSvcLogic = function(req,res){
+
+ if ( DBmasterHost.length > 0 && currentHost != DBmasterHost )
+ {
+ // need to copy file so SLA functionality works
+ var source = process.env.SDNC_CONFIG_DIR
+ + "/svclogic.properties." + currentHost;
+ var target = process.env.SDNC_CONFIG_DIR
+ + "/svclogic.properties";
+ fs.copy(source,target,{replace:true}, function(err){
+ if(err){
+ res.render("pages/err",
+ {result:{code:'error',
+ msg:"Unable to copy svclogic.properties. "+ String(err) }});
+ return;
+ }
+ });
+ }
+}
+*/
+function initDB( next ) {
+
+
+ var tasks = [];
+ for (var x=0; x<properties.databases.length; x++){
+
+ var db = properties.databases[x];
+ var dbArray = db.split("|");
+ var _dbIP = dnsSync.resolve(dbArray[0]);
+ var _dbName = dbArray[1];
+
+ tasks.push( createFindMasterFunctionObj(_dbIP, _dbName) );
+ }
+ async.series(tasks, function(err,result)
+ {
+ if(err){
+ if ( err == 'found' ){
+ if ( typeof next != 'undefined'){
+ next();
+ }
+ else {
+ return;
+ }
+ }
+ else {
+ console.error( String(err) ); // ALARM
+ return;
+ }
+ }
+ console.log('result=' + result);
+ });
+ return;
+}
+
+
+function createFindMasterFunctionObj(dbIP,dbName){
+ return function(callback) { findMaster(dbIP, dbName, callback); }
+}
+
+function findMaster (ldbIP, ldbName, callback){
+var dbIP = ldbIP;
+var dbName = ldbName;
+
+ console.log('checking dbIP:' + dbIP);
+
+ pool = mysql.createPool({
+ connectionLimit : properties.dbConnLimit,
+ host : dbIP,
+ user : properties.dbUser,
+ password : properties.dbPassword,
+ database : properties.dbName,
+ multipleStatements: true,
+ debug : false
+ });
+
+ pool.getConnection(function(err,connection){
+
+ if(err){
+ callback( String(err) );
+ return;
+ }
+ var sql = 'select @@read_only';
+ connection.query(sql, function(err,result){
+ connection.release();
+
+ // @@read_only=0 means db is writeable
+ console.log('@@read_only=' + result[0]['@@read_only']);
+ if ( result[0]['@@read_only'] == '0' )
+ { // writeable
+ // if this is not the current DB, make it since its writeable
+ currentDB = dbIP;
+ currentDbName = dbName;
+ console.log('currentDB=' + currentDB + "|" + currentDbName);
+ var newpool = mysql.createPool({
+ connectionLimit : properties.dbConnLimit,
+ host : currentDB,
+ user : properties.dbUser,
+ password : properties.dbPassword,
+ database : properties.dbName,
+ multipleStatements: true,
+ debug : false
+ }); // end create
+ pool = newpool;
+ callback('found', currentDB);
+ return;
+ }
+ // otherwise this is the current db and its writeable, just return
+ callback(null, currentDB);
+ return;
+ });
+ });
+}
+
+exports.checkDB = function(req,res,next){
+
+console.log('checkDB');
+
+
+ if ( properties.dbFabric == 'true' )
+ {
+ connectFabric();
+ next();
+ }
+ else
+ {
+ initDB( next );
+ }
+}
+
+
+exports.saveUser = function(req,res){
+
+ pool.getConnection(function(err,connection){
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/signup", {result:{code:'error', msg:"Unable to get database connection. " + String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ //var sql = "SELECT AES_DECRYPT(password, '" + enckey + "') password FROM PORTAL_USERS";
+ var sql = "SELECT email FROM PORTAL_USERS WHERE email='" + req.body.nf_email + "'";
+
+ console.log(sql);
+
+ connection.query(sql, function(err,result){
+ if(err){
+ res.render("pages/signup", {result:{code:'error', msg:"Unable to get database connection. " + String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ if (result.length == 1 || result.length > 1)
+ {
+ res.render("pages/signup", {result:{code:'error', msg:'User Information already exists.'},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ sql = "INSERT INTO PORTAL_USERS (email,password,privilege) VALUES ("
+ +"'"+ req.body.nf_email + "',"
+ + "AES_ENCRYPT('" + req.body.nf_password + "','" + enckey + "'),"
+ +"'A')";
+
+ console.log(sql);
+
+ connection.query(sql, function(err,result){
+ connection.release();
+
+ if(err){
+ res.render("pages/signup", {result:{ code:'error', msg:String(err) },header:process.env.MAIN_MENU});;
+ return;
+ }
+ res.render('pages/signup', {result:{code:'success', msg:'User created. Please login.'},header:process.env.MAIN_MENU});
+ return;
+ });
+ });
+ });
+}
+
+// delete User
+exports.deleteUser = function(req,res){
+
+ var rows={};
+ var resultObj = { code:'', msg:'' };
+ var privilegeObj = req.session.loggedInAdmin;
+
+ pool.getConnection(function(err,connection) {
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("user/list", {rows: null, result:{code:'error', msg:"Unable to get database connection. Error:" + String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+
+ var sqlUpdate = "DELETE FROM PORTAL_USERS WHERE email='" + req.query.email + "'";
+
+ console.log(sqlUpdate);
+
+ connection.query(sqlUpdate,function(err,result){
+
+ if(err){
+ resultObj = {code:'error', msg:'Delete of user failed Error: '+ String(err) };
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT email,password,privilege FROM PORTAL_USERS", function(err, rows) {
+ connection.release();
+ if(!err) {
+ if ( rows.length > 0 )
+ {
+ resultObj = {code:'success',msg:'Successfully deleted user.'};
+ res.render('user/list', { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU } );
+ return;
+ }else{
+ res.render("user/list", { rows: null, result:{code:'error', msg:'Unexpected no rows returned from database, please try again.',
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ } else {
+ res.render("user/list", { rows: null, result:{code:'error', msg:'Unexpected no rows returned from database. Error: ' + String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ }); //end query
+ });
+ }); // end of getConnection
+}
+
+// add User
+exports.addUser = function(req,res){
+
+ var rows={};
+ var resultObj = { code:'', msg:'' };
+ var privilegeObj = req.session.loggedInAdmin;
+
+ pool.getConnection(function(err,connection) {
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("user/list", {rows: null, result:{code:'error', msg:"Unable to get database connection. "+ String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+
+ if( req.body.nf_privilege == "admin" ){
+ var char_priv = 'A';
+ }else if(req.body.nf_privilege == 'readonly'){
+ var char_priv = 'R';
+ }else{
+ var char_priv = 'A';
+ }
+
+
+ //connection.query(sqlRequest, function(err,result){
+ var sqlUpdate = "INSERT INTO PORTAL_USERS (email, password, privilege) VALUES ("
+ +"'"+ req.body.nf_email + "',"
+ + "AES_ENCRYPT('" + req.body.nf_password + "','" + enckey + "'),"
+ +"'"+ char_priv + "')";
+
+ console.log(sqlUpdate);
+
+ connection.query(sqlUpdate,function(err,result){
+
+ if(err){
+ resultObj = {code:'error', msg:'Add of user failed Error: '+err};
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT email,AES_DECRYPT(password, '" + enckey + "') password,privilege FROM PORTAL_USERS", function(err, rows) {
+
+ connection.release();
+ if(!err) {
+ if ( rows.length > 0 )
+ {
+ resultObj = {code:'success',msg:'Successfully added user.'};
+ res.render('user/list', { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU } );
+ return;
+ }else{
+ res.render("user/list", {rows: null, result:{code:'error', msg:'Unexpected no rows returned from database, please try again.',
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ } else {
+ res.render("user/list", {rows: null, result:{code:'error', msg:'Unexpected no rows returned from database. Error: '+ err ,
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ }); //end query
+ });
+
+ }); // end of getConnection
+}
+
+// updateUser
+exports.updateUser= function(req,res){
+
+ var rows={};
+ var resultObj = { code:'', msg:'' };
+ var privilegeObj = req.session.loggedInAdmin;
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("user/list", {rows: null, result:{code:'error', msg:"Unable to get database connection. " + String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+
+ if( req.body.uf_privilege == "admin" ){
+ var char_priv = 'A';
+ }else if(req.body.uf_privilege == 'readonly'){
+ var char_priv = 'R';
+ }else{
+ var char_priv = 'A';
+ }
+
+
+ //connection.query(sqlRequest, function(err,result){
+ var sqlUpdate = "UPDATE PORTAL_USERS SET "
+ + "email = '" + req.body.uf_email + "',"
+ + "password = " + "AES_ENCRYPT('" + req.body.uf_password + "','" + enckey + "'), "
+ + "privilege = '"+ char_priv + "'"
+ + " WHERE email = '" + req.body.uf_key_email + "'";
+
+ console.log(sqlUpdate);
+
+ connection.query(sqlUpdate,function(err,result){
+
+ if(err){
+ resultObj = {code:'error', msg:'Update of user failed Error: '+err};
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT email, AES_DECRYPT(password,'" + enckey + "') password, privilege FROM PORTAL_USERS", function(err, rows) {
+ connection.release();
+ if(!err) {
+ if ( rows.length > 0 )
+ {
+ resultObj = {code:'success',msg:'Successfully updated user.'};
+ res.render('user/list', { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU} );
+ return;
+ }else{
+ res.render("user/list", {rows: null, result:{ code:'error', msg:'Unexpected no rows returned from database.',
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ } else {
+ res.render("user/list", {rows: null, result:{code:'error', msg:'Unexpected no rows returned from database. ' + String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ }); //end query
+ });
+ }); // end of getConnection
+};
+
+exports.listUsers = function(req,res,resultObj){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var rows={};
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/list", {rows: null, result:{code:'error', msg:"Unable to get database connection. " + String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+
+ // Need DB lookup logic here
+ var selectUsers = "SELECT email, AES_DECRYPT(password,'" + enckey + "') password, privilege from PORTAL_USERS";
+ console.log(selectUsers);
+ connection.query(selectUsers, function(err, rows) {
+
+ connection.release();
+ if(err){
+ resultObj = {code:'error', msg:'Unable to SELECT users Error: '+err};
+ }
+
+ if(!err) {
+ if ( rows.length > 0 )
+ {
+ console.log(JSON.stringify(rows));
+ res.render('user/list', { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU });
+ return;
+ }
+ else{
+ res.render("user/list", {rows: null, result:{code:'error', msg:'Unexpected no rows returned from database.',
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ } else {
+ res.render("user/list", {rows: null, result:{code:'error', msg:'Unexpected no rows returned from database. ' + String(err),
+ privilege:privilegeObj },header:process.env.MAIN_MENU});
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+exports.listSLA = function(req,res,resultObj){
+
+ var privilegeObj = req.session.loggedInAdmin;
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT module,rpc,version,mode,active,graph FROM SVC_LOGIC", function(err, rows) {
+
+ connection.release();
+ if(err) {
+ res.render("pages/err", {result:{code:'error',msg:'Database Error: '+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ else {
+ res.render("sla/list", {rows:rows, result:resultObj, privilege:privilegeObj, header:process.env.MAIN_MENU} );
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+exports.executeSQL = function(sql,req,res,callback){
+
+ console.log(sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ connection.query(sql, function(err,result){
+ connection.release();
+ if (err) {
+ callback(err,'Database operation failed. ' + err );
+ }
+ else
+ {
+console.log('affectedRows='+result.affectedRows);
+ callback(null, result.affectedRows);
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+// gamma - deleteParameter
+exports.deleteParameter = function(req,res,callback){
+
+ var sql = "DELETE FROM PARAMETERS WHERE name='" + req.query.name + "'";
+
+ console.log(sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.log( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+ connection.query(sql, function(err,result){
+ connection.release();
+ if(err){
+ console.log('Update failed. ' + err );
+ callback(err,'Update failed. ' + err );
+ }
+ else
+ {
+ callback(null,'');
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+exports.getTable = function(req,res,sql,rdestination,resultObj,privilegeObj){
+
+console.log('SQL:'+sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ connection.query(sql,function(err, rows)
+ {
+ connection.release();
+ if(err) {
+ res.render(rdestination, {result:{code:'error',msg:'Database Error: '+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ else {
+ res.render(rdestination, { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU } );
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+exports.getMetaTable = function(req,res,sql,rdestination,resultObj,privilegeObj){
+
+ console.log('SQL:'+ sql);
+
+ var rdata = [];
+ var v_tables = [];
+ var vtables = properties.viewTables;
+
+ for ( var i in vtables ) {
+ v_tables.push(vtables[i]);
+ }
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ connection.query(sql,function(err, rows, fields)
+ {
+ console.log('rows:' + JSON.stringify(rows,null,2));
+ // http://stackoverflow.com/questions/14528385/how-to-convert-json-object-to-javascript-array
+ //logger.debug(Object.keys(rows[0]).map(function(v) { return rows[0][v]; }));
+ for ( var i in rows ){
+ rdata.push(Object.keys(rows[i]).map(function(v) { return rows[i][v]; }));
+ //logger.debug(Object.keys(rows[i]).map(function(v) { return rows[i][v]; }));
+ //logger.debug([i, rows[i]]);
+ }
+ for ( var x in rdata ){
+ for ( var j in rdata[x] ){
+ console.log('rdata[' + x + ']: ' + rdata[x][j]);
+ }
+ }
+ console.log('rdata:' + rdata[0]);
+ console.log('fields:' + JSON.stringify(fields,null,2));
+ connection.release();
+ if(err) {
+ res.render(rdestination, {result:{code:'error',msg:'Database Error: '+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ else {
+ res.render(rdestination, { displayTable:true, vtables:v_tables, rows:rdata, fields:fields, result:resultObj, privilege:privilegeObj, header:process.env.MAIN_MENU } );
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+exports.getVnfProfile = function(req,res,resultObj,privilegeObj){
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ connection.query("SELECT vnf_type,availability_zone_count,equipment_role "
+ + "FROM VNF_PROFILE ORDER BY VNF_TYPE", function(err, rows)
+ {
+ connection.release();
+ if(err) {
+ res.render("mobility/vnfProfile", {result:{code:'error',msg:'Database Error: '+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ else {
+ res.render('mobility/vnfProfile', { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU } );
+ return;
+ }
+ }); //end query
+console.log('after query');
+ }); // end getConnection
+}
+
+
+exports.getVnfPreloadData = function(req,res,dbtable,callback){
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT preload_data FROM " + dbtable + " WHERE id="
+ + req.query.id, function(err, rows)
+ {
+ connection.release();
+ if(err) {
+ callback(err);
+ return;
+ }
+ else {
+ var buffer = rows[0].preload_data;
+ var decode_buffer = decodeURI(buffer);
+ var content = JSON.parse(decode_buffer);
+ callback(null,content);
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+
+exports.getVnfNetworkData = function(req,res,resultObj,privilegeObj){
+
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT id,svc_request_id,svc_action,status,filename,ts,preload_data "
+ + "FROM PRE_LOAD_VNF_NETWORK_DATA ORDER BY id", function(err, rows)
+ {
+ var msgArray = new Array();
+
+ connection.release();
+ if(err) {
+ msgArray = 'Database Error: '+ String(err);
+ res.render("mobility/vnfPreloadNetworkData", {
+ result:{code:'error',msg:msgArray},
+ preloadImportDirectory: properties.preloadImportDirectory,
+ header:process.env.MAIN_MENU
+ });
+ return;
+ }
+ else {
+ var retData = [];
+ for( r=0; r<rows.length; r++)
+ {
+ var rowObj = {};
+ rowObj.row = rows[r];
+ if ( rows[r].filename.length > 0 )
+ {
+ try{
+ var buffer = rows[r].preload_data;
+ var decode_buffer = decodeURI(buffer);
+ var filecontent = JSON.parse(decode_buffer);
+ rowObj.filecontent = filecontent;
+ rowObj.network_name = filecontent.input["network-topology-information"]["network-topology-identifier"]["network-name"];
+ rowObj.network_type = filecontent.input["network-topology-information"]["network-topology-identifier"]["network-type"];
+ }
+ catch(error){
+ msgArray.push('File ' + rows[r].filename + ' has invalid JSON. Error:' + error);
+ }
+ }
+ else {
+ rowObj.filecontent = '';
+ }
+ retData.push(rowObj);
+ }
+ if(msgArray.length>0){
+ resultObj.code = 'failure';
+ resultObj.msg = msgArray;
+ }
+ res.render('mobility/vnfPreloadNetworkData', {
+ retData:retData,
+ result:resultObj,
+ privilege:privilegeObj,
+ preloadImportDirectory: properties.preloadImportDirectory,
+ header:process.env.MAIN_MENU
+ });
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+exports.getVnfData = function(req,res,resultObj,privilegeObj){
+
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT id,svc_request_id,svc_action,status,filename,ts,preload_data "
+ + "FROM PRE_LOAD_VNF_DATA ORDER BY id", function(err, rows)
+ {
+ var msgArray = new Array();
+
+ connection.release();
+ if(err) {
+ msgArray = 'Database Error: '+ String(err);
+ res.render("mobility/vnfPreloadData", {
+ result:{code:'error',msg:msgArray},
+ preloadImportDirectory: properties.preloadImportDirectory,
+ header:process.env.MAIN_MENU
+ });
+ return;
+ }
+ else {
+ var retData = [];
+ for( r=0; r<rows.length; r++)
+ {
+ var rowObj = {};
+ rowObj.row = rows[r];
+ if ( rows[r].filename.length > 0 )
+ {
+ try{
+ var buffer = rows[r].preload_data;
+ var s_buffer = decodeURI(buffer);
+ var filecontent = JSON.parse(s_buffer);
+ rowObj.filecontent = filecontent;
+ rowObj.vnf_name = filecontent.input["vnf-topology-information"]["vnf-topology-identifier"]["vnf-name"];
+ rowObj.vnf_type = filecontent.input["vnf-topology-information"]["vnf-topology-identifier"]["vnf-type"];
+ }
+ catch(error){
+ msgArray.push('File ' + rows[r].filename + ' has invalid JSON. Error:' + error);
+ }
+ }
+ else {
+ rowObj.filecontent = '';
+ }
+ retData.push(rowObj);
+ }
+ if(msgArray.length>0){
+ resultObj.code = 'failure';
+ resultObj.msg = msgArray;
+ }
+ res.render('mobility/vnfPreloadData',{
+ retData:retData, result:resultObj,
+ privilege:privilegeObj,
+ header:process.env.MAIN_MENU,
+ preloadImportDirectory: properties.preloadImportDirectory
+ });
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+exports.findAdminUser = function(email,res,callback) {
+
+
+ var adminUser={};
+ pool.getConnection(function(err,connection) {
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/login", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ // Need DB lookup logic here
+ connection.query("SELECT email, AES_DECRYPT(password, '" + enckey + "') password, privilege FROM PORTAL_USERS WHERE email='" + email + "'", function(err, rows) {
+
+ connection.release();
+ if(!err) {
+ if ( rows.length > 0 )
+ {
+ rows.forEach(function(row){
+ adminUser = {
+ "email" : row.email,
+ "password" : row.password,
+ "privilege" : row.privilege };
+ });
+ callback(adminUser);
+ return;
+ }else{
+ console.log("no rows returned");
+ res.render("pages/login", {result:{code:'error', msg:'User is not in database.'},header:process.env.MAIN_MENU});
+ return;
+ }
+ } else {
+ res.render("pages/err", {result:{code:'error',msg:'Unexpected no rows returned from database. '+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+exports.addRow = function(sql,req,res,callback){
+
+ console.log(sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ connection.query(sql, function(err,result){
+ connection.release();
+ if(err){
+ console.debug('Database operation failed. ' + err );
+ callback(err,'Database operation failed. ' + err );
+ }
+ else
+ {
+ callback(null, result.affectedRows);
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+
+exports.addVnfProfile = function(row,res,callback){
+
+ var sqlInsert;
+
+ if ( row.length < 3 )
+ {
+ console.log('Row [' + row + '] does not have enough fields.');
+ callback(null, 'Row [' + row + '] does not have enough fields.');
+ return;
+ }
+
+ sqlInsert = "INSERT INTO VNF_PROFILE ("
+ + "vnf_type,availability_zone_count,equipment_role) VALUES ("
+ + "'" + row[0] + "',"
+ + row[1]
+ + ",'" + row[2] + "')";
+
+ console.log('SQL='+sqlInsert);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.log( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.');
+ return;
+ }
+ connection.query(sqlInsert, function(err,result){
+ connection.release();
+ if(err){
+ console.log('Row [' + row + '] failed to insert. ' + err );
+ callback(null,'Row [' + row + '] failed to insert. ' + err );
+ }
+ else
+ {
+ callback(null,'');
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+// Add to SVC_LOGIC table
+exports.addDG = function(_module, version, rpc, mode, xmlfile, req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var rows={};
+
+ pool.getConnection(function(err,connection) {
+ if(err){
+ console.error( String(err) ); // ALARM
+ res.render("pages/err", {result:{code:'error', msg:"Unable to get database connection. "+ String(err)},header:process.env.MAIN_MENU});
+ return;
+ }
+
+ var post = {
+ module : _module,
+ rpc : rpc,
+ version : version,
+ mode : mode,
+ active : "N",
+ graph : xmlfile
+ };
+
+ //logger.debug( JSON.stringify(post));
+
+ //connection.query(sqlRequest, function(err,result){
+ connection.query('INSERT INTO SVC_LOGIC SET ?', post, function(err,result){
+ // neat!
+
+ // Need DB lookup logic here
+ connection.query("SELECT module,rpc,version,mode,active,graph FROM SVC_LOGIC", function(err, rows) {
+
+ if(!err) {
+ if ( rows.length > 0 )
+ {
+ res.render('sla/list', { rows: rows, result:{code:'',msg:''}, privilege:privilegeObj,header:process.env.MAIN_MENU } );
+ return;
+ }else{
+ console.log("no rows returned");
+ res.render("pages/home");
+ return;
+ }
+ }
+ connection.on('error', function(err){
+ connection.release();
+ console.log(500, "An error has occurred -- " + err);
+ res.render("pages/home");
+ return;
+ });
+ }); //end query
+
+ connection.release();
+ });
+ //connection.query('INSERT INTO SVC_LOGIC SET ?', post, function(err,result){
+ // neat!
+ //logger.debug('inserted rows');
+ //});
+
+ //if(err){
+ //res.render('pages/home');
+ //}
+ return;
+
+ }); // end of getConnection
+};
+
+exports.activate = function(req,res,_module,rpc,version,mode,callback){
+
+ var sql = "UPDATE SVC_LOGIC SET active=\'Y\' WHERE module=\'"
+ + _module + "' AND rpc=\'"
+ + rpc + "' AND version=\'"
+ + version + "' AND mode=\'"
+ + mode + "'";
+
+ console.log('SQL='+sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ connection.query(sql, function(err,result){
+
+ connection.release();
+ if(err){
+ callback(err, 'Unable to get database connection.' + err);
+ }
+ else
+ {
+ callback(null,'');
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+exports.deactivate = function(req,res,_module,rpc,version,mode,callback){
+
+ var sql = "UPDATE SVC_LOGIC SET active=\'N\' WHERE module=\'"
+ + _module + "' AND rpc=\'"
+ + rpc + "' AND version=\'"
+ + version + "' AND mode=\'"
+ + mode + "'";
+
+ console.log('SQL='+sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ connection.query(sql, function(err,result){
+
+ connection.release();
+ if(err){
+ callback(err, 'Unable to get database connection.' + err);
+ }
+ else
+ {
+ callback(null,'');
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+exports.global_deactivate = function(req,res,_module,rpc,mode,callback){
+
+ var sql = "UPDATE SVC_LOGIC SET active=\'N\' WHERE module=\'"
+ + _module + "' AND rpc=\'"
+ + rpc + "' AND mode=\'"
+ + mode + "'";
+
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ connection.query(sql, function(err,result){
+
+ connection.release();
+ if(err){
+ callback(err, err);
+ }
+ else
+ {
+ callback(null,'');
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+exports.deleteDG = function(req,res,_module,rpc,version,mode,callback){
+
+ var sql = "DELETE FROM SVC_LOGIC WHERE module=\'"
+ + _module + "' AND rpc=\'"
+ + rpc + "' AND version=\'"
+ + version + "' AND mode=\'"
+ + mode + "'";
+
+ console.log('SQL='+sql);
+
+ pool.getConnection(function(err,connection) {
+
+ if(err){
+ console.error( String(err) ); // ALARM
+ callback(err, 'Unable to get database connection.' + err);
+ return;
+ }
+
+ connection.query(sql, function(err,result){
+
+ connection.release();
+ if(err){
+ callback(err, 'Unable to get database connection.' + err);
+ }
+ else
+ {
+ callback(null,'');
+ }
+ }); //end query
+ }); // end getConnection
+}
+
+
+
+function padLeft(nr, n, str){
+ return Array(n-String(nr).length+1).join(str||'0')+nr;
+}
+
diff --git a/admportal/server/router/routes/gamma.js b/admportal/server/router/routes/gamma.js
new file mode 100644
index 00000000..70e6713c
--- /dev/null
+++ b/admportal/server/router/routes/gamma.js
@@ -0,0 +1,1667 @@
+var express = require('express');
+var router = express.Router();
+var exec = require('child_process').exec;
+var util = require('util');
+var fs = require('fs');
+var dbRoutes = require('./dbRoutes');
+var csp = require('./csp');
+var multer = require('multer');
+var bodyParser = require('body-parser');
+var sax = require('sax'),strict=true,parser = sax.parser(strict);
+var async = require('async');
+var l_ = require('lodash');
+
+
+// used for file upload button, retain original file name
+//router.use(bodyParser());
+router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+//var upload = multer({ dest: process.cwd() + '/uploads/', rename: function(fieldname,filename){ return filename; } });
+
+// multer 1.1
+var storage = multer.diskStorage({
+ destination: function (req, file, cb) {
+ cb(null, process.cwd() + '/uploads/')
+ },
+ filename: function (req, file, cb) {
+ cb(null, file.originalname )
+ }
+});
+
+var upload = multer({
+ storage: storage
+});
+
+
+//router.use(express.json());
+//router.use(express.urlencoded());
+//router.use(multer({ dest: './uploads/' }));
+
+// 1604
+var selectNetworkProfile = "SELECT network_type,technology FROM NETWORK_PROFILE ORDER BY network_type";
+
+var selectNbVlanRange = "SELECT vlan_plan_id,plan_type,purpose,LPAD(range_start,4,0) range_start,LPAD(range_end,4,0) range_end,generated from VLAN_RANGES ORDER BY vlan_plan_id";
+
+var selectNbVlanPool = "SELECT aic_site_id,availability_zone,vlan_plan_id,plan_type,purpose,LPAD(vlan_id,4,0) vlan_id,status FROM VLAN_POOL ORDER BY aic_site_id,availability_zone,vlan_plan_id,vlan_id";
+
+router.get('/getNetworkProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getTable(req,res,selectNetworkProfile,'gamma/networkProfile',{code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getNbVlanRange', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getTable(req,res,selectNbVlanRange,'gamma/nbVlanRange',{code:'', msg:''}, req.session.loggedInAdmin);
+});
+
+router.get('/getNbVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ if (typeof req.query.vlan_plan_id == "undefined"){
+ dbRoutes.getTable(req,res,selectNbVlanPool,'gamma/nbVlanPool',{code:'', msg:''}, req.session.loggedInAdmin);
+ }else{
+ var sql = "SELECT aic_site_id,availability_zone,vlan_plan_id,plan_type,purpose,vlan_id,status FROM VLAN_POOL WHERE vlan_plan_id='" + req.query.vlan_plan_id + "' AND vlan_id BETWEEN "
+ + req.query.range_start + " AND " + req.query.range_end;
+ dbRoutes.getTable(req,res,sql,'gamma/nbVlanPool',{code:'', msg:''}, req.session.loggedInAdmin);
+ }
+});
+
+router.post('/addNetworkProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var network_type = removeNL(req.body.nf_network_type);
+ var technology = removeNL(req.body.nf_technology);
+ var sql = "INSERT INTO NETWORK_PROFILE (network_type,technology) VALUES ("
+ + "'"+ network_type + "',"
+ + "'"+ technology + "')";
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.addRow(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err)
+ {
+ msgArray.push(err);
+ dbRoutes.getTable(req,res,ucpePhsCredentials, 'gamma/networkProfile', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ if ( result == 1 )
+ {
+ msgArray.push('Successfully added Network Profile.');
+ dbRoutes.getTable(req,res,selectNetworkProfile, 'gamma/networkProfile', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ msgArray.push('Was not able to add Network Profile.');
+ dbRoutes.getTable(req,res,ucpePhsCredentials, 'gamma/networkProfile', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ }
+ });
+});
+
+router.post('/saveNbVlanRange', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var plan_type = req.body.nf_plan_type;
+ var purpose = req.body.nf_purpose;
+ var range_start = padLeft(removeNL(req.body.nf_range_start),4);
+ var range_end = padLeft(removeNL(req.body.nf_range_end),4);
+ var tasks = [];
+ var privilegeObj = req.session.loggedInAdmin;
+
+ tasks.push( function(callback) {
+ dbRoutes.saveNbVlanRange(range_start,range_end,plan_type,purpose,req,res,callback);
+ });
+
+ // will probably need to be a new call that is a transaction if i use a new
+ // plan_type-purpose-counter table.
+ //tasks.push( function(callback) { dbRoutes.addRow(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err)
+ {
+ msgArray.push(err);
+ dbRoutes.getTable(req,res,selectNbVlanRange, 'gamma/nbVlanRange', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ msgArray.push('Successfully added VLAN Range.');
+ dbRoutes.getTable(req,res,selectNbVlanRange, 'gamma/nbVlanRange', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.get('/deleteNetworkProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback){
+ dbRoutes.executeSQL("DELETE FROM NETWORK_PROFILE WHERE network_type = '" + req.query.network_type + "'", req,res,callback);
+
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push("Error: " + err);
+ dbRoutes.getTable(req,res,selectNetworkProfile, 'gamma/networkProfile', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ if ( result[0] == 1 )
+ {
+ msgArray.push('Successfully deleted Network Profile.');
+ dbRoutes.getTable(req,res,selectNetworkProfile, 'gamma/networkProfile', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ msgArray.push('No rows removed.');
+ dbRoutes.getTable(req,res,selectNetworkProfile, 'gamma/networkProfile', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ }
+ });
+});
+
+router.get('/deleteNbVlanRange', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+
+ tasks.push(function(callback){
+ dbRoutes.deleteNbVlanRange(req.query.vlan_plan_id,req,res,callback);
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getTable(req,res,selectNbVlanRange, 'gamma/nbVlanRange', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ msgArray.push('Successfully deleted Range.');
+ dbRoutes.getTable(req,res,selectNbVlanRange, 'gamma/nbVlanRange', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.post('/updateNetworkProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var sql = "UPDATE NETWORK_PROFILE SET "
+ + "network_type='"+ removeNL(req.body.uf_network_type) + "', "
+ + "technology='" + removeNL(req.body.uf_technology) + "' "
+ + "WHERE network_type='" + removeNL(req.body.uf_key_network_type) + "'";
+
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.executeSQL(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getTable(req,res,selectNetworkProfile, 'gamma/networkProfile', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated Network Profile.');
+ dbRoutes.getTable(req,res,selectNetworkProfile, 'gamma/networkProfile', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.post('/updateNbVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var sql = "UPDATE VLAN_POOL SET "
+ + "status='"+ removeNL(req.body.uf_status) + "' "
+ + " WHERE aic_site_id='" + removeNL(req.body.uf_key_aic_site_id) + "'"
+ + " AND availability_zone='" + removeNL(req.body.uf_key_availability_zone) + "'"
+ + " AND vlan_plan_id='" + removeNL(req.body.uf_key_vlan_plan_id) + "'"
+ + " AND plan_type='" + removeNL(req.body.uf_key_plan_type) + "'"
+ + " AND purpose='" + removeNL(req.body.uf_key_purpose) + "'"
+ + " AND vlan_id=" + removeNL(req.body.uf_key_vlan_id);
+
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.executeSQL(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getTable(req,res,selectNbVlanPool, 'gamma/nbVlanPool', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated Network Profile.');
+ dbRoutes.getTable(req,res,selectNbVlanPool, 'gamma/nbVlanPool', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.post('/updateNbVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+});
+router.get('/generateNbVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var vlan_plan_id = req.query.vlan_plan_id;
+ var plan_type = req.query.plan_type;
+ var purpose = req.query.purpose;
+ var range_start = req.query.range_start;
+ var range_end = req.query.range_end;
+ var tasks = [];
+ var privilegeObj = req.session.loggedInAdmin;
+
+ tasks.push( function(callback) {
+ dbRoutes.generateNbVlanPool(range_start,range_end,plan_type,purpose,vlan_plan_id,req,res,callback);
+ });
+
+ // will probably need to be a new call that is a transaction if i use a new
+ // plan_type-purpose-counter table.
+ //tasks.push( function(callback) { dbRoutes.addRow(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err)
+ {
+ msgArray.push(err);
+ dbRoutes.getTable(req,res,selectNbVlanRange, 'gamma/nbVlanRange', {code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else
+ {
+ msgArray.push('Successfully added VLAN Range.');
+ dbRoutes.getTable(req,res,selectNbVlanRange, 'gamma/nbVlanRange', {code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+///// end 1604
+
+
+// GET
+router.get('/getServiceHoming', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getServiceHoming(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getServiceHomingRollback', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getServiceHomingRollback(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVlanPool(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getAicSite', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getAicSite(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getAicSwitch', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getAicSwitch(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getAicAvailZone', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getAicAvailZone(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVpePool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVpePool(req,res,{code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVplspePool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVplspePool(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+
+// ROLLBACK SERVICE_HOMING
+router.get('/rollbackServiceHoming', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.rollbackServiceHoming(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getServiceHomingRollback(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('SERVICE_HOMING table successfully restored.');
+ dbRoutes.getServiceHoming(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// DELETE SERVICE_HOMING
+router.get('/deleteServiceHoming', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteServiceHoming(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getServiceHoming(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from SERVICE_HOMING table.');
+ dbRoutes.getServiceHoming(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+// DELETE AIC_SITE
+router.get('/deleteSite', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteSite(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getAicSite(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from AIC_SITE table.');
+ dbRoutes.getAicSite(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// DELETE AIC_SWITCH
+router.get('/deleteSwitch', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteSwitch(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getAicSwitch(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from AIC_SWITCH table.');
+ dbRoutes.getAicSwitch(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// DELETE AIC_AVAIL_ZONE_POOL
+router.get('/deleteZone', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteZone(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getAicAvailZone(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from AIC_AVAIL_ZONE_POOL table.');
+ dbRoutes.getAicAvailZone(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// DELETE VLAN_ID_POOL
+router.get('/deleteVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteVlanPool(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVlanPool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VLAN_ID_POOL table.');
+ dbRoutes.getVlanPool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// DELETE VPE_POOL
+router.get('/deleteVpePool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteVpePool(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVpePool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VPE_POOL table.');
+ dbRoutes.getVpePool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+// DELETE VPE_POOL
+router.get('/deleteVplspePool', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push(function(callback) {
+ dbRoutes.deleteVplspePool(req,res,callback);
+ });
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVplspePool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VPLSPE_POOL table.');
+ dbRoutes.getVplspePool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// POST
+router.post('/addServiceHoming', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.addWebServiceHoming(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getServiceHoming(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully added SERVICE_HOMING');
+ dbRoutes.getServiceHoming(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+// gamma - updateProvStatus
+router.post('/updateProvStatus', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateProvStatus(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVpePool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated Provisioning Status');
+ dbRoutes.getVpePool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateAicSite
+router.post('/updateAicSite', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateAicSite(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getAicSite(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated AIC_SITE table.');
+ dbRoutes.getAicSite(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateAicSwitch
+router.post('/updateAicSwitch', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateAicSwitch(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getAicSwitch(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated AIC_SWITCH table.');
+ dbRoutes.getAicSwitch(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateAicAvailZone
+router.post('/updateAicAvailZone', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateAicAvailZone(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getAicAvailZone(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated AIC_AVAIL_ZONE_POOL table.');
+ dbRoutes.getAicAvailZone(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateVlanPool
+router.post('/updateVlanPool', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateVlanPool(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVlanPool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated VLAN_ID_POOL table.');
+ dbRoutes.getVlanPool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateVpePool
+router.post('/updateVpePool', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateVpePool(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVpePool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated VPE_POOL table.');
+ dbRoutes.getVpePool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// gamma - updateVplspePool
+router.post('/updateVplspePool', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateVplspePool(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVplspePool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated VPLSPE_POOL table.');
+ dbRoutes.getVplspePool(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+// gamma - updateServiceHoming
+router.post('/updateServiceHoming', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.updateServiceHoming(req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getServiceHoming(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully updated SERVICE_HOMING table.');
+ dbRoutes.getServiceHoming(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.post('/uploadVLAN', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res, next){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVlanPool(req,res,{code:'danger', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ // check for valid filename format
+ var tagpos = str.search("_ctag_pool");
+ var csvpos = str.search(".csv");
+ if(tagpos != 13 || csvpos != 23){
+ var msgArray = new Array();
+ msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_ctag_pool.csv');
+ dbRoutes.getVlanPool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVLAN(lrow,res,callback); }
+ }
+
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ //async.parallelLimit(funcArray, 5, function(err,result){
+ async.series(funcArray, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVlanPool(req,res, result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getVlanPool(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ console.error('error:'+ex);
+ msgArray = [];
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getVlanPool(req,res, {code:'danger', msg:msgArray}, privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray = [];
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVlanPool(req,res, {code:'danger', msg:msgArray}, privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray = [];
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVlanPool(req,res, {code:'danger', msg:msgArray}, privilegeObj);
+ return;
+ }
+
+});
+
+
+// POST
+router.post('/uploadAicSite', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getAicSite(req,res, {code:'danger', msg:'There was an error uploading the file, please try again.'}, privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ // check for valid filename format
+ var tagpos = str.search("_site");
+ var csvpos = str.search(".csv");
+ if(tagpos != 13 || csvpos != 18){
+ msgArray.length = 0;
+ msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_site.csv');
+ dbRoutes.getAicSite(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addAicSite(lrow,res,callback); }
+ }
+
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.parallelLimit(funcArray, 50, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getAicSite(req,res, result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getAicSite(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getAicSite(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getAicSite(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getAicSite(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ }
+
+} );
+
+// POST
+router.post('/uploadAicSwitch', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getAicSwitch(req,res,{code:'danger', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.orignalname;
+
+ // check for valid filename format
+ var tagpos = str.search("_switch");
+ var csvpos = str.search(".csv");
+ if(tagpos != 13 || csvpos != 20){
+ msgArray.length = 0;
+ msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_switch.csv');
+ dbRoutes.getAicSwitch(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addAicSwitch(lrow,res,callback); }
+ }
+
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.parallelLimit(funcArray, 50, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getAicSwitch(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getAicSwitch(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getAicSwitch(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getAicSwitch(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getAicSwitch(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+// POST
+router.post('/uploadAicAvailZone', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getAicAvailZone(req,res,{code:'failure', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ // check for valid filename format
+ var tagpos = str.search("_availabilityzone");
+ var csvpos = str.search(".csv");
+ if(tagpos != 13 || csvpos != 30){
+ msgArray.length = 0;
+ msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_availabilityzone.csv');
+ dbRoutes.getAicAvailZone(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addAicAvailZone(lrow,res,callback); }
+ }
+
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.parallelLimit(funcArray, 50, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getAicAvailZone(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getAicAvailZone(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getAicAvailZone(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getAicAvailZone(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getAicAvailZone(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+// POST
+router.post('/uploadVpePool', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVpePool(req,res,{code:'failure', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ // check for valid filename format
+ var tagpos = str.search("_vpe");
+ var csvpos = str.search(".csv");
+ if(tagpos != 13 || csvpos != 17){
+ msgArray.length = 0;
+ msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_vpe.csv');
+ var resultObj = {code:'failure', msg:msgArray};
+ dbRoutes.getVpePool(req,res,resultObj,privilegeObj);
+ return;
+ }
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVpePool(lrow,res,callback); }
+ }
+
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.parallelLimit(funcArray, 50, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVpePool(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getVpePool(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getVpePool(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVpePool(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVpePool(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+// POST
+router.post('/uploadVplspePool', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVplspePool(req,res,{code:'failure', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ // check for valid filename format
+ var tagpos = str.search("_vpls");
+ var csvpos = str.search(".csv");
+ if(tagpos != 13 || csvpos != 18){
+ msgArray.length = 0;
+ msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_vpls.csv');
+ dbRoutes.getVplspePool(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVplspePool(lrow,res,callback); }
+ }
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.parallelLimit(funcArray, 50, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVplspePool(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getVplspePool(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getVplspePool(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVplspePool(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVplspePool(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+// POST
+router.post('/uploadServiceHoming', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res)
+{
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname)
+ {
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getServiceHoming(req,res,{code:'failure', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists)
+ {
+ if(exists)
+ {
+ var str = req.file.originalname;
+
+ // check for valid filename format
+ var csvpos = str.search(".csv");
+ if( (l_.startsWith(str,'aichoming_') != true) || csvpos != 18)
+ {
+ msgArray.length = 0;
+ msgArray.push('Not a valid filename, format must be aichoming_mmddYYYY.csv');
+ //msgArray.push('Not a valid filename, format must be pp_YYYYMMDDHH_vpls.csv');
+ dbRoutes.getServiceHoming(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ try
+ {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var csvrows = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function()
+ {
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addServiceHoming(lrow,req,res,callback); }
+ }
+ funcArray.push(function(callback) {
+ dbRoutes.saveServiceHoming(req,res,callback);
+ });
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in series
+ async.series(funcArray, function(err,result)
+ {
+ if ( err )
+ {
+ result = {code:'failure', msg:result};
+ dbRoutes.getServiceHoming(req,res,result,privilegeObj);
+ return;
+ }
+ else
+ { // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++)
+ {
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getServiceHoming(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getServiceHoming(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getServiceHoming(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else
+ {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getServiceHoming(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+function removeNL(s) {
+ /*
+ ** Remove NewLine, CarriageReturn and Tab characters from a String
+ ** s string to be processed
+ ** returns new string
+ */
+ r = "";
+ for (i=0; i < s.length; i++)
+ {
+ if (s.charAt(i) != '\n' &&
+ s.charAt(i) != '\r' &&
+ s.charAt(i) != '\t')
+ {
+ r += s.charAt(i);
+ }
+ }
+ return r;
+}
+function padLeft(nr, n, str){
+ return Array(n-String(nr).length+1).join(str||'0')+nr;
+}
+
+
+module.exports = router;
diff --git a/admportal/server/router/routes/helpers.js b/admportal/server/router/routes/helpers.js
new file mode 100644
index 00000000..6ac8215f
--- /dev/null
+++ b/admportal/server/router/routes/helpers.js
@@ -0,0 +1,66 @@
+
+var _ = require('lodash');
+var csvtojson = require('csvtojson');
+var async = require('async');
+var uuid = require('node-uuid'); // generate a uuid with "uuid.v1()"
+var path = require('path');
+var fs = require("fs");
+var moment = require('moment');
+
+var helpers = module.exports;
+
+function puts(obj) { console.log(obj); }
+function putd(obj) { console.log(obj); }
+helpers.puts = puts;
+helpers.putd = putd;
+
+
+helpers.readCsv = function(filedir, filename, callback) {
+
+
+ var Converter=csvtojson.Converter;
+ var csvFileName=path.join(filedir,filename);
+ var fileStream=fs.createReadStream(csvFileName);
+ fileStream.on('error', function(err){
+ callback(err, null);
+ });
+ var param={noheader:true, checkType:false};
+ var csvConverter=new Converter(param);
+ csvConverter.on("end_parsed",function(jsonObj){
+ var returnValue = jsonObj;
+ callback(null, returnValue);
+ });
+ fileStream.on('error', function(err) {
+ putd(err);
+ callback(err,"");
+ });
+ fileStream.pipe(csvConverter);
+}
+
+helpers.getParam = function(csv, matchField, matchValue, returnField) {
+ dataRow=_.find(csv, matchField, matchValue);
+ dataValue=dataRow[returnField];
+ return dataValue;
+}
+
+helpers.writeOutput = function(req, filename, jsonOutput, callback) {
+ try {
+ fs.writeFileSync(filename, jsonOutput);
+ }
+ catch(err){
+ callback(err);
+ }
+}
+
+helpers.getFileName = function(req, defFilename) {
+
+ var fileObj = null;
+ for (var x=0; x < req.files.length; x++)
+ {
+ var fileObj = req.files[x];
+ if ( fileObj.filename.indexOf(defFilename) != -1 ){
+ return fileObj.filename;
+ }
+ }
+ return null;
+}
diff --git a/admportal/server/router/routes/mobility.js b/admportal/server/router/routes/mobility.js
new file mode 100644
index 00000000..1c45452e
--- /dev/null
+++ b/admportal/server/router/routes/mobility.js
@@ -0,0 +1,1339 @@
+var express = require('express');
+var router = express.Router();
+var exec = require('child_process').exec;
+var util = require('util');
+var fs = require('fs.extra');
+var dbRoutes = require('./dbRoutes');
+var csp = require('./csp');
+var multer = require('multer');
+var bodyParser = require('body-parser');
+var sax = require('sax'),strict=true,parser = sax.parser(strict);
+var async = require('async');
+var l_ = require('lodash');
+var dateFormat = require('dateformat');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+
+
+// pass host, username and password to ODL
+// target host for ODL request
+var username = properties.odlUser;
+var password = properties.odlPasswd;
+var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
+var host = properties.odlHost;
+var port = properties.odlPort;
+
+var header = {'Host': host, 'Authorization': auth, 'Content-Type': 'application/json'};
+var options = {
+ host : host,
+ headers : header,
+ port : port,
+ rejectUnauthorized:false,
+ strictSSL: false
+};
+
+// Connection to OpenDaylight
+Odl = require('./Odl');
+
+// used for file upload button, retain original file name
+//router.use(bodyParser());
+//router.use(bodyParser.urlencoded({
+ //extended: true
+//}));
+
+//var upload = multer({ dest: process.cwd() + '/uploads/', rename: function(fieldname,filename){ return filename; } });
+
+// multer 1.1
+var storage = multer.diskStorage({
+ destination: function (req, file, cb) {
+ cb(null, process.cwd() + '/uploads/')
+ },
+ filename: function (req, file, cb) {
+ cb(null, file.originalname )
+ }
+});
+
+var upload = multer({
+ storage: storage
+});
+
+
+
+
+// GET
+router.get('/getVnfData', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVnfData(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVmNetworks', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVmNetworks(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVnfProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVnfProfile(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVnfNetworks', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVnfNetworks(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+router.get('/getVmProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVmProfile(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+////////
+router.get('/getVnfNetworkData', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.getVnfNetworkData(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+
+router.get('/viewVnfNetworkData', csp.checkAuth, function(req,res)
+{
+ var privilegeObj = req.session.loggedInAdmin;
+ var resp_msg = '';
+ var network_name = req.query.network_name;
+ var network_type = req.query.network_type;
+ var tasks = [];
+
+ tasks.push(function(callback){
+ Odl.GetPreloadVnfData('/restconf/config/VNF-API:preload-vnfs/vnf-preload-list/'
+ + encodeURIComponent(network_name) + '/' + encodeURIComponent(network_type) + '/', options,res,callback);
+
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ resp_msg = err;
+ res.render('mobility/displayVnfNetworkData', {result:{code:'failure', msg:resp_msg}, header:process.env.MAIN_MENU});
+ return;
+ }
+ else{
+ resp_msg = JSON.stringify(JSON.parse(result[0],null,4));
+ res.render('mobility/displayVnfNetworkData', {result:{code:'success', msg:JSON.parse(result[0])}, header:process.env.MAIN_MENU});
+ return;
+ }
+ });
+
+});
+
+router.get('/viewVnfData', csp.checkAuth, function(req,res)
+{
+ var privilegeObj = req.session.loggedInAdmin;
+ var resp_msg = '';
+ var vnf_name = req.query.vnf_name;
+ var vnf_type = req.query.vnf_type;
+ var tasks = [];
+
+ tasks.push(function(callback){
+ Odl.GetPreloadVnfData('/restconf/config/VNF-API:preload-vnfs/vnf-preload-list/'
+ + encodeURIComponent(vnf_name) + '/' + encodeURIComponent(vnf_type) + '/', options,res,callback);
+
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ resp_msg = err;
+ res.render('mobility/displayVnfData', {result:{code:'failure', msg:resp_msg}, header:process.env.MAIN_MENU});
+ return;
+ }
+ else{
+ resp_msg = JSON.stringify(JSON.parse(result[0],null,4));
+ res.render('mobility/displayVnfData', {result:{code:'success', msg:JSON.parse(result[0])}, header:process.env.MAIN_MENU});
+ return;
+ }
+ });
+
+});
+
+router.get('/loadVnfNetworkData', csp.checkAuth, dbRoutes.checkDB, function(req,res)
+{
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var msgArray = new Array();
+
+ if ( req.query.status != 'pending' )
+ {
+ msgArray.push("Upload Status must be in 'pending' state.");
+ dbRoutes.getVnfNetworkData(req,res, {code:'failure', msg:msgArray}, privilegeObj);
+ return;
+ }
+
+ // build request-id
+ var now = new Date();
+ var df = dateFormat(now,"isoDateTime");
+ var rnum = Math.floor((Math.random() * 9999) +1);
+ var svc_req_id = req.query.id + "-" + df + "-" + rnum;
+
+ var tasks = [];
+
+ // first get the contents of the file from the db
+ tasks.push(function(callback){
+ dbRoutes.getVnfPreloadData(req,res,"PRE_LOAD_VNF_NETWORK_DATA",callback);
+ });
+
+ // then format the request and send it using the arg1 parameter
+ // which is the contents of the file returned from the previous function
+ // call in the tasks array
+ tasks.push(function(arg1,callback){
+
+ var s_file = JSON.stringify(arg1);
+
+ // remove the last two braces, going to add the headers there
+ // will add them back later.
+ s_file = s_file.substring(0, (s_file.length-2));
+
+ // add the request-information header
+ s_file = s_file.concat(',"request-information": {"request-action": "PreloadNetworkRequest"}');
+
+ // add the sdnc-request-header
+ s_file = s_file.concat(',"sdnc-request-header": {"svc-request-id":"');
+ s_file = s_file.concat(svc_req_id);
+ s_file = s_file.concat('","svc-action": "reserve"}');
+
+ // add the two curly braces at the end that we stripped off
+ s_file = s_file.concat('}}');
+
+ Odl.Post('/restconf/operations/VNF-API:preload-network-topology-operation',
+ options,s_file,res,callback);
+ });
+
+ // if successful then update the status
+ tasks.push(function(arg1,callback){
+ dbRoutes.executeSQL("UPDATE PRE_LOAD_VNF_NETWORK_DATA SET status='uploaded',svc_request_id='"
+ + svc_req_id + "',svc_action='reserve' WHERE id="+req.query.id,req,res,callback);
+ });
+
+ // use the waterfall method of making calls
+ async.waterfall(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push("Error posting pre-load data to ODL: "+err);
+ dbRoutes.getVnfNetworkData(req,res, {code:'failure', msg:msgArray}, privilegeObj);
+ return;
+ }
+ else{
+ msgArray.push('Successfully loaded VNF pre-loaded data.');
+ dbRoutes.getVnfNetworkData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.get('/loadVnfData', csp.checkAuth, dbRoutes.checkDB, function(req,res)
+{
+ var privilegeObj = req.session.loggedInAdmin;
+ var full_path_file_name = process.cwd() + "/uploads/" + req.query.filename
+ var msgArray = new Array();
+
+ if ( req.query.status != 'pending' )
+ {
+ msgArray.push("Upload Status must be in 'pending' state.");
+ dbRoutes.getVnfData(req,res, {code:'failure', msg:msgArray}, privilegeObj);
+ return;
+ }
+
+ // build request-id
+ var now = new Date();
+ var df = dateFormat(now,"isoDateTime");
+ var rnum = Math.floor((Math.random() * 9999) +1);
+ var svc_req_id = req.query.id + "-" + df + "-" + rnum;
+
+ var tasks = [];
+
+ // first get the contents of the file from the db
+ tasks.push(function(callback){
+ dbRoutes.getVnfPreloadData(req,res,"PRE_LOAD_VNF_DATA",callback);
+ });
+
+ // then format the request and send it using the arg1 parameter
+ // which is the contents of the file returned from the previous function
+ // call in the tasks array
+ tasks.push(function(arg1,callback){
+
+ var s1_file = JSON.stringify(arg1);
+ var s_file = decodeURI(s1_file);
+
+
+ // remove the last two braces, going to add the headers there
+ // will add them back later.
+ s_file = s_file.substring(0, (s_file.length-2));
+
+ // add the request-information header
+ s_file = s_file.concat(',"request-information": {"request-action": "PreloadVNFRequest"}');
+
+ // add the sdnc-request-header
+ s_file = s_file.concat(',"sdnc-request-header": {"svc-request-id":"');
+ s_file = s_file.concat(svc_req_id);
+ s_file = s_file.concat('","svc-action": "reserve"}');
+
+ // add the two curly braces at the end that we stripped off
+ s_file = s_file.concat('}}');
+
+ Odl.Post('/restconf/operations/VNF-API:preload-vnf-topology-operation',
+ options,s_file,res,callback);
+ });
+
+ // if successful then update the status
+ tasks.push(function(arg1,callback){
+ dbRoutes.executeSQL("UPDATE PRE_LOAD_VNF_DATA SET status='uploaded',svc_request_id='"
+ + svc_req_id + "',svc_action='reserve' WHERE id="+req.query.id,req,res,callback);
+ });
+
+ // use the waterfall method of making calls
+ async.waterfall(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push("Error posting pre-load data to ODL: "+err);
+ dbRoutes.getVnfData(req,res, {code:'failure', msg:msgArray}, privilegeObj);
+ return;
+ }
+ else{
+ msgArray.push('Successfully loaded VNF pre-loaded data.');
+ dbRoutes.getVnfData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.get('/deleteVnfNetworkData', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql = 'DELETE FROM PRE_LOAD_VNF_NETWORK_DATA WHERE id=' + req.query.id;
+
+ // if status is pending, then we do not have to call
+ // ODL, just remove from db
+ if (req.query.status == 'pending'){
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ } else {
+ // format the request to ODL
+ var inputString = '{"input":{"network-topology-information":{"network-topology-identifier":{"service-type":"SDN-MOBILITY","network-name": "';
+ inputString = inputString.concat(req.query.network_name);
+ inputString = inputString.concat('","network-type":"');
+ inputString = inputString.concat(req.query.network_type);
+ inputString = inputString.concat('"}},');
+
+ // add the request-information header
+ inputString = inputString.concat('"request-information": {"request-action": "DeletePreloadNetworkRequest"},');
+
+ // add the sdnc-request-header
+ inputString = inputString.concat('"sdnc-request-header": {"svc-request-id":"');
+ inputString = inputString.concat(req.query.svc_request_id);
+ inputString = inputString.concat('","svc-action": "delete"}}}');
+
+ tasks.push(function(callback) {
+ Odl.Post('/restconf/operations/VNF-API:preload-network-topology-operation',
+ options,inputString,res,callback);
+ });
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ }
+ async.series(tasks, function(err,result){
+
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfNetworkData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from PRE_LOAD_VNF_NETWORK_DATA table and ODL.');
+ dbRoutes.getVnfNetworkData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.get('/deleteVnfData', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql = 'DELETE FROM PRE_LOAD_VNF_DATA WHERE id=' + req.query.id;
+
+ // if status is pending, then we do not have to call
+ // ODL, just remove from db
+ if (req.query.status == 'pending'){
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ } else {
+ var inputString = '{"input":{"vnf-topology-information":{"vnf-topology-identifier":{"service-type":"SDN-MOBILITY","vnf-name": "';
+ inputString = inputString.concat(req.query.vnf_name);
+ inputString = inputString.concat('","vnf-type":"');
+ inputString = inputString.concat(req.query.vnf_type);
+ inputString = inputString.concat('"}},');
+
+ // add the request-information header
+ inputString = inputString.concat('"request-information": {"request-action": "DeletePreloadVNFRequest"},');
+
+ // add the request-information header
+ //inputString = inputString.concat('"request-information": {"request-id": "259c0f93-23cf-46ad-84dc-162ea234fff1",');
+ //inputString = inputString.concat('"source": "ADMINPORTAL",');
+ //inputString = inputString.concat('"order-version": "1",');
+ //inputString = inputString.concat('"notification-url": "notused-this would be infrastructure portal",');
+ //inputString = inputString.concat('"order-number": "1",');
+ //inputString = inputString.concat('"request-action": "DeletePreloadVNFRequest"},');
+
+ // add the sdnc-request-header
+ inputString = inputString.concat('"sdnc-request-header": {"svc-request-id":"');
+ inputString = inputString.concat(req.query.svc_request_id);
+ inputString = inputString.concat('","svc-action": "delete"}}}');
+
+ //inputString = inputString.concat('"sdnc-request-header":{');
+ //inputString = inputString.concat('"svc-request-id": "2015-01-15T14:34:54.st1101a",');
+ //inputString = inputString.concat('"svc-notification-url": "not used",');
+ //inputString = inputString.concat('"svc-action": "delete"}}}');
+
+ tasks.push(function(callback) {
+ Odl.Post('/restconf/operations/VNF-API:preload-vnf-topology-operation',
+ options,inputString,res,callback);
+ });
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ }
+ async.series(tasks, function(err,result){
+
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from PRE_LOAD_VNF_DATA table and ODL.');
+ dbRoutes.getVnfData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.get('/deleteVmProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql = '';
+
+ sql = "DELETE FROM VM_PROFILE WHERE vnf_type='" + req.query.vnf_type + "'"
+ + " AND vm_type='" + req.query.vm_type + "'";
+
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVmProfile(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VM_PROFILE table.');
+ dbRoutes.getVmProfile(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.get('/deleteVnfNetwork', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql = '';
+
+ sql = "DELETE FROM VNF_NETWORKS WHERE vnf_type='" + req.query.vnf_type + "'"
+ + " AND network_role='" + req.query.network_role + "'";
+
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfNetwork(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VNF_NETWORKS table.');
+ dbRoutes.getVnfNetworks(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.get('/deleteVnfProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql = '';
+
+ sql = "DELETE FROM VNF_PROFILE WHERE vnf_type='" + req.query.vnf_type + "'";
+
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfProfile(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VNF_PROFILE table.');
+ dbRoutes.getVnfProfile(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.get('/deleteVmNetwork', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql = '';
+
+ sql = "DELETE FROM VM_NETWORKS WHERE vnf_type='" + req.query.vnf_type
+ + "' AND vm_type='" + req.query.vm_type + "' AND network_role='"
+ + req.query.network_role + "'";
+
+ tasks.push(function(callback) {
+ dbRoutes.executeSQL(sql,req,res,callback);
+ });
+ async.series(tasks, function(err,result)
+ {
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVmNetworks(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from VM_NETWORKS table.');
+ dbRoutes.getVmNetworks(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+// POST
+router.post('/addVmProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql;
+
+
+ if ( req.body.nf_vm_count.length > 0 )
+ {
+ sql = "INSERT INTO VM_PROFILE (vnf_type,vm_type,vm_count) VALUES ("
+ + "'" + req.body.nf_vnf_type + "',"
+ + "'" + req.body.nf_vm_type + "',"
+ + req.body.nf_vm_count + ")";
+ }
+ else
+ {
+ sql = "INSERT INTO VM_PROFILE (vnf_type,vm_type) VALUES ("
+ + "'" + req.body.nf_vnf_type + "',"
+ + "'" + req.body.nf_vm_type + "')";
+ }
+
+
+ console.log("SQL: " + sql);
+
+ tasks.push( function(callback) { dbRoutes.executeSQL(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVmProfile(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully added VM Profile');
+ dbRoutes.getVmProfile(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+
+router.post('/addVnfNetwork', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+
+ var sql = "INSERT INTO VNF_NETWORKS (vnf_type,network_role) VALUES ("
+ + "'" + req.body.nf_vnf_type + "',"
+ + "'" + req.body.nf_network_role + "')";
+
+ console.log("SQL: " + sql);
+
+ tasks.push( function(callback) { dbRoutes.executeSQL(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfNetworks(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully added VNF Network');
+ dbRoutes.getVnfNetworks(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.post('/addVnfProfile', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var sql;
+
+ sql = "INSERT INTO VNF_PROFILE (vnf_type,availability_zone_count,equipment_role) VALUES ("
+ + "'" + req.body.nf_vnf_type + "',"
+ + req.body.nf_availability_zone_count
+ + ",'" + req.body.nf_equipment_role + "')";
+
+console.log(sql);
+
+ tasks.push( function(callback) { dbRoutes.executeSQL(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfProfile(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully added VNF Profile');
+ dbRoutes.getVnfProfile(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+router.post('/addVmNetwork', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ var msgArray = new Array();
+
+ // convert true|false to 1|0
+ var assign_ips = (req.body.nf_assign_ips == 'true') ? 1 : 0;
+ var assign_macs = (req.body.nf_assign_macs == 'true') ? 1 : 0;
+ var assign_floating_ip = (req.body.nf_assign_floating_ip == 'true') ? 1 : 0;
+
+
+ if ((req.body.nf_assign_ips == 'true' &&
+ (typeof req.body.nf_ip_count == 'undefined' || req.body.nf_ip_count.length <=0)))
+ {
+ msgArray.push("If assign_ips equals 'true', ip_count must be populated with a number.");
+ dbRoutes.getVmNetworks(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+
+
+ if ( req.body.nf_ip_count.length >0 )
+ {
+ var sql = "INSERT INTO VM_NETWORKS (vnf_type,vm_type,network_role,ip_count,assign_ips,assign_macs,assign_floating_ip) VALUES ("
+ + "'" + req.body.nf_vnf_type + "',"
+ + "'" + req.body.nf_vm_type + "',"
+ + "'" + req.body.nf_network_role + "',"
+ + req.body.nf_ip_count + ","
+ + assign_ips + ","
+ + assign_macs + ","
+ + assign_floating_ip + ")";
+ }
+ else
+ {
+ var sql = "INSERT INTO VM_NETWORKS (vnf_type,vm_type,network_role,assign_ips,assign_macs,assign_floating_ip) VALUES ("
+ + "'" + req.body.nf_vnf_type + "',"
+ + "'" + req.body.nf_vm_type + "',"
+ + "'" + req.body.nf_network_role + "',"
+ + assign_ips + ","
+ + assign_macs + ","
+ + assign_floating_ip + ")";
+ }
+
+ tasks.push( function(callback) { dbRoutes.executeSQL(sql,req,res,callback); } );
+ async.series(tasks, function(err,result){
+ msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVmNetworks(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully added VM Network');
+ var message = '';
+ if (req.body.nf_ip_count.length >0)
+ {
+ message = req.body.nf_vnf_type
+ + ',' + req.body.nf_vm_type
+ + ',' + req.body.nf_network_role
+ + ',' + req.body.nf_ip_count
+ + ',' + req.body.nf_assign_ips
+ + ',' + req.body.nf_assign_macs
+ + ',' + req.body.nf_assign_floating_ip;
+ }
+ else
+ {
+ message = req.body.nf_vnf_type
+ + ',' + req.body.nf_vm_type
+ + ',' + req.body.nf_network_role
+ + ',' + req.body.nf_assign_ips
+ + ',' + req.body.nf_assign_macs
+ + ',' + req.body.nf_assign_floating_ip;
+ }
+ dbRoutes.getVmNetworks(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+});
+
+// POST
+router.post('/uploadVnfData', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res)
+{
+console.log('filename:'+ JSON.stringify(req.file.originalname));
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname)
+ {
+ if (req.file.originalname.size == 0) {
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists)
+ {
+ if(exists)
+ {
+ var str = req.file.originalname;
+ var content;
+ var enc_content;
+
+ try{
+ content = fs.readFileSync(req.file.path);
+ enc_content = encodeURI(content);
+
+
+ var sql = "INSERT INTO PRE_LOAD_VNF_DATA "
+ + "(filename,preload_data) VALUES ("
+ + "'"+ str + "'," + "'" + enc_content + "')";
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.addRow(sql,req,res,callback); } );
+ async.series(tasks, function(err,result)
+ {
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully uploaded ' + str);
+ dbRoutes.getVnfData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ catch(error){
+ fs.removeSync(req.file.path); // remove bad file that was uploaded
+ console.error("There was an error reading the file '"+str+"'. Error: " + error);
+ msgArray.push("There was an error reading the file '"+str+"'. Error: " + error);
+ dbRoutes.getVnfData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfData(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else
+ {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfData(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+router.post('/uploadVnfNetworkData', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res)
+{
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname)
+ {
+ if (req.file.originalname.size == 0) {
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists)
+ {
+ if(exists)
+ {
+ var str = req.file.originalname;
+ var content;
+ var enc_content;
+
+ try{
+ content = fs.readFileSync(req.file.path);
+ enc_content = encodeURI(content);
+
+ var sql = "INSERT INTO PRE_LOAD_VNF_NETWORK_DATA "
+ + "(filename,preload_data) VALUES ("
+ + "'"+ str + "'," + "'" + enc_content + "')";
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.addRow(sql,req,res,callback); } );
+ async.series(tasks, function(err,result)
+ {
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfNetworkData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ msgArray.push('Successfully uploaded ' + str);
+ dbRoutes.getVnfNetworkData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ catch(error){
+ fs.removeSync(req.file.path); // remove bad file that was uploaded
+ msgArray.push("There was an error reading the file '"+str+"'. Error: " + error);
+ dbRoutes.getVnfNetworkData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfNetworkData(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else
+ {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfNetworkData(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+
+router.post('/uploadVmNetworks', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVmNetworks(req,res,{code:'failure', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVmNetwork(lrow,res,callback); }
+ }
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.parallelLimit(funcArray, 50, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVmNetworks(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getVmNetworks(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getVmNetworks(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVmNetworks(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVmNetworks(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+
+} );
+
+router.post('/uploadVnfProfile', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname)
+ {
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVnfProfile(req,res,{code:'failure', msg:'There was an error uploading the file, please try again.'},privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVnfProfile(lrow,res,callback); }
+ }
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.series(funcArray, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVnfProfile(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+console.log('rowError='+rowError);
+ var rowsProcessed = f.length - rowError;
+console.log('rowsProcessed='+rowsProcessed);
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+console.log('result='+JSON.stringify(result));
+ dbRoutes.getVnfProfile(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ console.error('There was an error uploading the file. '+ex);
+ dbRoutes.getVnfProfile(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfProfile(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfProfile(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+} );
+
+
+router.post('/uploadVnfNetworks', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname)
+ {
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVnfProfile(req,res,
+ {code:'failure', msg:'There was an error uploading the file, please try again.'},
+ privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVnfNetwork(lrow,res,callback); }
+ }
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.series(funcArray, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVnfNetworks(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getVnfNetworks(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getVnfNetworks(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfNetworks(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVnfNetworks(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+} );
+
+router.post('/uploadVmProfile', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res){
+
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ if(req.file.originalname)
+ {
+ if (req.file.originalname.size == 0) {
+ dbRoutes.getVmProfile(req,res,
+ {code:'failure', msg:'There was an error uploading the file, please try again.'},
+ privilegeObj);
+ return;
+ }
+ fs.exists(req.file.path, function(exists) {
+
+ if(exists) {
+
+ var str = req.file.originalname;
+
+ try {
+ var csv = require('csv');
+
+ // the job of the parser is to convert a CSV file
+ // to a list of rows (array of rows)
+ var parser = csv.parse({
+ columns: function(line) {
+ // By defining this callback, we get handed the
+ // first line of the spreadsheet. Which we'll
+ // ignore and effectively skip this line from processing
+ },
+ skip_empty_lines: true
+ });
+
+ var row = 0;
+ var f = new Array();
+ var transformer = csv.transform(function(data){
+ // this will get row by row data, so for example,
+ //logger.debug(data[0]+','+data[1]+','+data[2]);
+
+ // build an array of rows
+ f[row] = new Array();
+ for ( col=0; col<data.length; col++ )
+ {
+ f[row][col] = data[col];
+ }
+ row++;
+ });
+
+ // called when done with processing the CSV
+ transformer.on("finish", function() {
+
+ var funcArray = new Array();
+
+ function createFunction(lrow,res)
+ {
+ return function(callback) { dbRoutes.addVmProfile(lrow,res,callback); }
+ }
+ // loop for each row and create an array of callbacks for async.parallelLimit
+ // had to create a function above 'createFunction' to get
+ for (var x=0; x<f.length; x++)
+ {
+ funcArray.push( createFunction(f[x],res) );
+ }
+
+ // make db calls in parrallel
+ async.series(funcArray, function(err,result){
+
+ if ( err ) {
+ dbRoutes.getVmProfile(req,res,result,privilegeObj);
+ return;
+ }
+ else {
+ // result array has an entry in it, success entries are blank, figure out
+ // how many are not blank, aka errors.
+ var rowError = 0;
+ for(var i=0;i<result.length;i++){
+ if ( result[i].length > 0 )
+ {
+ rowError++;
+ }
+ }
+ var rowsProcessed = f.length - rowError;
+ result.push(rowsProcessed + ' of ' + f.length + ' rows processed.');
+ if ( rowError > 0 )
+ {
+ result = {code:'failure', msg:result};
+ }
+ else
+ {
+ result = {code:'success', msg:result};
+ }
+ dbRoutes.getVmProfile(req,res,result,privilegeObj);
+ return;
+ }
+ });
+ });
+
+ var stream = fs.createReadStream(req.file.path, "utf8");
+ stream.pipe(parser).pipe(transformer);
+
+ } catch(ex) {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file. '+ex);
+ dbRoutes.getVmProfile(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ } else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVmProfile(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+ }
+ else {
+ msgArray.length = 0;
+ msgArray.push('There was an error uploading the file.');
+ dbRoutes.getVmProfile(req,res,{code:'danger', msg:msgArray},privilegeObj);
+ return;
+ }
+} );
+
+module.exports = router;
diff --git a/admportal/server/router/routes/network.js b/admportal/server/router/routes/network.js
new file mode 100644
index 00000000..c64beae2
--- /dev/null
+++ b/admportal/server/router/routes/network.js
@@ -0,0 +1,400 @@
+
+// Helper functions for processing a NETWORK worksheet
+
+var helpers = require('./helpers.js');
+var _ = require('lodash');
+var csvtojson = require('csvtojson');
+var async = require('async');
+var uuid = require('node-uuid'); // generate a uuid with "uuid.v1()"
+var path = require('path');
+var fs = require("fs");
+var moment = require("moment");
+
+var network = module.exports;
+var getParam = helpers.getParam;
+
+var indir;
+var csvGeneral, csvSubnets, csvVpnBindings, csvPolicies, csvNetRoutes;
+var rawJson={}
+var finalJson={};
+var platform;
+var req,res;
+var preloadVersion; // 1607, 1610, etc...
+
+puts = helpers.puts;
+putd = helpers.putd;
+
+network.go = function(lreq,lres,cb,dir) {
+ puts("Processing NETWORK workbook");
+ req = lreq;
+ res = lres;
+ callback = cb;
+ if (dir!="") {
+ platform="pc";
+ indir=dir;
+ } else {
+ platform="portal";
+ indir=process.cwd() + "/uploads/";
+ }
+ doGeneral();
+}
+
+// READ WORKSHEET: GENERAL
+
+function doGeneral() {
+ puts("Reading General worksheet");
+ var csvFilename="General.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotGeneral);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotGeneral(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('General.csv file is missing from upload.');
+ return;
+ }
+ csvGeneral = jsonObj;
+ puts("\nRead this: ");
+ putd(csvGeneral);
+ puts("\n");
+ doSubnets();
+}
+
+// READ WORKSHEET: SUBNETS
+
+function doSubnets() {
+ puts("Reading Subnets worksheet");
+ var csvFilename="Subnets.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotSubnets);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotSubnets(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('Subnets.csv file is missing from upload.');
+ return;
+ }
+ csvSubnets = jsonObj;
+ csvSubnets = _.reject(csvSubnets, 'field2', 'Subnets');
+ csvSubnets = _.reject(csvSubnets, 'field2', 'start-address');
+ csvSubnets = _.reject(csvSubnets, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvSubnets);
+ puts("\n");
+ doVpnBindings();
+}
+
+// READ WORKSHEET: VPN-BINDINGS
+
+function doVpnBindings() {
+ puts("Reading VPN-Bindings worksheet");
+ var csvFilename="VPN-Bindings.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotVpnBindings);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotVpnBindings(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('VPN-Bindings.csv file is missing from upload.');
+ return;
+ }
+ csvVpnBindings = jsonObj;
+ csvVpnBindings = _.reject(csvVpnBindings, 'field2', 'VPN-Bindings');
+ csvVpnBindings = _.reject(csvVpnBindings, 'field2', 'vpn-binding-id');
+ csvVpnBindings = _.reject(csvVpnBindings, function(o) { return (_.trim(o.field2)=="") && (_.trim(o.field3)==""); } );
+ puts("\nRead this: ");
+ putd(csvVpnBindings);
+ puts("\n");
+ doPolicies();
+}
+
+
+// READ WORKSHEET: POLICIES
+
+function doPolicies() {
+ puts("Reading Policies worksheet");
+ var csvFilename="Policies.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotPolicies);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotPolicies(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('Policies.csv file is missing from upload.');
+ return;
+ }
+ csvPolicies = jsonObj;
+ csvPolicies = _.reject(csvPolicies, 'field2', 'Policies');
+ csvPolicies = _.reject(csvPolicies, 'field2', 'network-policy-fqdn');
+ csvPolicies = _.reject(csvPolicies, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvPolicies);
+ puts("\n");
+ doNetRoutes();
+}
+
+
+// READ WORKSHEET: NETWORK-ROUTES
+
+function doNetRoutes() {
+ puts("Reading Network-Routes worksheet");
+ var csvFilename="Network-Routes.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ preloadVersion = getParam(csvGeneral, 'field2', 'preload-version', 'field3');
+ if ( preloadVersion == '1607' ) {
+ puts("This is a 1607 spreadsheet. Skipping Network-Routes.csv.");
+ gotNetRoutes(null,{});
+ return;
+ }
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotNetRoutes);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotNetRoutes(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('Network-Routes.csv file is missing from upload.');
+ return;
+ }
+ csvNetRoutes = jsonObj;
+ csvNetRoutes = _.reject(csvNetRoutes, 'field2', 'Network-Routes');
+ csvNetRoutes = _.reject(csvNetRoutes, 'field2', 'route-table-reference-fqdn');
+ csvNetRoutes = _.reject(csvNetRoutes, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvNetRoutes);
+ puts("\n");
+ doneReadingFiles();
+}
+
+
+// DONE READING FILES
+
+function doneReadingFiles() {
+ puts("\n");
+ puts("DONE READING FILES!");
+ puts("\n");
+ processJson();
+}
+
+
+// PROCESS THE CSV FILES INTO OBJECTS TO BE ASSEMBLED INTO FINAL OUTPUT
+function processJson() {
+ processGeneral();
+ processSubnets();
+ processVpnBindings();
+ processPolicies();
+ processNetRoutes();
+ assembleJson();
+}
+
+// ASSEMBLE AND OUTPUT RESULTS
+
+function assembleJson() {
+ puts("\n");
+ puts("Using raw JSON and assembling final ouptut JSON.");
+ puts("\n");
+
+ networkTopoID = { "network-name": rawJson['network-name'],
+ "network-role": rawJson['network-role'],
+ "network-type": rawJson['network-type'],
+ "network-technology": rawJson['network-technology'] };
+
+ providerInfo = { "physical-network-name": rawJson['physical-network-name'],
+ "is-provider-network": rawJson['is-provider-network'],
+ "is-shared-network": rawJson['is-shared-network'],
+ "is-external-network": rawJson['is-external-network'] };
+
+ networkSubnets = rawJson['subnets'];
+
+ networkVpnBindings = rawJson['vpn-bindings'];
+
+ networkPolicies = rawJson['network-policy-fqdns'];
+
+ networkRoutes = rawJson['route-table-reference'];
+
+ networkTopo = { "network-topology-identifier": networkTopoID,
+ "provider-network-information": providerInfo,
+ "subnets": networkSubnets,
+ "vpn-bindings": networkVpnBindings,
+ "network-policy": networkPolicies,
+ "route-table-reference": networkRoutes};
+
+ networkInput = {'network-topology-information': networkTopo};
+
+ finalJson = {"input": networkInput};
+
+ outputJson();
+}
+
+function outputJson() {
+ puts("\n");
+ puts("\n");
+ puts(JSON.stringify(finalJson,null,2));
+ puts("\n");
+ puts("\n");
+ var unixTime, fullpath_filename, filename;
+ unixTime = moment().unix();
+ if (platform=='portal') {
+ fullpath_filename = process.cwd() + "/uploads/" + unixTime + ".net_worksheet.json";
+ filename = unixTime + ".net_worksheet.json.";
+ } else {
+ fullpath_filename = "./output.json."+unixTime;
+ filename = "output.json." + unixTime;
+ }
+ helpers.writeOutput(req, fullpath_filename, JSON.stringify(finalJson,null,2), callback);
+ callback(null, finalJson, filename);
+}
+
+
+// Gather functions that actually process data after it is all read
+
+function processGeneral() {
+ preloadVersion = getParam(csvGeneral, 'field2', 'preload-version', 'field3');
+ rawJson['preload-version'] = preloadVersion;
+ puts("Preload version: " + preloadVersion);
+
+ if ( (preloadVersion!='1607') && (preloadVersion!='1610') ) {
+ puts("\nError - incorrect version of preload worksheet.");
+ callback('Error - incorrect version of preload worksheet.');
+ }
+
+ rawJson['network-name'] = getParam(csvGeneral, 'field2', 'network-name', 'field3');
+ rawJson['network-role'] = getParam(csvGeneral, 'field2', 'network-role', 'field3');
+ rawJson['network-type'] = getParam(csvGeneral, 'field2', 'network-type', 'field3');
+ rawJson['network-technology'] = getParam(csvGeneral, 'field2', 'network-technology', 'field3');
+
+ if ( preloadVersion!='1607' ) {
+ rawJson['physical-network-name'] = getParam(csvGeneral, 'field2', 'physical-network-name', 'field3');
+ rawJson['is-provider-network'] = getParam(csvGeneral, 'field2', 'is-provider-network', 'field3');
+ rawJson['is-shared-network'] = getParam(csvGeneral, 'field2', 'is-shared-network', 'field3');
+ rawJson['is-external-network'] = getParam(csvGeneral, 'field2', 'is-external-network', 'field3');
+ }
+
+ rawJson['request-action'] = "PreloadNetworkRequest";
+ rawJson['svc-request-id'] = uuid.v1();
+ rawJson['svc-action'] = "reserve";
+ puts('rawJson:');
+ putd(rawJson);
+ puts("\n");
+}
+
+function processSubnets() {
+ var newSubnets = [];
+ csvSubnets.forEach( function(subnet) {
+ var subnetJson = {};
+ subnetJson["start-address"] = subnet.field2;
+ if (subnet.field3!='') {
+ subnetJson["dhcp-start-address"] = subnet.field3;
+ }
+ if (subnet.field4!='') {
+ subnetJson["dhcp-end-address"] = subnet.field4;
+ }
+ if (subnet.field5!='') {
+ subnetJson["gateway-address"] = subnet.field5;
+ }
+ subnetJson["cidr-mask"] = subnet.field6;
+ subnetJson["ip-version"] = subnet.field7;
+ subnetJson["dhcp-enabled"] = subnet.field8;
+ subnetJson["subnet-name"] = subnet.field9;
+ newSubnets.push(subnetJson);
+ }
+ );
+ puts("subnets:");
+ putd(newSubnets);
+ puts("\n");
+ rawJson["subnets"] = newSubnets;
+}
+
+function processVpnBindings() {
+ var newVpnBindings = [];
+
+ csvVpnBindings.forEach( function(vpn) {
+ var vpnJson = {};
+ bindid = _.trim(vpn.field2);
+ vpnJson["vpn-binding-id"] = bindid;
+ if (bindid!="") {
+ newVpnBindings.push(vpnJson);
+ }
+ });
+
+ puts("VPN-Bindings:");
+ putd(newVpnBindings);
+ puts("\n");
+ rawJson["vpn-bindings"] = newVpnBindings;
+}
+
+function processPolicies() {
+ var newPolicies = [];
+
+ csvPolicies.forEach( function(policy) {
+ var policyJson = {};
+ fqdn = _.trim(policy.field2);
+ if (fqdn != "") {
+ policyJson["network-policy-fqdn"] = fqdn;
+ newPolicies.push(policyJson);
+ }
+
+ }
+ );
+
+ puts("Policies:");
+ putd(newPolicies);
+ puts("\n");
+ rawJson["network-policy-fqdns"] = newPolicies;
+}
+
+function processNetRoutes() {
+ var newNetRoutes = [];
+
+ csvNetRoutes.forEach( function(netroute) {
+ var netrouteJson = {};
+ fqdn = _.trim(netroute.field2);
+ if (fqdn != "") {
+ netrouteJson["route-table-reference-fqdn"] = fqdn;
+ newNetRoutes.push(netrouteJson);
+ }
+
+ }
+ );
+
+ puts("Network-Routes:");
+ putd(newNetRoutes);
+ puts("\n");
+ rawJson["route-table-reference"] = newNetRoutes;
+}
+
+
+
diff --git a/admportal/server/router/routes/odl.js b/admportal/server/router/routes/odl.js
new file mode 100644
index 00000000..fba646fa
--- /dev/null
+++ b/admportal/server/router/routes/odl.js
@@ -0,0 +1,258 @@
+var express = require('express');
+var router = express.Router();
+var csp = require('./csp');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+var async = require('async');
+
+
+// pass host, username and password to ODL
+var username = properties.odlUser;
+var password = properties.odlPasswd;
+var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
+
+// target host for ODL request
+var host = properties.odlHost;
+var port = properties.odlPort;
+var header = {'Host': host, 'Authorization': auth, 'Content-Type': 'application/yang.data+json'};
+var options = {
+ host: host,
+ headers : header,
+ port : port,
+ rejectUnauthorized: false,
+ strictSSL : false
+};
+
+// Connection to OpenDaylight
+Odl = require('./Odl');
+
+function handleResult(err, response_str, res) {
+ if (err) {
+ console.error( String(err) );
+ res.render('pages/err', {result:{code:'failure', msg:String(err)}, header:process.env.MAIN_MENU});
+ } else {
+ // make sure response starts with JSON string
+ if (response_str && response_str.indexOf('{') == 0) {
+ //console.log("response: ", result);
+ res.render('odl/listWklst', { response_obj: JSON.parse(response_str), header:process.env.MAIN_MENU });
+ } else {
+ res.render('pages/err', {result:{code:'failure', msg:String(err) }, header:process.env.MAIN_MENU});
+ }
+ }
+}
+
+// / index page
+// calls restconf to get information
+router.get('/listWklst', csp.checkAuth, function(req, res) {
+ options.strictSSL = true; // used to test SSL certificate
+ Odl.Get('/restconf/config/L3SDN-API:services',options, handleResult,req,res);
+});
+
+router.get('/pageWklst', csp.checkAuth, function(req,res) {
+ pageWklst(req,res, {code:'', msg:''}, req.session.loggedInAdmin);
+});
+
+
+function pageWklst(req,res,resultObj,privilegeObj)
+{
+ if(req.session == null || req.session == undefined
+ || req.session.l3sdnPageInfo == null || req.session.l3sdnPageInfo == undefined)
+ {
+ res.render("pages/err",
+ { result: {code:'error', msg:"Unable to read session information. "+ String(err) }, header:process.env.MAIN_MENU});
+ return;
+ }
+
+ var l3sdnPageInfo = req.session.l3sdnPageInfo;
+ var currentPage=1;
+ if (typeof req.query.page != 'undefined')
+ {
+ currentPage = +req.query.page;
+ }
+ l3sdnPageInfo.currentPage = currentPage;
+ l3sdnPageInfo.rows = l3sdnPageInfo.pages[currentPage-1];
+ req.session.l3sdnPageInfo = l3sdnPageInfo;
+ res.render('odl/listWklst',
+ {
+ pageInfo : l3sdnPageInfo,
+ result : resultObj,
+ privilege : privilegeObj, header:process.env.MAIN_MENU
+ });
+ return;
+}
+
+
+router.post('/update_vr_lan_interface', function(req,res){
+ var svc_instance_id = encodeURIComponent(req.body.svc_instance_id);
+
+ // format msg
+ var msgRsp =
+ {
+ "vr-lan-interface" :
+ [
+ {
+ "vr-designation" : req.body.uf_vr_designation,
+ "v6-vr-lan-prefix" : req.body.uf_vr_lan_prefix,
+ "v6-vr-lan-prefix-length": req.body.uf_vr_lan_prefix_length,
+ "v6-vce-wan-address" : req.body.uf_vce_wan_address,
+ "v4-vr-lan-prefix" : req.body.uf_vr_lan_prefix,
+ "v4-vr-lan-prefix-length": req.body.uf_vr_lan_prefix_length,
+ "v4-vce-loopback-address": req.body.uf_vce_loopback_address
+ }
+ ]
+ };
+ var tasks = [];
+ tasks.push(function(callback){
+ Odl.put_vr_lan_interface('/restconf/config/L3SDN-API:services/layer3-service-list/'
+ + svc_instance_id
+ + '/service-data/vr-lan/', options, callback);
+ });
+ async.series(tasks, function(err,result){
+
+ if(err){
+ }
+ else{
+ var msgArray = new Array();
+ //result:{code:'error', msg:"got vr-lan information: "+ String(result)}
+ msgArray.push('vr-lan-interface successfully updated.');
+ res.render("odl/listVRlan",
+ {
+ svc_instance_id: req.body.svc_instance_id,
+ response_obj : JSON.parse(result), header:process.env.MAIN_MENU
+ });
+ return;
+ }
+ });
+});
+
+
+// sendData submits form data to ODL
+// Data is read from URL params and converted to JSON
+router.get('/svc-topology-operation', function(req, res) {
+ var formData = '{"input":{'
+ + '"svc-request-id":"'+ new Date().toISOString() + '"' +','
+ + '"svc-notification-url":"'+ req.query['svc-notification-url']+ '"' + ','
+ + '"svc-action":"'+ req.query['svc-action']+ '"' + ','
+ + '"svc-vnf-type":"'+ req.query['svc-vnf-type']+ '"' + ','
+ + '"svc-instance-id":"'+ req.query['svc-instance-id']+ '"' + ','
+ + '"svc-aic-site-id":"'+ req.query['svc-aic-site-id']+ '"'
+ +' } }';
+ Odl.Post('/restconf/operations/L3SDN-API:svc-topology-operation', options, formData, handleResult, res);
+});
+
+// delete request
+router.get('/wklist-delete', function(req, res) {
+ //console.dir(req.query);
+ Odl.Delete('/restconf/config/L3SDN-API:l3sdn-api-worklist/requests/'+req.query['request'], options, handleResult, res);
+});
+
+// get request
+router.get('/getid',function(req, res) {
+ //console.dir(req.query);
+ Odl.GetID('/restconf/config/L3SDN-API:l3sdn-api-worklist/requests/'+req.query['request'], options, res);
+});
+
+router.get('/getvnf', function(req,res) {
+ //console.log("/getvnf "+req.query);
+ Odl.GetVNF('/restconf/config/L3SDN-API:l3sdn-api-worklist/requests/'+req.query['request']+'/vnf/',options,req,res);
+});
+router.get('/getvrlan', function(req,res) {
+ var vrtasks = [];
+ var reqstr = encodeURIComponent(req.query['request']);
+ vrtasks.push(function(callback) {
+ Odl.GetVRlan('/restconf/config/L3SDN-API:services/layer3-service-list/'+reqstr+'/service-data/vr-lan/',options,callback);
+ });
+ async.series(vrtasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ Odl.Get('/restconf/config/L3SDN-API:services',options, handleResult,res);
+ //res.render("pages/err",
+ //{result:{code:'error', msg:"Unable to get vr-lan information: "+ String(err) }});
+ return;
+ }
+ else {
+ msgArray.push('Row successfully deleted from AIC_SITE table.');
+ res.render("odl/listVRlan",
+ {
+ svc_instance_id: req.query['request'],
+ response_obj : JSON.parse(result), header:process.env.MAIN_MENU
+ });
+ return;
+ }
+ });
+});
+router.get('/getClusterStatus', function(req,res) {
+
+
+ var urltasks = [];
+ var _header = {'Host': host, 'Authorization': auth, 'Content-Type': 'application/yang.data+json'};
+ var _options = null;
+
+ var slist = properties.shard_list;
+ var hlist = properties.hostnameList;
+ var port = properties.clusterPort;
+ var prefix_url = properties.clusterPrefixURL;
+ var mid_url = properties.clusterMidURL;
+ var suffix_url = properties.clusterSuffixURL;
+ var urlArray = new Array();
+ var url_request='';
+ var shard=null, hostname=null;
+
+ // build array of urls from properties
+ for(var x=0; x<slist.length; x++)
+ {
+ shard = slist[x];
+ for(var y=0; y<hlist.length; y++)
+ {
+ hostname = hlist[y];
+
+ url_request = properties.odlProtocol + '://'
+ + hostname.hname + ':'
+ + port
+ + prefix_url
+ + (y+1)
+ + mid_url
+ + shard.shard_name
+ + suffix_url;
+
+ _options = {
+ method : "GET",
+ path : url_request,
+ host : hostname.hname,
+ headers : _header,
+ port : port,
+ rejectUnauthorized: false,
+ strictSSL : false
+ };
+ urlArray.push(_options);
+ }
+ }
+
+ urlArray.forEach(function(request){
+ urltasks.push(function(callback) {
+ Odl.GetClusterStatus(request,callback);
+ });
+ });
+ async.series(urltasks, function(err,result){
+ var msgArray = new Array();
+ if(err){
+ msgArray.push(err);
+ res.render("pages/err",
+ {result:{code:'error', msg:"Unable to get status: "+ String(err) }, header:process.env.MAIN_MENU});
+ return;
+ }
+ else {
+ var msgArray = new Array();
+ msgArray.push('Sucess');
+ res.render("odl/cluster_status",
+ {
+ result : {code:'success', msg:msgArray},
+ response_obj : result, header:process.env.MAIN_MENU
+ });
+ return;
+ }
+ });
+});
+
+
+module.exports = router;
diff --git a/admportal/server/router/routes/preload.js b/admportal/server/router/routes/preload.js
new file mode 100644
index 00000000..1a63ec0e
--- /dev/null
+++ b/admportal/server/router/routes/preload.js
@@ -0,0 +1,154 @@
+var express = require('express');
+var router = express.Router();
+var exec = require('child_process').exec;
+var util = require('util');
+var fs = require('fs.extra');
+var dbRoutes = require('./dbRoutes');
+var csp = require('./csp');
+var multer = require('multer');
+var bodyParser = require('body-parser');
+var sax = require('sax'),strict=true,parser = sax.parser(strict);
+var async = require('async');
+var l_ = require('lodash');
+var dateFormat = require('dateformat');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+var vnf = require('./vnf');
+var network = require('./network');
+var moment = require('moment');
+
+
+
+// pass host, username and password to ODL
+// target host for ODL request
+var username = properties.odlUser;
+var password = properties.odlPasswd;
+var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
+var host = properties.odlHost;
+var port = properties.odlPort;
+
+var header = {'Host': host, 'Authorization': auth, 'Content-Type': 'application/json'};
+var options = {
+ host : host,
+ headers : header,
+ port : port,
+ rejectUnauthorized:false,
+ strictSSL: false
+};
+
+// Connection to OpenDaylight
+Odl = require('./Odl');
+
+// multer 1.1
+var unixTime = moment().unix();
+var storage = multer.diskStorage({
+ destination: function (req, file, cb) {
+ cb(null, process.cwd() + '/uploads/')
+ },
+ filename: function (req, file, cb) {
+ cb(null, unixTime + "." + file.originalname )
+ }
+});
+
+var upload = multer({
+ storage: storage,
+ fileFilter: function(req,file,cb) {
+ var type = file.mimetype;
+ if ( type.indexOf('ms-excel') == -1 ) {
+ return cb(null,false);
+ }
+ cb(null,true);
+ }
+});
+
+router.post('/uploadVnfCsv', csp.checkAuth, dbRoutes.checkDB, upload.array('filename'), function(req, res)
+{
+ console.log('files:'+ JSON.stringify(req.files,null,4));
+
+ var tasks = []
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+
+ tasks.push ( function(callback) { vnf.go(req,res,callback,''); } );
+ tasks.push ( function(arg1,arg2,callback) { formatVnfInsertStatement(arg1,arg2,req,res,callback); } );
+ tasks.push( function(arg1, callback) { dbRoutes.addRow(arg1,req,res,callback); } );
+ async.waterfall(tasks, function(err,result)
+ {
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ //logger.debug('Successfully uploaded ' + req.session.worksheetFilename);
+ msgArray.push('Successfully uploaded file.' );
+ dbRoutes.getVnfData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+
+});
+
+router.post('/uploadNetworkCsv', csp.checkAuth, dbRoutes.checkDB, upload.array('filename'), function(req, res)
+{
+ console.log('files:'+ JSON.stringify(req.files,null,4));
+
+ var tasks = []
+ var msgArray = new Array();
+ var privilegeObj = req.session.loggedInAdmin;
+
+ var privilegeObj = req.session.loggedInAdmin;
+ var tasks = [];
+
+ tasks.push ( function(callback) { network.go(req,res,callback,''); } );
+ tasks.push ( function(arg1,arg2,callback) { formatNetworkInsertStatement(arg1,arg2,req,res,callback); } );
+ tasks.push( function(arg1, callback) { dbRoutes.addRow(arg1,req,res,callback); } );
+ async.waterfall(tasks, function(err,result)
+ {
+ if(err){
+ msgArray.push(err);
+ dbRoutes.getVnfNetworkData(req,res,{code:'failure', msg:msgArray},privilegeObj);
+ return;
+ }
+ else {
+ //logger.debug('Successfully uploaded ' + req.session.worksheetFilename);
+ msgArray.push('Successfully uploaded file.' );
+ dbRoutes.getVnfNetworkData(req,res,{code:'success', msg:msgArray},privilegeObj);
+ return;
+ }
+ });
+
+});
+
+
+function formatVnfInsertStatement(content,filename,req,res,callback)
+{
+ //var newstr = JSON.stringify(content).replace(/\\\"/g,'\\\\\\"');
+ //var ins_str = newstr.replace("\r\n ", "\\r\\n");
+ var newstr = JSON.stringify(content);
+ var enc_str = encodeURI(newstr);
+ var sql = "INSERT INTO PRE_LOAD_VNF_DATA "
+ + "(filename,preload_data) VALUES ("
+ + "'"+ filename + "',"
+ + "'" + enc_str + "')";
+
+ callback(null,sql);
+}
+
+function formatNetworkInsertStatement(content,filename,req,res,callback)
+{
+ var newstr = JSON.stringify(content);
+ var enc_str = encodeURI(newstr);
+ var sql = "INSERT INTO PRE_LOAD_VNF_NETWORK_DATA "
+ + "(filename,preload_data) VALUES ("
+ + "'"+ filename + "',"
+ + "'" + enc_str + "')";
+
+ callback(null,sql);
+}
+
+
+
+module.exports = router;
diff --git a/admportal/server/router/routes/root.js b/admportal/server/router/routes/root.js
new file mode 100644
index 00000000..f586892b
--- /dev/null
+++ b/admportal/server/router/routes/root.js
@@ -0,0 +1,111 @@
+var express = require('express');
+var router = express.Router();
+var csp = require('./csp.js');
+var dbRoutes = require('./dbRoutes.js');
+var sla = require('./sla');
+var os = require('os');
+var async = require('async');
+var Odl = require('./Odl');
+var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json');
+
+
+
+router.use('/healthcheck', function(req,res){
+ res.render('pages/healthcheck');
+});
+router.get('/test', function(req,res){
+
+//console.log('port='+ req.socket.localPort);
+//console.log('port='+ req.protocol);
+
+ // pass host, username and password to ODL
+ var username = properties.odlUser;
+ var password = properties.odlPasswd;
+ var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
+
+ // target host for ODL request
+ var host = properties.odlHost;
+ var header = {'Host': host, 'Authorization': auth, 'Content-Type': 'application/yang.data+json'};
+ var c_header = {'Host': properties.odlConexusHost, 'Authorization': auth, 'Content-Type': 'application/yang.data+json'};
+
+// path = '/restconf/config/SLI-API:healthcheck',
+ var _options = {
+ method : 'POST',
+ host : host,
+ headers : header,
+ port : '8443',
+ path : '/restconf/operations/SLI-API:healthcheck',
+ rejectUnauthorized: false,
+ strictSSL : false
+ };
+ var c_options = {
+ method : 'POST',
+ host : properties.odlConexusHost,
+ headers : c_header,
+ port : '8543',
+ path : '/restconf/operations/SLI-API:healthcheck',
+ rejectUnauthorized: false,
+ strictSSL : false
+ };
+
+
+ var tasks = [];
+ //tasks.push( function(callback) { dbRoutes.testdb(req,res,callback); } );
+
+ tasks.push ( createFunctionObj(_options) );
+
+ tasks.push ( createFunctionObj(c_options) );
+
+ async.series(tasks, function(err,result){
+ if(err) {
+ res.status(400).send(err);
+ return;
+ }
+ res.status(200).send(result);
+ return;
+ });
+});
+
+function createFunctionObj( loptions ) {
+ return function(callback) { Odl.Healthcheck(loptions,callback); };
+}
+
+router.get('/mytree', function(req,res) {
+ res.render('pages/tree');
+});
+router.get('/setuplogin', function(req,res) {
+ res.render('pages/setuplogin');
+});
+router.post('/formSetupLogin', dbRoutes.checkDB, function(req,res) {
+ dbRoutes.saveSetupLogin(req,res);
+});
+router.post('/formSignUp', dbRoutes.checkDB, function(req,res) {
+ dbRoutes.saveUser(req,res);
+});
+router.post('/formlogin', csp.login, dbRoutes.checkDB, function(req,res) {
+});
+router.get('/login', function(req,res) {
+ res.render('pages/login');
+ // handle get
+});
+router.get('/signup', function(req,res) {
+ res.render('pages/signup');
+ // handle get
+});
+router.get('/info', function(req,res) {
+ // handle get
+ res.send("login info");
+});
+router.get('/logout', csp.logout, function(req,res) {
+ // handle get
+});
+router.get('/csplogout', function(req,res) {
+ // handle get
+ res.render("pages/csplogout", {result:{code:'success', msg:'You have been successfylly logged out.'},header:process.env.MAIN_MENU});
+});
+router.get('/getuser', function(req,res) {
+ // handle get
+ res.render("pages/home");
+});
+
+module.exports = router;
diff --git a/admportal/server/router/routes/sla.js b/admportal/server/router/routes/sla.js
new file mode 100644
index 00000000..92fa846b
--- /dev/null
+++ b/admportal/server/router/routes/sla.js
@@ -0,0 +1,369 @@
+var express = require('express');
+var router = express.Router();
+var exec = require('child_process').exec;
+//var util = require('util');
+var fs = require('fs');
+var dbRoutes = require('./dbRoutes');
+var csp = require('./csp');
+var multer = require('multer');
+var bodyParser = require('body-parser');
+//var sax = require('sax'),strict=true,parser = sax.parser(strict);
+var async = require('async');
+
+
+// SVC_LOGIC table columns
+var _module=''; // cannot use module its a reserved word
+var version='';
+var rpc='';
+var mode='';
+var xmlfile='';
+
+
+// used for file upload button, retain original file name
+//router.use(bodyParser());
+router.use(bodyParser.urlencoded({
+ extended: true
+}));
+//var upload = multer({ dest: process.cwd() + '/uploads/', rename: function(fieldname,filename){ return filename; } });
+
+// multer 1.1
+var storage = multer.diskStorage({
+ destination: function (req, file, cb) {
+ cb(null, process.cwd() + '/uploads/')
+ },
+ filename: function (req, file, cb) {
+ cb(null, file.originalname )
+ }
+});
+
+var upload = multer({
+ storage: storage
+});
+
+
+/*
+router.use(multer({
+ dest: process.cwd() + '/uploads/',
+ rename: function(fieldname,filename){
+ return filename;
+ }
+}));
+*/
+
+
+//router.use(express.json());
+//router.use(express.urlencoded());
+//router.use(multer({ dest: './uploads/' }));
+
+
+// GET
+router.get('/listSLA', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.listSLA(req,res,{code:'', msg:''} );
+});
+
+router.get('/activate', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var _module = req.query.module;
+ var rpc = req.query.rpc;
+ var version = req.query.version;
+ var mode = req.query.mode;
+
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.global_deactivate(req,res,_module,rpc,mode,callback); } );
+ tasks.push( function(callback) { dbRoutes.activate(req,res,_module,rpc,version,mode,callback); } );
+ async.series(tasks, function(err,result){
+
+ if ( err ) {
+ dbRoutes.listSLA(req,res,{code:'failure', msg:'Failed to activate, '+ String(err) });
+ }
+ else {
+ dbRoutes.listSLA(req,res,{ code:'success', msg:'Successfully activated directed graph.'});
+ }
+ });
+});
+
+router.get('/deactivate', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var _module = req.query.module;
+ var rpc = req.query.rpc;
+ var version = req.query.version;
+ var mode = req.query.mode;
+
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.deactivate(req,res,_module,rpc,version,mode,callback); } );
+ async.series(tasks, function(err,result){
+
+ if ( err ) {
+ dbRoutes.listSLA(req,res,{code:'failure', msg:'There was an error uploading the file. '+ err });
+ }
+ else {
+ dbRoutes.listSLA(req,res,{ code:'success', msg:'Successfully deactivated directed graph.'});
+ }
+ });
+});
+
+router.get('/deleteDG', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ var _module = req.query.module;
+ var rpc = req.query.rpc;
+ var version = req.query.version;
+ var mode = req.query.mode;
+
+ var tasks = [];
+ tasks.push( function(callback) { dbRoutes.deleteDG(req,res,_module,rpc,version,mode,callback); } );
+ async.series(tasks, function(err,result){
+
+ if ( err ) {
+ dbRoutes.listSLA(req,res,{ code:'failure', msg:'There was an error uploading the file. '+ err });
+ }
+ else {
+ dbRoutes.listSLA(req,res,{ code:'success', msg:'Successfully deleted directed graph.'});
+ }
+ });
+});
+
+router.post('/dgUpload', dbRoutes.checkDB, upload.single('filename'), function(req, res, next){
+
+ if(req.file.originalname){
+ if (req.file.originalname == 0) {
+
+ dbRoutes.listSLA(req,res,{ code:'danger', msg:'There was an error uploading the file, please try again.'});
+ }
+ fs.exists(req.file.path, function(exists) {
+ if(exists) {
+
+ // parse xml
+ try {
+ //dbRoutes.checkSvcLogic(req,res);
+
+ var file_buf = fs.readFileSync(req.file.path, "utf8");
+
+ // call Dan's svclogic shell script from here
+ var currentDB = dbRoutes.getCurrentDB();
+ var commandToExec = process.cwd()
+ + "/shell/svclogic.sh load "
+ + req.file.path + " "
+ + process.env.SDNC_CONFIG_DIR + "/svclogic.properties." + currentDB;
+
+ console.log("commandToExec:" + commandToExec);
+ child = exec(commandToExec ,function (error,stdout,stderr){
+ if(error){
+ console.error("error:" + error);
+ //res.type('text/html').status(400).send( error);
+ //return;
+ }
+ if(stderr){
+ res.status(400).send(stderr);
+ return;
+ }
+ if(stdout){
+ res.status(200).send( new Buffer('Success'));
+ return;
+ }
+
+ // remove the grave accents, the sax parser does not like them
+ //parser.write(file_buf.replace(/\`/g,'').toString('utf8')).close();
+ //dbRoutes.addDG(_module,version,rpc,mode,file_buf,req,res);
+ //dbRoutes.listSLA(req,res, resultObj);
+ });
+ } catch(ex) {
+ // keep 'em silent
+ console.error('sax error:'+ex);
+ res.status(400).send(ex);
+ return;
+ }
+
+ } else {
+ res.status(400).send(new Buffer('Cannot find file.'));
+ return;
+
+ }
+ });
+ }
+ else {
+ res.status(400).send(new Buffer('file does not exist\n'));
+ }
+ return;
+});
+
+
+// POST
+router.post('/upload', csp.checkAuth, dbRoutes.checkDB, upload.single('filename'), function(req, res, next){
+
+console.log('file:'+ JSON.stringify(req.file));
+
+ if(req.file.originalname){
+ if (req.file.originalname.size == 0) {
+ dbRoutes.listSLA(req,res,{ code:'danger', msg:'There was an error uploading the file, please try again.'});
+ }
+ fs.exists(req.file.path, function(exists) {
+ if(exists) {
+
+ // parse xml
+ try {
+ //dbRoutes.checkSvcLogic(req,res);
+
+ var currentDB = dbRoutes.getCurrentDB();
+ var file_buf = fs.readFileSync(req.file.path, "utf8");
+
+ // call Dan's svclogic shell script from here
+ var commandToExec = process.cwd()
+ + "/shell/svclogic.sh load "
+ + req.file.path + " "
+ + process.env.SDNC_CONFIG_DIR + "/svclogic.properties." + currentDB;
+
+ console.log("commandToExec:" + commandToExec);
+ child = exec(commandToExec ,function (error,stdout,stderr){
+ if(error){
+ console.error("error:" + error);
+ dbRoutes.listSLA(req,res,{code:'failure',msg:error} );
+ return;
+ }
+ if(stderr){
+ console.error("stderr:" + JSON.stringify(stderr,null,2));
+ var s_stderr = JSON.stringify(stderr);
+ if ( s_stderr.indexOf("Saving") > -1 )
+ {
+ dbRoutes.listSLA(req,res,{code:'success', msg:'File sucessfully uploaded.'});
+ }else {
+ dbRoutes.listSLA(req,res,{code:'failure', msg:stderr});
+ }
+ return;
+ }
+ if(stdout){
+ console.log("stderr:" + stdout);
+ dbRoutes.listSLA(req,res,{code:'success', msg:'File sucessfully uploaded.'});
+ return;
+ }
+
+ // remove the grave accents, the sax parser does not like them
+ //parser.write(file_buf.replace(/\`/g,'').toString('utf8')).close();
+ //dbRoutes.addDG(_module,version,rpc,mode,file_buf,req,res);
+ //dbRoutes.listSLA(req,res, resultObj);
+ });
+ } catch(ex) {
+ // keep 'em silent
+ console.error("error:" + ex);
+ dbRoutes.listSLA(req,res,{code:'failure',msg:ex} );
+ }
+
+ } else {
+ dbRoutes.listSLA(req,res,{ code:'danger', msg:'There was an error uploading the file, please try again.'});
+ }
+ });
+ }
+ else {
+ dbRoutes.listSLA(req,res,{ code:'danger', msg:'There was an error uploading the file, please try again.'});
+ }
+});
+
+router.get('/printAsXml', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ try {
+ //dbRoutes.checkSvcLogic(req,res);
+
+ var _module = req.query.module;
+ var rpc = req.query.rpc;
+ var version = req.query.version;
+ var mode = req.query.mode;
+ var currentDB = dbRoutes.getCurrentDB();
+
+ // call Dan's svclogic shell script from here
+ var commandToExec = process.cwd()
+ + "/shell/svclogic.sh get-source "
+ + _module + " "
+ + rpc + " "
+ + mode + " "
+ + version + " "
+ + process.env.SDNC_CONFIG_DIR + "/svclogic.properties." + currentDB;
+
+ console.log("commandToExec:" + commandToExec);
+
+ child = exec(commandToExec , {maxBuffer: 1024*5000}, function (error,stdout,stderr){
+ if(error){
+ console.error("error:" + error);
+ dbRoutes.listSLA(req,res,{code:'failure',msg:error} );
+ return;
+ }
+ //if(stderr){
+ //logger.info("stderr:" + stderr);
+ //}
+ if(stdout){
+ console.log("OUTPUT:" + stdout);
+ res.render('sla/printasxml', {result:{code:'success',
+ msg:'Module : ' + _module + '\n' +
+ 'RPC : ' + rpc + '\n' +
+ 'Mode : ' + mode + '\n' +
+ 'Version: ' + version + '\n\n' + stdout}, header:process.env.MAIN_MENU});
+ }
+
+ // remove the grave accents, the sax parser does not like them
+ //parser.write(file_buf.replace(/\`/g,'').toString('utf8')).close();
+ //dbRoutes.addDG(_module,version,rpc,mode,file_buf,req,res);
+ //dbRoutes.listSLA(req,res, resultObj);
+ });
+ } catch(ex) {
+ console.error("error:" + ex);
+ dbRoutes.listSLA(req,res,{code:'failure',msg:ex} );
+ }
+});
+
+
+router.get('/printAsGv', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ try {
+ //dbRoutes.checkSvcLogic(req,res);
+
+ var _module = req.query.module;
+ var rpc = req.query.rpc;
+ var version = req.query.version;
+ var mode = req.query.mode;
+ var currentDB = dbRoutes.getCurrentDB();
+console.log('currentDB='+currentDB);
+
+ // call Dan's svclogic shell script from here
+ var commandToExec = process.cwd()
+ + "/shell/svclogic.sh print "
+ + _module + " "
+ + rpc + " "
+ + mode + " "
+ + version + " "
+ + process.env.SDNC_CONFIG_DIR + "/svclogic.properties." + currentDB
+ + " | dot -Tpng";
+
+ console.log("commandToExec:" + commandToExec);
+
+ child = exec(commandToExec ,
+ {encoding:'base64',maxBuffer:5000*1024}, function (error,stdout,stderr){
+ if(error){
+ console.error("error:" + error);
+ dbRoutes.listSLA(req,res,{code:'failure',msg:error} );
+ return;
+ }
+ if(stderr){
+ console.error("stderr:" + stderr);
+ }
+ if(stdout){
+ //logger.info("OUTPUT:" + stdout);
+ //res.render('sla/printasgv', result = {code:'success',
+ //msg:new Buffer(stdout,'base64')} );
+ res.render('sla/printasgv', {result:{code:'success',
+ module: _module,
+ rpc: rpc,
+ version: version,
+ mode:mode,
+ msg:stdout}, header:process.env.MAIN_MENU});
+ }
+
+ // remove the grave accents, the sax parser does not like them
+ //parser.write(file_buf.replace(/\`/g,'').toString('utf8')).close();
+ //dbRoutes.addDG(_module,version,rpc,mode,file_buf,req,res);
+ //dbRoutes.listSLA(req,res, resultObj);
+ });
+ } catch(ex) {
+ console.error("error:" + ex);
+ dbRoutes.listSLA(req,res,{code:'failure',msg:ex} );
+ }
+
+});
+module.exports = router;
diff --git a/admportal/server/router/routes/user.js b/admportal/server/router/routes/user.js
new file mode 100644
index 00000000..116bf932
--- /dev/null
+++ b/admportal/server/router/routes/user.js
@@ -0,0 +1,169 @@
+var express = require('express');
+var router = express.Router();
+var exec = require('child_process').exec;
+var util = require('util');
+var fs = require('fs');
+var dbRoutes = require('./dbRoutes');
+var csp = require('./csp');
+var bodyParser = require('body-parser');
+var sax = require('sax'),strict=true,parser = sax.parser(strict);
+
+// SVC_LOGIC table columns
+var _module=''; // cannot use module its a reserved word
+var version='';
+var rpc='';
+var mode='';
+var xmlfile='';
+
+
+//router.use(bodyParser());
+router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+
+// GET
+router.get('/listUsers', csp.checkAuth, function(req,res) {
+ dbRoutes.listUsers(req,res, {user:req.session.loggedInAdmin,code:'', msg:''} );
+});
+router.get('/deleteUser', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.deleteUser(req,res, {code:'', msg:''} );
+});
+
+//router.get('/activate', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ //var _module = req.query.module;
+ //var rpc = req.query.rpc;
+ //var version = req.query.version;
+ //var mode = req.query.mode;
+
+ //dbRoutes.activate(req,res,_module,rpc,version,mode);
+//});
+
+//router.get('/deactivate', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ //var _module = req.query.module;
+ //var rpc = req.query.rpc;
+ //var version = req.query.version;
+ //var mode = req.query.mode;
+//
+ //dbRoutes.deactivate(req,res,_module,rpc,version,mode);
+//});
+
+//router.get('/deleteDG', csp.checkAuth, dbRoutes.checkDB, function(req,res){
+
+ //var _module = req.query.module;
+ //var rpc = req.query.rpc;
+ //var version = req.query.version;
+ //var mode = req.query.mode;
+
+ //dbRoutes.deleteDG(req,res,_module,rpc,version,mode);
+//});
+/*
+// SAX
+parser.onerror = function (e) {
+ logger.debug('onerror');
+ // an error happened.
+};
+parser.ontext = function (t) {
+ // got some text. t is the string of text.
+ logger.debug('ontext:'+t);
+};
+parser.onopentag = function (node) {
+ // opened a tag. node has "name" and "attributes"
+ if ( node.name == 'service-logic' )
+ {
+ _module = node.attributes.module;
+ version = node.attributes.version;
+ }
+ if ( node.name == 'method' )
+ {
+ rpc = node.attributes.rpc;
+ mode = node.attributes.mode;
+ }
+};
+parser.onattribute = function (attr) {
+ // an attribute. attr has "name" and "value"
+ logger.debug('onattribute:'+attr);
+};
+parser.onend = function () {
+ // parser stream is done, and ready to have more stuff written to it.
+ logger.debug('onend:');
+};
+*/
+
+
+// POST
+router.post('/updateUser', csp.checkAuth, dbRoutes.checkDB, function(req,res,next){
+ dbRoutes.updateUser(req,res,{code:'',msg:''});
+});
+router.post('/addUser', csp.checkAuth, dbRoutes.checkDB, function(req,res) {
+ dbRoutes.addUser(req,res, {code:'', msg:''} );
+});
+
+//router.post('/upload', csp.checkAuth, dbRoutes.checkDB, function(req, res, next){
+
+/*
+logger.debug("upload");
+ if(req.files.filename){
+ if (req.files.filename.size == 0) {
+ resultObj =
+ {code:'danger', msg:'There was an error uploading the file, please try again.'};
+ dbRoutes.listSLA(req,res, resultObj);
+ }
+ fs.exists(req.files.filename.path, function(exists) {
+ if(exists) {
+ resultObj = {code:'success', msg:'File sucessfully uploaded.'};
+
+ // parse xml
+ try {
+ var file_buf = fs.readFileSync(req.files.filename.path, "utf8");
+logger.debug('file '+req.files.filename);
+
+
+ // call Dan's svclogic shell script from here
+ var commandToExec = process.cwd()
+ + "/shell/svclogic.sh load "
+ + req.files.filename.path + " "
+ + process.cwd()
+ + "/config/svclogic.properties";
+
+ logger.debug("commandToExec:" + commandToExec);
+ child = exec(commandToExec ,function (error,stdout,stderr){
+ if(error){
+ logger.info("error:" + error);
+ }
+ if(stderr){
+ logger.info("stderr:" + stderr);
+ }
+ if(stdout){
+ logger.info("OUTPUT:" + stdout);
+ dbRoutes.listSLA(req,res, resultObj);
+ }
+
+ // remove the grave accents, the sax parser does not like them
+ //parser.write(file_buf.replace(/\`/g,'').toString('utf8')).close();
+ //dbRoutes.addDG(_module,version,rpc,mode,file_buf,req,res);
+ //dbRoutes.listSLA(req,res, resultObj);
+ });
+ } catch(ex) {
+ // keep 'em silent
+ logger.debug('sax error:'+ex);
+ }
+
+ } else {
+ resultObj =
+ {code:'danger', msg:'There was an error uploading the file, please try again.'};
+ dbRoutes.listSLA(req,res, resultObj);
+ }
+ });
+ }
+ else {
+ resultObj =
+ {code:'danger', msg:'There was an error uploading the file, please try again.'};
+ dbRoutes.listSLA(req,res, resultObj);
+ }
+});
+*/
+
+module.exports = router;
diff --git a/admportal/server/router/routes/vnf.js b/admportal/server/router/routes/vnf.js
new file mode 100644
index 00000000..be004fe2
--- /dev/null
+++ b/admportal/server/router/routes/vnf.js
@@ -0,0 +1,603 @@
+
+// Helper functions for processing a VNF worksheet
+
+var helpers = require('./helpers.js');
+var _ = require('lodash');
+var csvtojson = require('csvtojson');
+var async = require('async');
+var uuid = require('node-uuid'); // generate a uuid with "uuid.v1()"
+var path = require('path');
+var fs = require("fs");
+var moment = require("moment");
+
+var vnf = module.exports;
+var getParam = helpers.getParam;
+
+var callback;
+var indir;
+var csvGeneral, csvZones, csvNetworks, csvVMs, csvVMnetworks, csvVMnetworkIPs, csvVMnetworkMACs, csvTagValues;
+var rawJson={}
+var finalJson={};
+var platform;
+var req, res;
+var preloadVersion; // 1607, 1610, etc...
+
+puts = helpers.puts;
+putd = helpers.putd;
+
+vnf.go = function(lreq,lres,cb,dir){
+ puts("Processing VNF workbook");
+ req = lreq;
+ res = lres;
+ callback = cb;
+ if (dir!="") {
+ platform="pc";
+ indir=dir;
+ } else {
+ platform="portal";
+ indir=process.cwd() + "/uploads/";
+ }
+ doGeneral();
+}
+
+
+// READ WORKSHEET: GENERAL
+
+function doGeneral() {
+ puts("Reading General worksheet");
+ var csvFilename="General.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotGeneral);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotGeneral(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('General.csv file is missing from upload.');
+ return;
+ }
+ csvGeneral = jsonObj;
+ puts("\nRead this: ");
+ putd(csvGeneral);
+ puts("\n");
+ doAvailZones();
+}
+
+// READ WORKSHEET: AVAILABILITY ZONES
+
+function doAvailZones() {
+ puts("Reading Availability-zones worksheet");
+ var csvFilename="Availability-zones.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotAvailZones);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotAvailZones(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('Availability-zones.csv file is missing from upload.');
+ return;
+ }
+ csvZones = jsonObj;
+ csvZones = _.reject(csvZones, 'field2', 'Availability Zones');
+ csvZones = _.reject(csvZones, 'field2', 'List the availability zones for this VNF');
+ csvZones = _.reject(csvZones, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvZones);
+ puts("\n");
+ doNetworks();
+}
+
+// READ WORKSHEET: NETWORKS
+
+function doNetworks() {
+ puts("Reading Networks worksheet");
+ var csvFilename="Networks.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotNetworks);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotNetworks(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('Networks.csv file is missing from upload.');
+ return;
+ }
+ csvNetworks = jsonObj;
+ csvNetworks = _.reject(csvNetworks, 'field2', 'Networks');
+ csvNetworks = _.reject(csvNetworks, 'field2', 'List the VNF networks. (VM-networks are on a different worksheet.)');
+ csvNetworks = _.reject(csvNetworks, 'field2', 'network-role');
+ csvNetworks = _.reject(csvNetworks, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvNetworks);
+ puts("\n");
+ doVMs();
+}
+
+// READ WORKSHEET: VMs
+
+function doVMs() {
+ puts("Reading VMs worksheet");
+ var csvFilename="VMs.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotVMs);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotVMs(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('VMs.csv file is missing from upload.');
+ return;
+ }
+ csvVMs = jsonObj;
+ csvVMs = _.reject(csvVMs, 'field2', 'VMs');
+ csvVMs = _.reject(csvVMs, 'field2', 'List the VM types for this VNF');
+ csvVMs = _.reject(csvVMs, 'field2', 'vm-type');
+ csvVMs = _.reject(csvVMs, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvVMs);
+ puts("\n");
+ doVMnetworks();
+}
+
+// READ WORKSHEET: VM-NETWORKS
+
+function doVMnetworks() {
+ puts("Reading VM-networks worksheet");
+ var csvFilename="VM-networks.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotVMnetworks);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotVMnetworks(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('VM-networks.csv file is missing from upload.');
+ return;
+ }
+ csvVMnetworks = jsonObj;
+ csvVMnetworks = _.reject(csvVMnetworks, 'field2', 'VM-networks');
+ csvVMnetworks = _.reject(csvVMnetworks, 'field2', 'List the VM-networks for each VM type');
+ csvVMnetworks = _.reject(csvVMnetworks, 'field2', 'vm-type');
+ csvVMnetworks = _.reject(csvVMnetworks, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvVMnetworks);
+ puts("\n");
+ doVMnetworkIPs();
+}
+
+// READ WORKSHEET: VM-NETWORK-IPS
+
+function doVMnetworkIPs() {
+ puts("Reading VM-network-IPs worksheet");
+ var csvFilename="VM-network-IPs.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotVMnetworkIPs);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotVMnetworkIPs(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('VM-network-IPs.csv file is missing from upload.');
+ return;
+ }
+ csvVMnetworkIPs = jsonObj;
+ csvVMnetworkIPs = _.reject(csvVMnetworkIPs, 'field2', 'VM-network-IPs');
+ csvVMnetworkIPs = _.reject(csvVMnetworkIPs, 'field2', 'List the IPs assigned to each VM-network');
+ csvVMnetworkIPs = _.reject(csvVMnetworkIPs, 'field2', 'vm-type');
+ csvVMnetworkIPs = _.reject(csvVMnetworkIPs, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvVMnetworkIPs);
+ puts("\n");
+ doVMnetworkMACs();
+}
+
+// READ WORKSHEET: VM-NETWORK-MACS
+
+function doVMnetworkMACs() {
+ puts("Reading VM-network-MACs worksheet");
+ var csvFilename="VM-network-MACs.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotVMnetworkMACs);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotVMnetworkMACs(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('VM-network-MACs.csv file is missing from upload.');
+ return;
+ }
+ csvVMnetworkMACs = jsonObj;
+ csvVMnetworkMACs = _.reject(csvVMnetworkMACs, 'field2', 'VM-network-MACs');
+ csvVMnetworkMACs = _.reject(csvVMnetworkMACs, 'field2', 'List the MACs assigned to each VM-network');
+ csvVMnetworkMACs = _.reject(csvVMnetworkMACs, 'field2', 'vm-type');
+ csvVMnetworkMACs = _.reject(csvVMnetworkMACs, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvVMnetworkMACs);
+ puts("\n");
+ doTagValues();
+}
+
+// READ WORKSHEET: TAG-VALUES
+
+function doTagValues() {
+ puts("Reading Tag-values worksheet");
+ var csvFilename="Tag-values.csv";
+ var newFileName = helpers.getFileName(req, csvFilename);
+ if ( newFileName != null ) {
+ helpers.readCsv(indir, newFileName, gotTagValues);
+ }
+ else {
+ callback(csvFilename + ' file is missing from upload.');
+ }
+}
+
+function gotTagValues(err, jsonObj) {
+ if (err) {
+ puts("\nError!");
+ putd(err);
+ callback('Tag-values.csv file is missing from upload.');
+ return;
+ }
+ csvTagValues = jsonObj;
+ csvTagValues = _.reject(csvTagValues, 'field2', 'Tag-values');
+ csvTagValues = _.reject(csvTagValues, 'field2', 'Extra data to be passed into the HEAT template for this VNF');
+ csvTagValues = _.reject(csvTagValues, 'field2', 'vnf-parameter-name');
+ csvTagValues = _.reject(csvTagValues, 'field2', 'vnf-parameter-value');
+ csvTagValues = _.reject(csvTagValues, 'field2', '');
+ puts("\nRead this: ");
+ putd(csvTagValues);
+ puts("\n");
+ doneReadingFiles();
+}
+
+
+
+
+function doneReadingFiles() {
+ puts("\n");
+ puts("DONE READING FILES!");
+ puts("\n");
+ processJson();
+}
+
+
+// PROCESS THE CSV FILES INTO OBJECTS TO BE ASSEMBLED INTO FINAL OUTPUT
+function processJson() {
+ processGeneral();
+ processAvailZones();
+ processNetworks();
+ processVMnetworks();
+ processVMnetips();
+ processVMnetmacs();
+ processVMs();
+ processTagValues();
+ assembleJson();
+}
+
+// ASSEMBLE AND OUTPUT RESULTS
+
+function assembleJson() {
+ puts("\n");
+ puts("Using raw JSON and assembling final ouptut JSON.");
+ puts("\n");
+
+ vnfTopoID = { "service-type": "SDN-MOBILITY",
+ "vnf-name": rawJson['vf-module-name'],
+ "vnf-type": rawJson['vf-module-model-name'],
+ "generic-vnf-name": rawJson['generic-vnf-name'],
+ "generic-vnf-type": rawJson['generic-vnf-type'] };
+
+ vnfZones = rawJson['availability-zones'];
+
+ vnfNetworks = rawJson['networks'];
+
+ vnfVMs = rawJson['vms'];
+
+ vnfParams = rawJson['tag-values'];
+
+ vnfAssignments = { "availability-zones": vnfZones,
+ "vnf-networks": vnfNetworks,
+ "vnf-vms": vnfVMs};
+
+ vnfTopo = { "vnf-topology-identifier": vnfTopoID,
+ "vnf-assignments": vnfAssignments,
+ "vnf-parameters": vnfParams };
+
+ vnfInput = {'vnf-topology-information': vnfTopo};
+
+ finalJson = {"input": vnfInput};
+
+ outputJson();
+}
+
+function outputJson() {
+ puts("\n");
+ puts("\n");
+ puts(JSON.stringify(finalJson,null,2));
+ puts("\n");
+ puts("\n");
+ var unixTime, fullpath_filename, filename;
+ unixTime = moment().unix();
+ if (platform=='portal') {
+ fullpath_filename = process.cwd() + "/uploads/" + unixTime + ".vnf_worksheet.json";
+ filename = unixTime + ".vnf_worksheet.json.";
+ } else {
+ fullpath_filename = "./output.json."+unixTime;
+ filename = "output.json." + unixTime;
+ }
+ helpers.writeOutput(req, fullpath_filename, JSON.stringify(finalJson,null,2), callback);
+ callback(null, finalJson, filename);
+}
+
+
+// Gather functions that actually process data after it is all read
+
+function processGeneral() {
+
+ preloadVersion = getParam(csvGeneral, 'field2', 'preload-version', 'field3');
+ rawJson['preload-version'] = preloadVersion;
+ puts("Preload version: " + preloadVersion);
+
+ if ( (preloadVersion!='1607') && (preloadVersion!='1610') ) {
+ puts("\nError - incorrect version of preload worksheet.");
+ callback('Error - incorrect version of preload worksheet.');
+ }
+
+ rawJson['vf-module-name'] = getParam(csvGeneral, 'field2', 'vf-module-name', 'field3');
+ // rawJson['vf-module-type'] = getParam(csvGeneral, 'field2', 'vf-module-type', 'field3');
+ try {
+ rawJson['vf-module-model-name'] = getParam(csvGeneral, 'field2', 'vf-module-model-name', 'field3');
+ } catch (e) {
+ puts("\n\n");
+ puts("ERROR ERROR ERROR ERROR ERROR\n");
+ puts("Failed to find data field 'vf-module-model-name'. Maybe this preload worksheet is older?")
+ puts("If on the 'general' tab there is a field called 'vf-module-type' please rename it to 'vf-module-model-name'");
+ puts("\n\n");
+ process.exit();
+ }
+ rawJson['generic-vnf-name'] = getParam(csvGeneral, 'field2', 'vnf-name', 'field3');
+ rawJson['generic-vnf-type'] = getParam(csvGeneral, 'field2', 'vnf-type', 'field3');
+ rawJson['request-id'] = uuid.v1();
+ rawJson['source'] = "ADMINPORTAL";
+ rawJson['request-action'] = "PreloadVNFRequest";
+ rawJson['svc-request-id'] = uuid.v1();
+ rawJson['svc-action'] = "reserve";
+ puts('rawJson:');
+ putd(rawJson);
+ puts("\n");
+}
+
+function processAvailZones() {
+ var newZones = _.map(csvZones, function(x) { return {'availability-zone': x['field2']}; } );
+ rawJson['availability-zones'] = newZones;
+ puts("Availability zones read:");
+ putd(rawJson['availability-zones']);
+ puts("\n");
+}
+
+function processNetworks() {
+ var newNetworks = [];
+ csvNetworks.forEach( function(network) {
+ var netJson = {};
+ netJson["network-role"] = network.field2;
+ netJson["network-name"] = network.field3;
+ netJson["network-id"] = network.field4;
+ netJson["contrail-network-fqdn"] = network.field5;
+ netJson["subnet-name"] = network.field6;
+ netJson["subnet-id"] = network.field7;
+ netJson["ipv6-subnet-name"] = network.field8;
+ netJson["ipv6-subnet-id"] = network.field9;
+ newNetworks.push(netJson);
+ }
+ );
+ puts("networks:");
+ putd(newNetworks);
+ rawJson["networks"] = newNetworks;
+}
+
+function processVMs() {
+ var newVMs = [];
+ csvVMs.forEach( function(vm) {
+ var vmJson = {};
+ vmJson["vm-type"] = vm.field2;
+ vmJson["vm-name"] = vm.field3;
+ newVMs.push(vmJson);
+ }
+ );
+
+ puts("VMs:");
+ putd(newVMs);
+
+ // OK, now for each type, get count and then build vm-names array of the names
+ var vnfvms=[]
+ vmTypes = _.uniq(_.pluck(newVMs,'vm-type'));
+ vmTypes.forEach( function(vmType) {
+ puts(vmType);
+ var vmJson={};
+ var vmThisType;
+ var vmCount;
+ var vmNames=[];
+ var tmpNames;
+ vmThisType=_.select(newVMs, 'vm-type', vmType);
+ vmCount=vmThisType.length;
+ vmJson["vm-type"] = vmType;
+ vmJson["vm-count"] = vmCount;
+ tmpNames = _.pluck(vmThisType,'vm-name');
+ vmJson["vm-names"] = _.map(tmpNames, function(nam) { return {"vm-name": nam}; } );
+ netroles = _.select( rawJson["vm-networks"], "vm-type", vmType );
+ newnetroles=[]
+ netroles.forEach( function(netrole) {
+ tmpNetDetails = {};
+ tmpNetDetails["network-role"] = netrole["network-role"];
+ tmpNetDetails["use-dhcp"] = netrole["use-dhcp"];
+
+ var tmpipsThisVmType=[];
+ tmpipsThisVmType = _.select( rawJson["vm-net-ips"], "vm-type", vmType);
+ var tmpips=[];
+ tmpips = _.select( tmpipsThisVmType, "network-role", netrole["network-role"]);
+ tmpipsJson = _.map(tmpips, function(ip) { return {"ip-address": ip["ip-address"]} } );
+ tmpipsJson = _.reject(tmpipsJson, function(o) { return (o["ip-address"]==undefined); } );
+ tmpNetDetails["network-ips"] = tmpipsJson;
+
+ var tmpipsv6ThisVmType=[];
+ tmpipsv6ThisVmType = _.select( rawJson["vm-net-ips"], "vm-type", vmType);
+ var tmpipsv6=[];
+ tmpipsv6 = _.select( tmpipsv6ThisVmType, "network-role", netrole["network-role"]);
+ tmpipsv6Json = _.map(tmpipsv6, function(ip) { return {"ip-address-ipv6": ip["ipv6-address"]} } );
+ tmpipsv6Json = _.reject(tmpipsv6Json, function(o) { return (o["ip-address-ipv6"]==undefined); } );
+ tmpNetDetails["network-ips-v6"] = tmpipsv6Json;
+
+ var tmpirpThisVmType=[];
+ tmpirpThisVmType = _.select( rawJson["vm-net-ips"], "vm-type", vmType);
+ var tmpirp=[];
+ tmpirp = _.select( tmpirpThisVmType, "network-role", netrole["network-role"]);
+ tmpirpJson = _.map(tmpirp, function(irp) { return {"interface-route-prefix-cidr": irp["interface-route-prefix"]} } );
+ tmpirpJson = _.reject(tmpirpJson, function(o) { return (o["interface-route-prefix-cidr"]==undefined); } );
+ tmpNetDetails["interface-route-prefixes"] = tmpirpJson;
+
+ var tmpmacsThisVmType=[];
+ tmpmacsThisVmType = _.select( rawJson["vm-net-macs"], "vm-type", vmType);
+ var tmpmacs=[];
+ tmpmacs = _.select( tmpmacsThisVmType, "network-role", netrole["network-role"]);
+ tmpmacsJson = _.map(tmpmacs, function(mac) { return {"mac-address": mac["mac-address"]} } );
+ tmpNetDetails["network-macs"] = tmpmacsJson;
+
+ var fip='';
+ fip = netrole["floating-ip"];
+ fip = _.trim(fip);
+ if (fip != '') {
+ tmpNetDetails["floating-ip"] = netrole["floating-ip"];
+ }
+
+ var fipv6='';
+ fipv6 = netrole["floating-ip-v6"];
+ fipv6 = _.trim(fipv6);
+ if (fipv6 != '') {
+ tmpNetDetails["floating-ip-v6"] = netrole["floating-ip-v6"];
+ }
+
+ newnetroles.push(tmpNetDetails);
+ }
+ );
+ vmJson["vm-networks"] = newnetroles;
+ putd(vmJson);
+ vnfvms.push(vmJson);
+ }
+ );
+ rawJson["vms"] = vnfvms;
+}
+
+function processVMnetworks() {
+ // For each VM type, for each Network role, get details like use-dhcp
+ var newVMnetworks = [];
+ csvVMnetworks.forEach( function(vm) {
+ var newvmJson = {};
+ newvmJson["vm-type"] = vm.field2;
+ newvmJson["network-role"] = vm.field3;
+ newvmJson["use-dhcp"] = vm.field4;
+ newvmJson["floating-ip"] = vm.field5;
+ newvmJson["floating-ip-v6"] = vm.field6;
+ newVMnetworks.push(newvmJson);
+ }
+ );
+ rawJson["vm-networks"] = newVMnetworks;
+ puts("rawJson for vm-networks...");
+ putd( rawJson["vm-networks"] );
+}
+
+
+function processVMnetips() {
+ // For each VM type, for each network role, get the set of network IPs
+ puts("Processing VM-net-ips");
+ var newVMnetips = [];
+ csvVMnetworkIPs.forEach( function(vm) {
+ var newvmnetipsJson = {};
+ newvmnetipsJson["vm-type"] = vm.field2;
+ newvmnetipsJson["network-role"] = vm.field3;
+ if (_.trim(vm.field4)!="") {
+ newvmnetipsJson["ip-address"] = vm.field4;
+ }
+ if (_.trim(vm.field5)!="") {
+ newvmnetipsJson["ipv6-address"] = vm.field5;
+ }
+ if (_.trim(vm.field6)!="") {
+ newvmnetipsJson["interface-route-prefix"] = vm.field6;
+ }
+ newVMnetips.push(newvmnetipsJson);
+ }
+ );
+ rawJson["vm-net-ips"] = newVMnetips;
+ puts("rawJson for vm-net-ips");
+ putd(rawJson["vm-net-ips"]);
+}
+
+function processVMnetmacs() {
+ // For each VM type, for each network role, get the set of MACs
+ puts("Processing VM-net-macs");
+ var newVMnetmacs = [];
+ csvVMnetworkMACs.forEach( function(vm) {
+ var newvmnetmacsJson = {};
+ newvmnetmacsJson["vm-type"] = vm.field2;
+ newvmnetmacsJson["network-role"] = vm.field3;
+ newvmnetmacsJson["mac-address"] = vm.field4;
+ newVMnetmacs.push(newvmnetmacsJson);
+ }
+ );
+ rawJson["vm-net-macs"] = newVMnetmacs;
+ puts("rawJson for vm-net-macs");
+ putd(rawJson["vm-net-macs"]);
+}
+
+function processTagValues() {
+ var newTagValues = _.map(csvTagValues, function(x) { return {'vnf-parameter-name': x['field2'],
+ 'vnf-parameter-value': x['field3']}; } );
+ rawJson['tag-values'] = newTagValues;
+ puts("Tag-values read:");
+ putd(rawJson['tag-values']);
+ puts("\n");
+}
+
+