From 5cabe36fe85a780a9fb808343d6341f15da13524 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Mon, 12 Apr 2021 08:17:37 -0400 Subject: Fix ccsdk version and remove admportal Fix ccsdk versions and remove admportal, which is no longer supported Change-Id: Iaee9bd2b7d5d7345f889357684df18d53db466a1 Issue-ID: SDNC-1507 Signed-off-by: Dan Timoney Former-commit-id: a1d57d8f5131414429f9ef2d8b0468004d253d0a --- admportal/server/router/routes/OdlInterface.js | 594 ---------- admportal/server/router/routes/admin.js | 89 -- admportal/server/router/routes/csp.js | 103 -- admportal/server/router/routes/dbRoutes.js | 1407 ------------------------ admportal/server/router/routes/gamma.js | 1360 ----------------------- admportal/server/router/routes/helpers.js | 66 -- admportal/server/router/routes/mobility.js | 763 ------------- admportal/server/router/routes/network.js | 438 -------- admportal/server/router/routes/odl.js | 258 ----- admportal/server/router/routes/preload.js | 138 --- admportal/server/router/routes/root.js | 122 -- admportal/server/router/routes/sla.js | 262 ----- admportal/server/router/routes/user.js | 172 --- admportal/server/router/routes/vnf.js | 644 ----------- 14 files changed, 6416 deletions(-) delete mode 100755 admportal/server/router/routes/OdlInterface.js delete mode 100755 admportal/server/router/routes/admin.js delete mode 100644 admportal/server/router/routes/csp.js delete mode 100644 admportal/server/router/routes/dbRoutes.js delete mode 100644 admportal/server/router/routes/gamma.js delete mode 100644 admportal/server/router/routes/helpers.js delete mode 100644 admportal/server/router/routes/mobility.js delete mode 100644 admportal/server/router/routes/network.js delete mode 100644 admportal/server/router/routes/odl.js delete mode 100644 admportal/server/router/routes/preload.js delete mode 100644 admportal/server/router/routes/root.js delete mode 100644 admportal/server/router/routes/sla.js delete mode 100644 admportal/server/router/routes/user.js delete mode 100644 admportal/server/router/routes/vnf.js (limited to 'admportal/server/router/routes') diff --git a/admportal/server/router/routes/OdlInterface.js b/admportal/server/router/routes/OdlInterface.js deleted file mode 100755 index 1fc615c4..00000000 --- a/admportal/server/router/routes/OdlInterface.js +++ /dev/null @@ -1,594 +0,0 @@ -// OdlInterface.js -var https = require('https'); -var http = require('http'); -var properties = require(process.env.SDNC_CONFIG_DIR + '/admportal.json'); - - -var OdlInterface = 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 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 = OdlInterface; - diff --git a/admportal/server/router/routes/admin.js b/admportal/server/router/routes/admin.js deleted file mode 100755 index 9a33dc81..00000000 --- a/admportal/server/router/routes/admin.js +++ /dev/null @@ -1,89 +0,0 @@ -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 cookieParser = require('cookie-parser'); -var bodyParser = require('body-parser'); -var sax = require('sax'),strict=true,parser = sax.parser(strict); -var async = require('async'); -var csrf = require('csurf'); - -var csrfProtection = csrf({cookie: true}); -router.use(cookieParser()); - - -// 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, csrfProtection, 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, csrfProtection, 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, csrfProtection, 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 deleted file mode 100644 index f82edd89..00000000 --- a/admportal/server/router/routes/csp.js +++ /dev/null @@ -1,103 +0,0 @@ -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 tkn = req.sanitize(req.body._csrf); - - var loggedInAdmin={}; - var email = req.sanitize(req.body.email); - var pswd = req.sanitize(req.body.password); - dbRoutes.findAdminUser(email,res,function(adminUser) - { - // make sure correct password is provided - if (pswd != adminUser.password) { - res.render("pages/err", { result: { code:'error', msg:'Invalid password entered.' }, header:process.env.MAIN_MENU }); - return; - } - var loggedInAdmin = { - email:adminUser.email, - csrfToken: tkn, - password:adminUser.password, - privilege:adminUser.privilege - } - req.session.loggedInAdmin = loggedInAdmin; - - console.log("Login Success"+JSON.stringify(loggedInAdmin)); - res.redirect('sla/listSLA'); - return; - }); -} - -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); - if(req.session == null || req.session == undefined - || req.session.loggedInAdmin == null || req.session.loggedInAdmin == undefined) - { - console.log("loggedInAdmin not found.session timed out."); - res.redirect('/login'); - //res.render('pages/login'); - return; - } - console.log("cookie is: " + JSON.stringify(req.session.loggedInAdmin)); - next(); - return; -} - -function checkPriv(req,res,next) -{ - var priv = req.session.loggedInAdmin; - if(req.session == null || req.session == undefined - || req.session.loggedInAdmin == null || req.session.loggedInAdmin == undefined) - { - res.render("pages/err", - { - result: {code:'error', msg:'Unexpected null session.'}, - header: process.env.MAIN_MENU - }); - return; - } - else - { - if (priv.privilege == 'A') - { - next(); - return; - } - else - { - res.render("pages/err", - { - result: { code:'error', msg:'User does not have permission to run operation.'}, - header: process.env.MAIN_MENU - }); - return; - } - } -} - - -exports.login = login; -exports.logout = logout; -exports.checkAuth = checkAuth; -exports.checkPriv = checkPriv; diff --git a/admportal/server/router/routes/dbRoutes.js b/admportal/server/router/routes/dbRoutes.js deleted file mode 100644 index af3859b5..00000000 --- a/admportal/server/router/routes/dbRoutes.js +++ /dev/null @@ -1,1407 +0,0 @@ -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 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 1) - { - connection.release(); - res.render("pages/signup", {csrfToken:tkn, result:{code:'error', msg:'User Information already exists.'},header:process.env.MAIN_MENU}); - return; - } - sql = "INSERT INTO PORTAL_USERS (email,password,privilege) VALUES (" - + connection.escape(email) + "," - + "AES_ENCRYPT(" + connection.escape(pswd) + ",'" + enckey + "'),'A')"; - - connection.query(sql, function(err,result) - { - connection.release(); - - if(err){ - res.render("pages/signup", {csrfToken:tkn, result:{ code:'error', msg:String(err) },header:process.env.MAIN_MENU});; - return; - } - res.render('pages/signup', {csrfToken:tkn, 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=" + connection.escape(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; - var privilege = req.sanitize(req.body.nf_privilege); - var email = req.sanitize(req.body.nf_email); - var pswd = req.sanitize(req.body.nf_password); - - - 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( privilege == "admin" ){ - var char_priv = 'A'; - }else if(privilege == 'readonly'){ - var char_priv = 'R'; - }else{ - var char_priv = 'R'; - } - - //connection.query(sqlRequest, function(err,result) - var sqlUpdate = "INSERT INTO PORTAL_USERS (email, password, privilege) VALUES (" - + connection.escape(email) + "," - + "AES_ENCRYPT(" + connection.escape(pswd) + ",'" + enckey + "')," - + "'" + char_priv + "')"; - - - 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; - var email = req.sanitize(req.body.uf_email); - var key_email = req.sanitize(req.body.uf_key_email) - var pswd = req.sanitize(req.body.uf_password); - var privilege = req.sanitize(req.body.uf_privilege); - - 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( privilege == "admin" ){ - var char_priv = 'A'; - }else if(privilege == 'readonly'){ - var char_priv = 'R'; - }else{ - var char_priv = 'R'; - } - - var sqlUpdate = "UPDATE PORTAL_USERS SET " - + "email = " + connection.escape(email) + "," - + "password = " + "AES_ENCRYPT(" + connection.escape(pswd) + ",'" + enckey + "'), " - + "privilege = '" + char_priv + "'" - + " WHERE email = " + connection.escape(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"; - - 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 ); - return; - } - else - { - console.log('affectedRows='+result.affectedRows); - callback(null, result.affectedRows); - return; - } - }); //end query - }); // end getConnection -} - - -// gamma - deleteParameter -exports.deleteParameter = function(req,res,callback){ - - pool.getConnection(function(err,connection) { - - if(err){ - console.log( String(err) ); // ALARM - callback(err, 'Unable to get database connection.' + err); - return; - } - var sql = "DELETE FROM PARAMETERS WHERE name=" + connection.escape(req.query.name); - - console.log(sql); - connection.query(sql, function(err,result){ - connection.release(); - if(err){ - callback(err,'Update failed. ' + err ); - return; - } - else - { - callback(null,''); - return; - } - }); //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; - } - var sql = "SELECT vnf_type,availability_zone_count,equipment_role FROM VNF_PROFILE ORDER BY VNF_TYPE"; - console.log(sql); - connection.query(sql, 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 { - console.log('render vnfProfile'); - res.render('mobility/vnfProfile', { rows: rows, result:resultObj, privilege:privilegeObj,header:process.env.MAIN_MENU } ); - return; - } - }); //end 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 - var sql = "SELECT id,svc_request_id,svc_action,status,filename,ts,preload_data FROM PRE_LOAD_VNF_NETWORK_DATA ORDER BY id"; - console.log(sql); - connection.query(sql, 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}, - privilege:privilegeObj, - preloadImportDirectory: properties.preloadImportDirectory, - header:process.env.MAIN_MENU - }); - return; - } - else { - var retData = []; - for( r=0; r 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); - }//endloop - 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 - var sql = "SELECT id,svc_request_id,svc_action,status,filename,ts,preload_data FROM PRE_LOAD_VNF_DATA ORDER BY id"; - console.log(sql); - connection.query(sql,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}, - privilege:privilegeObj, - preloadImportDirectory: properties.preloadImportDirectory, - header:process.env.MAIN_MENU - }); - return; - } - else { - var retData = []; - for( r=0; r 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); - }//endloop - 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) - { - res.render("pages/err", {result:{code:'error', msg: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=" + connection.escape(email), function(err, rows) { - - connection.release(); - if(err) - { - res.render("pages/err", {result:{code:'error', msg:err},header:process.env.MAIN_MENU}); - return; - } - if ( rows.length > 0 ) - { - rows.forEach(function(row){ - adminUser = { - "email" : row.email, - "password" : row.password, - "privilege" : row.privilege }; - }); - callback(adminUser); - return; - } - else{ - res.render("pages/err", {result:{code:'error', msg:'User is not in database.'},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 -} - -exports.deleteVnfProfile = function(req,res,callback){ - - var privilegeObj = req.session.loggedInAdmin; - var rows={}; - - pool.getConnection(function(err,connection) { - - var sql = 'DELETE FROM VNF_PROFILE WHERE vnf_type = ' + connection.escape(req.sanitize(req.query.vnf_type)); - console.log(sql); - 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 vt = req.sanitize(req.query.vnf_type); - //var vnf_type = { vnf_type: vt }; - //var vnf_type = connection.escape(vt); - //console.log('type='+vnf_type); - //connection.query('DELETE FROM VNF_PROFILE WHERE vnf_type = ?', vnf_type, function(err,result) - connection.query(sql, function(err,result) - { - connection.release(); - if (err) { - callback(err,'Database operation failed. ' + err ); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('No rows deleted.'); - return; - } - console.log('rows deleted: ' + result.affectedRows); - callback(null, result.affectedRows); - return; - } - }); - }); // end of getConnection -}; - -exports.deleteVnfData = function(req,res,callback){ - - var privilegeObj = req.session.loggedInAdmin; - var rows={}; - - pool.getConnection(function(err,connection) { - - var sql = 'DELETE FROM PRE_LOAD_VNF_DATA WHERE id =' + connection.escape(req.sanitize(req.query.id)); - console.log(sql); - 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,result) - { - connection.release(); - if (err) { - callback(err,'Database operation failed. ' + err ); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('No rows deleted.'); - return; - } - console.log('rows deleted: ' + result.affectedRows); - callback(null, result.affectedRows); - return; - } - }); - }); // end of getConnection -}; - -exports.deleteVnfNetworkData = function(req,res,callback){ - - var privilegeObj = req.session.loggedInAdmin; - var rows={}; - - pool.getConnection(function(err,connection) { - - var sql = 'DELETE FROM PRE_LOAD_VNF_NETWORK_DATA WHERE id =' + connection.escape(req.sanitize(req.query.id)); - console.log(sql); - 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,result) - { - connection.release(); - if (err) { - callback(err,'Database operation failed. ' + err ); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('No rows deleted.'); - return; - } - console.log('rows deleted: ' + result.affectedRows); - callback(null, result.affectedRows); - return; - } - }); - }); // end of 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.updatePreloadStatus = function(sql,req,res,_module,rpc,version,mode,callback){ - - pool.getConnection(function(err,connection) { - - if(err){ - console.error( String(err) ); // ALARM - callback(err, 'Unable to get database connection.' + err); - return; - } - - var sql = _sql + " WHERE id = " + connection.escape(req.query.id); - - console.log(sql); - connection.query(sql, function(err,result){ - - connection.release(); - if(err){ - callback(err, 'Unable to get database connection.' + err); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('Unable to update preload status.'); - return; - } - callback(null, result.affectedRows); - return; - } - }); //end query - }); // end getConnection -} - -exports.activate = function(req,res,_module,rpc,version,mode,callback){ - - pool.getConnection(function(err,connection) { - - if(err){ - console.error( String(err) ); // ALARM - callback(err, 'Unable to get database connection.' + err); - return; - } - - var sql = "UPDATE SVC_LOGIC SET active=\'Y\' WHERE " - + "module = " + connection.escape(_module) + " AND " - + "rpc = " + connection.escape(rpc) + " AND " - + "version = " + connection.escape(version) + " AND " - + "mode = " + connection.escape(mode); - - console.log('SQL='+sql); - connection.query(sql, function(err,result){ - - connection.release(); - if(err){ - callback(err, 'Unable to get database connection.' + err); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('Unable to activate directed graph.'); - return; - } - console.log('rows deleted: ' + result.affectedRows); - callback(null, result.affectedRows); - return; - } - }); //end query - }); // end getConnection -} - - -exports.deactivate = function(req,res,_module,rpc,version,mode,callback){ - - pool.getConnection(function(err,connection) { - - if(err){ - console.error( String(err) ); // ALARM - callback(err, 'Unable to get database connection.' + err); - return; - } - - var sql = "UPDATE SVC_LOGIC SET active=\'N\' WHERE " - + "module = " + connection.escape(_module) + " AND " - + "rpc = " + connection.escape(rpc) + " AND " - + "version = " + connection.escape(version) + " AND " - + "mode = " + connection.escape(mode); - - console.log('SQL='+sql); - connection.query(sql, function(err,result){ - - connection.release(); - if(err){ - callback(err, 'Unable to get database connection.' + err); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('Unable to deactivate directed graph.'); - return; - } - console.log('rows deleted: ' + result.affectedRows); - callback(null, result.affectedRows); - return; - } - }); //end query - }); // end getConnection -} - -exports.global_deactivate = function(req,res,_module,rpc,mode,callback){ - - pool.getConnection(function(err,connection) { - - if(err){ - callback(err, 'Unable to get database connection.' + err); - return; - } - - // deactivate all versions - var sql = "UPDATE SVC_LOGIC SET active=\'N\' WHERE " - + "module = " + connection.escape(_module) + " AND " - + "rpc = " + connection.escape(rpc) + " AND " - + "mode = " + connection.escape(mode); - - console.log(sql); - connection.query(sql, function(err,result){ - - connection.release(); - if(err){ - callback(err, err); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('Unable to set all versions to deactivate.'); - return; - } - callback(null,result.affectedRows); - return; - } - }); //end query - }); // end getConnection -} - - -exports.deleteDG = function(req,res,_module,rpc,version,mode,callback){ - - pool.getConnection(function(err,connection) { - - if(err){ - console.error( String(err) ); // ALARM - callback(err, 'Unable to get database connection.' + err); - return; - } - - var sql = "DELETE FROM SVC_LOGIC WHERE " - + "module = " + connection.escape(_module) + " AND " - + "rpc = " + connection.escape(rpc) + " AND " - + "version = " + connection.escape(version) + " AND " - + "mode = " + connection.escape(mode); - - console.log(sql); - connection.query(sql, function(err,result){ - - connection.release(); - if(err){ - callback(err, 'Unable to get database connection.' + err); - return; - } - else - { - if (result.affectedRows == 0) - { - callback('No rows deleted.'); - return; - } - callback(null,result.affectedRows); - return; - } - }); //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 deleted file mode 100644 index 5b8c7649..00000000 --- a/admportal/server/router/routes/gamma.js +++ /dev/null @@ -1,1360 +0,0 @@ -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); -}); - -// GET -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 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 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 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 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 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 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 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 deleted file mode 100644 index 6ac8215f..00000000 --- a/admportal/server/router/routes/helpers.js +++ /dev/null @@ -1,66 +0,0 @@ - -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 deleted file mode 100644 index 8b5adabd..00000000 --- a/admportal/server/router/routes/mobility.js +++ /dev/null @@ -1,763 +0,0 @@ -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 cookieParser = require('cookie-parser'); -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 crypto = require('crypto'); -var csrf = require('csurf'); - -var csrfProtection = csrf({cookie: true}); -router.use(cookieParser()) - -// 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 -OdlInterface = require('./OdlInterface'); - -// 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, csrfProtection, function(req,res) { - dbRoutes.getVnfData(req,res, {code:'', msg:''}, req.session.loggedInAdmin); -}); -router.get('/getVnfNetworkData', csp.checkAuth, csrfProtection, function(req,res) { - dbRoutes.getVnfNetworkData(req,res, {code:'', msg:''}, req.session.loggedInAdmin); -}); -router.get('/getVnfProfile', csp.checkAuth, csrfProtection, function(req,res) { - dbRoutes.getVnfProfile(req,res, {code:'', msg:''}, req.session.loggedInAdmin); -}); -//router.get('/getVmNetworks', csp.checkAuth, function(req,res) { -// dbRoutes.getVmNetworks(req,res, {code:'', msg:''}, req.session.loggedInAdmin); -//}); -//router.get('/getVnfNetworks', csp.checkAuth, function(req,res) { -// dbRoutes.getVnfNetworks(req,res, {code:'', msg:''}, req.session.loggedInAdmin); -//}); -//router.get('/getVmProfile', csp.checkAuth, function(req,res) { -// dbRoutes.getVmProfile(req,res, {code:'', msg:''}, req.session.loggedInAdmin); -//}); -//////// - -router.get('/viewVnfNetworkData', csp.checkAuth, csrfProtection, 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){ - OdlInterface.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, csrfProtection, 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){ - OdlInterface.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, csp.checkPriv, 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"); - const rnum = crypto.randomBytes(4); - var svc_req_id = req.query.id + "-" + df + "-" + rnum.toString('hex');; - 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('}}'); - - OdlInterface.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.updatePreloadStatus("UPDATE PRE_LOAD_VNF_NETWORK_DATA SET status='uploaded',svc_request_id='" + svc_req_id + "',svc_action='reserve'",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, csp.checkPriv, function(req,res) -{ - var privilegeObj = req.session.loggedInAdmin; - var full_path_file_name = process.cwd() + "/uploads/" + req.sanitize(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"); - const rnum = crypto.randomBytes(4); - var svc_req_id = req.sanitize(req.query.id) + "-" + df + "-" + rnum.toString('hex'); - 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('}}'); - - OdlInterface.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'",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, csp.checkPriv, csrfProtection, function(req,res) { - - var privilegeObj = req.session.loggedInAdmin; - var tasks = []; - - // 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.deleteVnfNetworkData(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) { - OdlInterface.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, csp.checkPriv, csrfProtection, function(req,res) { - - var privilegeObj = req.session.loggedInAdmin; - var tasks = []; - - // 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.deleteVnfData(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) { - OdlInterface.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('/deleteVnfNetwork', csp.checkAuth, csp.checkPriv, csrfProtection, 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, csp.checkPriv, csrfProtection, function(req,res) { - - var privilegeObj = req.session.loggedInAdmin; - var tasks = []; - var sql = ''; - - - tasks.push(function(callback) { - dbRoutes.deleteVnfProfile(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; - } - }); -}); - -// POST -router.post('/addVnfProfile', csp.checkAuth, csp.checkPriv, csrfProtection, function(req,res){ - - var privilegeObj = req.session.loggedInAdmin; - var vnf_type = req.sanitize(req.body.nf_vnf_type); - var availability_zone_count = req.sanitize(req.body.nf_availability_zone_count); - var equipment_role = req.sanitize(req.body.nf_equipment_role); - var tasks = []; - var sql; - - sql = "INSERT INTO VNF_PROFILE (vnf_type,availability_zone_count,equipment_role) VALUES (" - + "'" + vnf_type + "'," + availability_zone_count + ",'" + 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; - } - }); -}); - -// POST -router.post('/uploadVnfData', csp.checkAuth, csp.checkPriv, 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, csp.checkPriv, 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('/uploadVnfProfile', csp.checkAuth, csp.checkPriv, 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 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; - } -} ); - -module.exports = router; diff --git a/admportal/server/router/routes/network.js b/admportal/server/router/routes/network.js deleted file mode 100644 index 30aa66b2..00000000 --- a/admportal/server/router/routes/network.js +++ /dev/null @@ -1,438 +0,0 @@ - -// 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... -var proc_error = false; -var filename; - -puts = helpers.puts; -putd = helpers.putd; - -network.go = function(lreq,lres,cb,dir) { - puts("Processing NETWORK workbook"); - proc_error = false; - 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 { - puts('general file is missing from upload.'); - proc_error=true; - } -} - -function gotGeneral(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - puts('subnets file is missing from upload.'); - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - return; - } -} - -function gotSubnets(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - puts('vnp-bindings file is missing from upload.'); - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - return; - } -} - -function gotVpnBindings(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - puts('policies file is missing from upload.'); - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - return; - } -} - -function gotPolicies(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - puts('network-routes file is missing from upload.'); - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - return; - } -} - -function gotNetRoutes(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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(); - outputJson(); - - puts('proc_error='); - putd(proc_error); - if ( proc_error ){ - puts('callback with failure'); - callback('Error was encountered processing upload.'); - return; - } - else - { - puts('callback with success'); - callback(null, finalJson, filename); - return; - } -} - -// 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; - 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."); - proc_error=true; - //callback('Error - incorrect version of preload worksheet.'); - return; - } - - 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 deleted file mode 100644 index 3882afcc..00000000 --- a/admportal/server/router/routes/odl.js +++ /dev/null @@ -1,258 +0,0 @@ -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 -OdlInterface = require('./OdlInterface'); - -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 - OdlInterface.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){ - OdlInterface.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']+ '"' - +' } }'; - OdlInterface.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); - OdlInterface.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); - OdlInterface.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); - OdlInterface.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) { - OdlInterface.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); - OdlInterface.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 -1 ) - { - dbRoutes.listSLA(req,res,{code:'success', msg:'File sucessfully uploaded.'}); - } - else - { - dbRoutes.listSLA(req,res,{code:'failure', msg:_lstderr} ); - } - return; - }); - } catch(ex) { - console.log("error: " + ex); - dbRoutes.listSLA(req,res,{code:'failure',msg:ex} ); - return; - } - } - else { - dbRoutes.listSLA(req,res,{code:'danger', msg:'There was an error uploading the file, please try again.'}); - return; - } - }); - } - else { - dbRoutes.listSLA(req,res,{code:'danger', msg:'There was an error uploading the file, please try again.'}); - return; - } -}); - -router.get('/printAsXml', csp.checkAuth, csrfProtection, function(req,res){ - - try { - var _lstdout = ""; - var _lstderr = ""; - 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"; - console.log("commandToExec:" + commandToExec); - console.log("_mode: " + _module); - console.log("rpc: " + rpc); - console.log("version: " + version); - console.log("currentDB: " + process.env.SDNC_CONFIG_DIR + "/svclogic.properties." + currentDB); - - child = spawn(commandToExec, ['get-source', _module, rpc, mode, version, process.env.SDNC_CONFIG_DIR + "/svclogic.properties." + currentDB], {maxBuffer: 1024*5000}); - child.on('error', function(error){ - console.log("error: " + error); - dbRoutes.listSLA(req,res,{code:'failure',msg:error} ); - return; - }); - child.stderr.on('data', function(data){ - console.log('stderr: ' + data); - _lstderr = _lstderr.concat(data); - }); - child.stdout.on('data', function(data){ - console.log("OUTPUT:" + data); - _lstdout = _lstdout.concat(data); - }); - child.on('exit', function(code,signal){ - - console.log('code: ' + code); - console.log('close:stdout: ' + _lstdout); - console.log('close:stderr: ' + _lstderr); - - if ( code != 0 ){ - dbRoutes.listSLA(req,res,{code:'failure',msg:_lstderr} ); - } - else { - res.render('sla/printasxml', {result:{code:'success', - msg:'Module : ' + _module + '\n' + - 'RPC : ' + rpc + '\n' + - 'Mode : ' + mode + '\n' + - 'Version: ' + version + '\n\n' + _lstdout}, header:process.env.MAIN_MENU}); - } - return; - }); - } catch(ex) { - console.error("error:" + ex); - dbRoutes.listSLA(req,res,{code:'failure',msg:ex} ); - return; - } -}); - -module.exports = router; diff --git a/admportal/server/router/routes/user.js b/admportal/server/router/routes/user.js deleted file mode 100644 index df5f8607..00000000 --- a/admportal/server/router/routes/user.js +++ /dev/null @@ -1,172 +0,0 @@ -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 cookieParser = require('cookie-parser'); -var csrf = require('csurf'); -var bodyParser = require('body-parser'); -//var sax = require('sax'),strict=true,parser = sax.parser(strict); - -var csrfProtection = csrf({cookie: true}); -router.use(cookieParser()); - -// 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:''} ); -}); -// POST -router.post('/updateUser', csp.checkAuth, csrfProtection, function(req,res,next){ - dbRoutes.updateUser(req,res,{code:'',msg:''}); -}); -router.post('/addUser', csp.checkAuth, csrfProtection, function(req,res) { - dbRoutes.addUser(req,res, {code:'', msg:''} ); -}); -router.get('/deleteUser', csp.checkAuth, csrfProtection, function(req,res) { - dbRoutes.deleteUser(req,res, {code:'', msg:''} ); -}); - -//router.get('/activate', csp.checkAuth, 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, 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, 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:'); -}; -*/ - - - -//router.post('/upload', csp.checkAuth, 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 deleted file mode 100644 index 99bb3a7d..00000000 --- a/admportal/server/router/routes/vnf.js +++ /dev/null @@ -1,644 +0,0 @@ - -// 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... -var proc_error=false; -var filename; - -puts = helpers.puts; -putd = helpers.putd; - -vnf.go = function(lreq,lres,cb,dir){ - puts("Processing VNF workbook"); - proc_error=false; - 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 { - puts('General.csv file is missing from upload.'); - proc_error=true; - } -} - -function gotGeneral(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotAvailZones(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotNetworks(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotVMs(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotVMnetworks(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotVMnetworkIPs(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotVMnetworkMACs(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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 { - proc_error=true; - callback(csvFilename + ' file is missing from upload.'); - } - return; -} - -function gotTagValues(err, jsonObj) { - if (err) { - puts("\nError!"); - putd(err); - proc_error=true; - 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(); - outputJson(); - - puts('proc_error='); - putd(proc_error); - if ( proc_error ){ - puts('callback with failure'); - callback('Error was encountered processing upload.'); - return; - } - else - { - puts('callback with success'); - callback(null, finalJson, filename); - return; - } -} - -// 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; - 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"); -} - - -- cgit 1.2.3-korg