2 * Copyright 2013 IBM Corp.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 var express = require('express');
18 var util = require('util');
19 var multer = require('multer');
20 var when = require('when');
21 var exec = require('child_process').exec;
23 var createUI = require("./ui");
24 var redNodes = require("./nodes");
25 var comms = require("./comms");
26 var storage = require("./storage");
28 var path = require("path");
34 var flowShareUsers = require("../flowShareUsers");
36 //console.dir(flowShareUsers);
38 function createServer(_server,_settings) {
42 comms.init(_server,_settings);
47 if (settings.httpAdminRoot !== false) {
50 if (!settings.disableEditor) {
51 createUI(settings,app);
54 var slaActions = require("./sla");
56 app.get("/flows",function(req,res) {
57 res.json(redNodes.getFlows());
60 app.get("/loadJSFiles",function(req,res) {
61 var appDir = path.dirname(require.main.filename);
62 var generatedJSDir=appDir + "/generatedJS";
63 var glob = require("glob")
64 glob(generatedJSDir + "/**/*.js", null, function (er, files) {
65 // files is an array of filenames.
66 // If the `nonull` option is set, and nothing
67 // was found, then files is ["**/*.js"]
68 // er is an error object or null.
71 for(var i=0;files!= null && i<files.length;i++){
72 var f = files[i].replace( new RegExp(generatedJSDir + "/", "g" ), "" );
73 console.log("loading file " + f);
75 sliValuesObj.push(require(files[i]));
76 //console.dir(sliValuesObj);
78 console.log("Error:Could not load file " + files[i]);
81 res.json({"sliValuesObj" : sliValuesObj});
85 app.get("/loadSelectedModules",function(req,res) {
86 var appDir = path.dirname(require.main.filename);
87 var userDir = appDir + "/" + settings.userDir;
88 var generatedJSDir=appDir + "/generatedJS";
90 var selectedModulesStr = req.query.selectedModules;
91 var selectedModules = [];
92 if(selectedModulesStr != undefined && selectedModulesStr != null){
93 selectedModules = selectedModulesStr.split(",");
95 console.log(selectedModules);
96 var loaded_modules = {"selected_modules" :selectedModules};
97 var file = userDir + "/selected_modules";
98 var content = "module.exports=\n" + JSON.stringify(loaded_modules);
100 fs.writeFileSync(file, content, 'utf8');
102 console.log("could not write to file " + file);
104 var sliValuesObj =[];
105 for(var i=0;selectedModules!= null && i<selectedModules.length;i++){
106 var f = generatedJSDir + "/" + selectedModules[i] + "_inputs.js";
108 delete require.cache[require.resolve(f)]
111 console.log("error deleting loaded module " + f + " from cache");
113 //console.log("loading file " + f);
115 sliValuesObj.push(require(f));
117 console.log("Error:Could not load file " + f);
120 //console.dir(sliValuesObj);
121 res.json({"sliValuesObj" : sliValuesObj});
124 app.get("/initialLoadSelectedModules",function(req,res) {
125 var appDir = path.dirname(require.main.filename);
126 var userDir = appDir + "/" + settings.userDir;
127 var generatedJSDir=appDir + "/generatedJS";
128 var file = userDir + "/selected_modules";
129 var sliValuesObj =[];
130 var selected_modules = [];
133 selectedModules = require(file);
134 selected_modules=selectedModules["selected_modules"];
135 //console.log("selected_modules are ");
136 //console.dir(selected_modules);
138 console.log("Could not load the file " + file);
140 for(var i=0;selected_modules!= null && i<selected_modules.length;i++){
141 var f = generatedJSDir + "/" + selected_modules[i] + "_inputs.js";
142 console.log("loading file " + f);
144 sliValuesObj.push(require(f));
146 console.log("Error:Could not load file " + f);
149 res.json({"sliValuesObj" : sliValuesObj});
152 app.get("/listAvailableModules",function(req,res) {
153 var appDir = path.dirname(require.main.filename);
154 var userDir = appDir + "/" + settings.userDir;
155 var generatedJSDir=appDir + "/generatedJS";
156 var glob = require("glob")
157 var file = userDir + "/selected_modules";
158 var selected_modules = [];
161 delete require.cache[require.resolve(file)]
164 console.log("error deleting loaded module " + file + " from cache");
167 selectedModules = require(file);
168 selected_modules=selectedModules["selected_modules"];
169 console.log("selected_modules are ");
170 //console.dir(selected_modules);
172 console.log("Could not load the file " + file);
174 glob(generatedJSDir + "/**/*.js", null, function (er, files) {
176 for(var i=0;files!= null && i<files.length;i++){
177 var f = files[i].replace( new RegExp(generatedJSDir + "/", "g" ), "" );
178 f = f.replace("_inputs.js","");
179 if(selected_modules != undefined && selected_modules != null && selected_modules.indexOf(f) != -1){
180 filesList.push(f + ":checked");
182 filesList.push(f + ":unchecked");
185 res.json({"files" : filesList});
189 app.get("/listSLA",function(req,res) {
190 var appDir = path.dirname(require.main.filename);
191 var userDir = appDir + "/" + settings.userDir;
192 var settingsFile = userDir + "/customSettings.js";
193 var jsonObj = require(settingsFile);
194 slaActions.listSLA(jsonObj,req,res);
197 app.get("/listCurrentDGs",function(req,res) {
198 var appDir = path.dirname(require.main.filename);
199 var userDir = appDir + "/" + settings.userDir;
200 var settingsFile = userDir + "/customSettings.js";
201 var jsonObj = require(settingsFile);
202 slaActions.listCurrentDGs(jsonObj,req,res);
205 app.get("/activateDG",function(req,res) {
206 var appDir = path.dirname(require.main.filename);
207 var userDir = appDir + "/" + settings.userDir;
208 var settingsFile = userDir + "/customSettings.js";
209 var jsonObj = require(settingsFile);
210 slaActions.activateDG(jsonObj,req,res);
213 app.get("/deActivateDG",function(req,res) {
214 var appDir = path.dirname(require.main.filename);
215 var userDir = appDir + "/" + settings.userDir;
216 var settingsFile = userDir + "/customSettings.js";
217 var jsonObj = require(settingsFile);
218 slaActions.deActivateDG(jsonObj,req,res);
221 app.get("/deleteDG",function(req,res) {
222 var appDir = path.dirname(require.main.filename);
223 var userDir = appDir + "/" + settings.userDir;
224 var settingsFile = userDir + "/customSettings.js";
225 var jsonObj = require(settingsFile);
226 slaActions.deleteDG(jsonObj,req,res);
229 app.get("/getCurrentSettings",function(req,res) {
230 var appDir = path.dirname(require.main.filename);
231 var userDir = appDir + "/" + settings.userDir;
232 //console.log("userDir:" + userDir);
233 var settingsFile = userDir + "/customSettings.js";
234 var jsonObj = require(settingsFile);
238 app.get("/getCommitsInfo", function(req,res) {
239 var appDir = path.dirname(require.main.filename);
240 var userDir = appDir + "/" + settings.userDir;
242 var filePath = req.query.filePath;
243 var fullFilePath = userDir + "/codecloud/" + filePath ;
244 //console.log("fullFilePath:" + fullFilePath);
245 var exec = require('child_process').exec;
246 var commandToExec = appDir + "/git_scripts/gitlog " + fullFilePath ;
247 console.log("commandToExec:" + commandToExec);
248 var child = exec(commandToExec ,function (error,stdout,stderr){
250 console.log("Error occured:" + error);
252 //console.log("stderr:" + stderr);
253 res.send(500,{'error':error,'stderr':stderr});
255 res.send(500,{'error':error});
257 //console.log("stdout :" + stdout);
260 console.log("stderr:" + stderr);
263 //console.log("output:" + stdout);
264 res.send(200,{'stdout':stdout,'stderr':stderr});
270 app.get("/importCodeCloudFlow",
272 var appDir = path.dirname(require.main.filename);
273 var userDir = appDir + "/" + settings.userDir;
275 var commitId = req.query.commitId;
276 var filePath = req.query.filePath;
277 var fullFilePath = userDir + "/codecloud/" + filePath ;
278 //console.log("fullFilePath:" + fullFilePath);
279 var exec = require('child_process').exec;
280 var commandToExec = appDir + "/git_scripts/gitckout " + commitId + " " + fullFilePath ;
281 console.log("commandToExec:" + commandToExec);
282 var child = exec(commandToExec ,{maxBuffer: 1024 * 1024 * 16}, function (error,stdout,stderr){
284 console.log("Error occured:" + error);
286 //console.log("stderr:" + stderr);
287 res.send(500,{'error':error,'stderr':stderr});
289 res.send(500,{'error':error});
293 console.log("stderr:" + stderr);
296 //console.log("output:" + stdout);
297 res.send(200,{'stdout':stdout,'stderr':stderr});
303 app.get("/importGitLocalFlow",
305 var appDir = path.dirname(require.main.filename);
306 var gitLocalRepository = settings.gitLocalRepository;
308 var filePath = req.query.filePath;
309 var fullFilePath = gitLocalRepository +"/" + filePath ;
310 //console.log("fullFilePath:" + fullFilePath);
311 var exec = require('child_process').exec;
312 var commandToExec = "cat " + fullFilePath ;
313 console.log("commandToExec:" + commandToExec);
314 var child = exec(commandToExec ,{maxBuffer: 1024 * 1024 * 16}, function (error,stdout,stderr){
316 console.log("Error occured:" + error);
318 //console.log("stderr:" + stderr);
319 res.send(500,{'error':error,'stderr':stderr});
321 res.send(500,{'error':error});
325 console.log("stderr:" + stderr);
328 //console.log("output:" + stdout);
329 res.send(200,{'stdout':stdout,'stderr':stderr});
336 app.get("/gitcheckout", function(req,res) {
337 var appDir = path.dirname(require.main.filename);
338 var gitLocalRepository = settings.gitLocalRepository;
340 var branch = req.query.branch;
341 //console.log("fullFilePath:" + fullFilePath);
342 var exec = require('child_process').exec;
343 var commandToExec = appDir + "/git_scripts/gitcheckout " + gitLocalRepository + " " + branch ;
344 console.log("commandToExec:" + commandToExec);
345 var child = exec(commandToExec ,function (error,stdout,stderr){
347 console.log("Error occured:" + error);
349 console.log("stderr:" + stderr);
350 res.json({"output":stderr});
352 res.json({"output":error});
356 console.log("stderr:" + stderr);
359 res.json({"output": stderr + " " + stdout});
365 app.get("/gitpull", function(req,res) {
366 var appDir = path.dirname(require.main.filename);
367 var gitLocalRepository = settings.gitLocalRepository;
369 var branch = req.query.branch;
370 //console.log("fullFilePath:" + fullFilePath);
371 var exec = require('child_process').exec;
372 var commandToExec = appDir + "/git_scripts/gitpull " + gitLocalRepository ;
373 console.log("commandToExec:" + commandToExec);
374 var child = exec(commandToExec ,function (error,stdout,stderr){
376 console.log("Error occured:" + error);
378 console.log("stderr:" + stderr);
379 res.json({"output":stderr});
381 res.json({"output":error});
385 console.log("stderr:" + stderr);
388 res.json({"output": stderr + " " + stdout});
394 app.get("/gitstatus", function(req,res) {
395 var appDir = path.dirname(require.main.filename);
396 var gitLocalRepository = settings.gitLocalRepository;
398 var branch = req.query.branch;
399 //console.log("fullFilePath:" + fullFilePath);
400 var exec = require('child_process').exec;
401 var commandToExec = appDir + "/git_scripts/gitstatus " + gitLocalRepository ;
402 console.log("commandToExec:" + commandToExec);
403 var child = exec(commandToExec ,function (error,stdout,stderr){
405 console.log("Error occured:" + error);
407 console.log("stderr:" + stderr);
408 res.json({"output":stderr});
410 res.json({"output":error});
414 console.log("stderr:" + stderr);
417 res.json({"output": stderr + " " + stdout});
423 app.post("/getSharedFlow",
426 var qs = require('querystring');
428 req.on('data', function (data) {
431 req.on('end', function () {
432 var post = qs.parse(body);
433 //console.log("body:" + body);
434 fs.readFile(post.filePath, 'utf8', function (err,data) {
436 return console.log(err);
441 //res.sendFile(body.filePath);
445 app.post("/downloadYang",
448 var qs = require('querystring');
450 req.on('data', function (data) {
453 req.on('end', function () {
454 var post = qs.parse(body);
455 var fileName = post.fileName;
456 var appDir = path.dirname(require.main.filename);
457 var yangDir = appDir + "/yangFiles" ;
458 var fullPathToFile = yangDir + "/" + fileName;
459 res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
460 res.setHeader('Content-type', 'application/yang');
461 res.download(fullPathToFile);
465 function writeToFile(fullPathToFileName,str){
467 fs.writeFileSync(fullPathToFileName,str);
469 console.log("Error:" + e);
472 function getCurrentDate(){
474 var mm = d.getMonth() + 1;
475 var dd = d.getDate();
476 var yyyy = d.getYear() + 1900;
477 var hr = d.getHours();
478 var min = d.getMinutes();
479 var sec = d.getSeconds();
480 if(mm<10) mm = "0" + mm;
481 if(dd<10) dd = "0" + dd;
482 if(hr<10) hr = "0" + hr;
483 if(min<10) min = "0" + min;
484 if(sec<10) sec = "0" + sec;
485 var formatedValue = mm + "-" + dd + "-" + yyyy + "_" + hr + "" + min + "" + sec;
486 return formatedValue;
490 app.post("/downloadXml",
491 express.json({'limit':'16mb'}),
493 //console.log("Received request and processing:" + new Date());
494 var qs = require('querystring');
496 //var msecs1= Date.now();
497 req.on('data', function (data) {
500 req.on('end', function () {
501 var appDir = path.dirname(require.main.filename);
502 var xmlDir = appDir + "/" + settings.xmlPath;
503 //var msecs2= Date.now();
504 //console.log("Time taken to get request body:" + (msecs2 - msecs1));
505 var msecs3= Date.now();
506 var post = qs.parse(body);
507 var msecs4= Date.now();
508 //console.log("Time taken to parse body:" + (msecs4 - msecs3));
509 var xml = post['flowXml'];
510 //var pd = require('pretty-data').pd;
511 //var formatted_xml = pd.xml(xml);
512 var moduleName = post['moduleName'];
513 var methodName = post['methodName'];
514 if(moduleName == "" || methodName == ""){
515 res.send({"ERROR":"ServiceLogic Module Name and method name are required."});
517 //var formatted_date = getCurrentDate();
518 //var fileNameForServer=moduleName + "_" +methodName+ "_" + formatted_date + ".xml";
519 //var fileName=moduleName + "_method_" +methodName+ ".xml";
520 var fileName=moduleName + "_" +methodName+ ".xml";
521 var file = xmlDir + "/" + fileName;
523 //var msecs2= Date.now();
524 writeToFile(file,xml);
525 //var msecs3= Date.now();
526 //console.log("Time taken to write File:" + (msecs3 - msecs2));
527 res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
528 res.setHeader('Content-type', 'text/xml');
530 //console.log("Response sent:" + new Date());
535 app.post("/downloadJson",
536 express.json({'limit':'16mb'}),
538 var appDir = path.dirname(require.main.filename);
539 var sharedDir = appDir + "/" + settings.sharedDir;
540 var qs = require('querystring');
542 req.on('data', function (data) {
545 req.on('end', function () {
546 var post = qs.parse(body);
547 var jsonStr = post['flowJson'];
548 var moduleName = post['moduleName'];
549 var methodName = post['methodName'];
550 //console.log("jsonStr:" + jsonStr);
551 if(moduleName == "" || methodName == ""){
552 res.send({"ERROR":"ServiceLogic Module Name and method name are required."});
554 var formatted_date = getCurrentDate();
555 //console.log("moduleName:" + moduleName);
556 //console.log("methodName:" + methodName);
558 //var fileName=moduleName + "_method_" +methodName + ".json";
559 //var renameOldfileTo=moduleName + "_method_" +methodName+ "_" + formatted_date + ".json";
560 var fileName=moduleName + "_" +methodName + ".json";
561 var renameOldfileTo=moduleName + "_" +methodName+ "_" + formatted_date + ".json";
562 var file = sharedDir + "/" + fileName;
563 //console.log("fileName:" + fileName);
564 var renameFilePath = sharedDir + "/backups/" + renameOldfileTo;
565 //console.log("localfile:" + localfile);
566 if (fs.existsSync(file)) {
567 fs.rename(file,renameFilePath, function (err) {
569 console.log('Error :' + err);
571 //write the newer version
572 writeToFile(file,jsonStr);
573 res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
574 res.setHeader('Content-type', 'application/json');
575 //res.download(file);
579 //write the newer version
580 writeToFile(file,jsonStr);
581 res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
582 res.setHeader('Content-type', 'application/json');
583 //res.download(file);
591 express.json({'limit':'16mb'}),
593 //console.log("Processing Request");
594 var flows = req.body;
595 redNodes.setFlows(flows).then(function() {
597 }).otherwise(function(err) {
598 util.log("[red] Error saving flows : "+err);
599 res.send(500,err.message);
602 function(error,req,res,next) {
603 res.send(400,"Invalid Flow. Error " + error);
607 app.get("/nodes",function(req,res) {
608 if (req.get("accept") == "application/json") {
609 res.json(redNodes.getNodeList());
611 res.send(redNodes.getNodeConfigs());
618 if (!settings.available()) {
619 res.send(400,new Error("Settings unavailable").toString());
625 promise = redNodes.addNode(node.file).then(reportAddedModules);
626 } else if (node.module) {
627 var module = redNodes.getNodeModuleInfo(node.module);
629 res.send(400,"Module already loaded");
632 promise = installModule(node.module);
634 res.send(400,"Invalid request");
637 promise.then(function(info) {
639 }).otherwise(function(err) {
640 if (err.code === 404) {
643 res.send(400,err.toString());
647 function(err,req,res,next) {
648 console.log(err.toString());
653 app.delete("/nodes/:id",
655 if (!settings.available()) {
656 res.send(400,new Error("Settings unavailable").toString());
659 var id = req.params.id;
660 var removedNodes = [];
662 var node = redNodes.getNodeInfo(id);
665 var module = redNodes.getNodeModuleInfo(id);
670 promise = uninstallModule(id);
673 promise = when.resolve([redNodes.removeNode(id)]).then(reportRemovedModules);
676 promise.then(function(removedNodes) {
677 res.json(removedNodes);
678 }).otherwise(function(err) {
679 console.log(err.stack);
680 res.send(400,err.toString());
683 res.send(400,err.toString());
686 function(err,req,res,next) {
691 app.get("/nodes/:id", function(req,res) {
692 var id = req.params.id;
694 if (req.get("accept") == "application/json") {
695 result = redNodes.getNodeInfo(id);
697 result = redNodes.getNodeConfig(id);
706 app.put("/nodes/:id",
709 if (!settings.available()) {
710 res.send(400,new Error("Settings unavailable").toString());
714 if (!body.hasOwnProperty("enabled")) {
715 res.send(400,"Invalid request");
720 var id = req.params.id;
721 var node = redNodes.getNodeInfo(id);
724 } else if (!node.err && node.enabled === body.enabled) {
728 info = redNodes.enableNode(id);
730 info = redNodes.disableNode(id);
732 if (info.enabled == body.enabled && !info.err) {
733 comms.publish("node/"+(body.enabled?"enabled":"disabled"),info,false);
734 util.log("[red] "+(body.enabled?"Enabled":"Disabled")+" node types:");
735 for (var i=0;i<info.types.length;i++) {
736 util.log("[red] - "+info.types[i]);
738 } else if (body.enabled && info.err) {
739 util.log("[red] Failed to enable node:");
740 util.log("[red] - "+info.name+" : "+info.err);
745 res.send(400,err.toString());
749 app.get("/getCodeCloudFlows",function(req,res) {
750 var userDir=settings.userDir;
751 var codeCloudDir=userDir + "/codecloud";
752 var glob = require("glob")
753 glob(codeCloudDir + "/**/*.json", null, function (er, files) {
754 // files is an array of filenames.
755 // If the `nonull` option is set, and nothing
756 // was found, then files is ["**/*.js"]
757 // er is an error object or null.
758 //console.dir(files);
760 for(var i=0;files!= null && i<files.length;i++){
761 var f = files[i].replace( new RegExp(codeCloudDir + "/", "g" ), "" );
765 res.json({"files" : filesList});
769 app.get("/getCurrentGitBranch",function(req,res) {
770 var appDir = path.dirname(require.main.filename);
771 var userDir=settings.userDir;
772 var settingsFile = appDir + "/" + userDir + "/customSettings.js";
773 //console.log("settingsFile:" + settingsFile);
774 var jsonObj = require(settingsFile);
775 var gitLocalRepository=jsonObj.gitLocalRepository;
776 if(gitLocalRepository == undefined || gitLocalRepository == null || gitLocalRepository == ''){
777 res.json({"output" : "GIT_LOCAL_REPOSITORY_NOT_SET"});
780 var exec = require('child_process').exec;
781 var commandToExec = appDir + "/git_scripts/gitcurbranch " + gitLocalRepository ;
782 console.log("commandToExec:" + commandToExec);
783 var child = exec(commandToExec ,function (error,stdout,stderr){
785 console.log("Error occured:" + error);
787 console.log("stderr:" + stderr);
788 res.json({"output":stderr});
790 res.json({"output":error});
794 console.log("stderr:" + stderr);
797 res.json({"output":stdout});
804 app.get("/getGitLocalFlows",function(req,res) {
805 var appDir = path.dirname(require.main.filename);
806 var userDir=settings.userDir;
807 var settingsFile = appDir + "/" + userDir + "/customSettings.js";
808 //console.log("settingsFile:" + settingsFile);
809 var jsonObj = require(settingsFile);
810 var performGitPull = jsonObj.performGitPull;
811 if(performGitPull == undefined || performGitPull == null) {
814 var gitLocalRepository=jsonObj.gitLocalRepository;
815 if(gitLocalRepository == undefined || gitLocalRepository == null || gitLocalRepository == ''){
816 res.json({"files" : ["GIT_LOCAL_REPOSITORY_NOT_SET"]});
821 if(performGitPull == "Y"){
822 var exec = require('child_process').exec;
823 var commandToExec = appDir + "/git_scripts/gitpull " + gitLocalRepository ;
824 console.log("commandToExec:" + commandToExec);
825 var child = exec(commandToExec ,function (error,stdout,stderr){
827 console.log("Error occured:" + error);
829 console.log("stderr:" + stderr);
830 res.json({"files":[]});
832 res.json({"files":[]});
836 console.log("stderr:" + stderr);
839 var glob = require("glob")
840 glob(gitLocalRepository + "/**/*.json", null, function (er, files) {
841 // files is an array of filenames.
842 // If the `nonull` option is set, and nothing
843 // was found, then files is ["**/*.js"]
844 // er is an error object or null.
845 //console.dir(files);
847 for(var i=0;files!= null && i<files.length;i++){
848 var f = files[i].replace( new RegExp(gitLocalRepository + "/", "g" ), "" );
852 res.json({"files" : filesList});
857 }else{//git pull not requested
858 var glob = require("glob")
859 glob(gitLocalRepository + "/**/*.json", null, function (er, files) {
860 // files is an array of filenames.
861 // If the `nonull` option is set, and nothing
862 // was found, then files is ["**/*.js"]
863 // er is an error object or null.
864 //console.dir(files);
866 for(var i=0;files!= null && i<files.length;i++){
867 var f = files[i].replace( new RegExp(gitLocalRepository + "/", "g" ), "" );
871 res.json({"files" : filesList});
877 app.get("/flowShareUsers",function(req,res) {
878 res.json(flowShareUsers);
880 app.get("/getRelease",function(req,res) {
881 var userDir = settings.userDir;
882 //var release = userDir.replace(/releases/g,"release");
883 res.json({"release" : userDir});
885 app.post("/getFiles/:id",function(req,res) {
886 var id = req.params.id;
887 //console.log("id:" + id);
888 var userDir=settings.userDir;
889 var flowDir= userDir + "/../" + id + "/flows/shared";
890 //console.log("flowDir:" + flowDir);
891 fs.readdir(flowDir,function(err, files){
893 res.json({"files": []});
895 var onlyFilesArr =[];
896 if(files != null && files.length>0){
897 files.sort(function(a,b){
898 //console.log("file1:" + a);
899 //console.log("file2:" + b);
900 var fileStat1=fs.statSync(flowDir+ "/" + a);
901 var fileStat2=fs.statSync(flowDir+ "/" + b);
902 if(fileStat1.mtime > fileStat2.mtime){
904 }else if(fileStat1.mtime < fileStat2.mtime){
910 for(var i=0;i<files.length;i++){
911 var fileStat=fs.statSync(flowDir+ "/" + files[i]);
912 if(fileStat.isFile()){
913 onlyFilesArr.push({"filePath":flowDir+ "/" + files[i],"name":files[i]});
916 res.json(onlyFilesArr);
918 res.json({"files": []});
924 app.post("/updateConfiguration",
927 var qs = require('querystring');
928 //console.log("Received the request:");
930 req.on('data', function (data) {
933 req.on('end',function(){
934 var post = qs.parse(body);
935 var dbHost = post["dbHost"];
936 var dbPort = post["dbPort"];
937 var dbName = post["dbName"];
938 var dbUser = post["dbUser"];
939 var dbPassword = post["dbPassword"];
940 var gitLocalRepository = post["gitLocalRepository"];
941 var performGitPull = post["performGitPull"];
942 var restConfUrl = post["restConfUrl"];
943 var restConfUser = post["restConfUser"];
944 var restConfPassword = post["restConfPassword"];
945 var emailAddress = post["emailAddress"];
946 var formatXML = post["formatXML"];
947 var formatJSON = post["formatJSON"];
948 var appDir = path.dirname(require.main.filename);
949 var userDir = appDir + "/" + settings.userDir;
950 console.log("userDir:" + userDir);
952 var settingsFile = userDir + "/customSettings.js";
953 var jsonObj = require(settingsFile);
954 jsonObj.emailAddress = emailAddress;
955 jsonObj.flowFile = jsonObj.flowFile.replace(appDir + "/",'');
956 jsonObj.dbHost = dbHost;
957 jsonObj.dbPort = dbPort;
958 jsonObj.dbName = dbName;
959 jsonObj.dbUser = dbUser;
960 jsonObj.dbPassword = dbPassword;
961 jsonObj.gitLocalRepository = gitLocalRepository;
962 jsonObj.performGitPull = performGitPull;
963 jsonObj.restConfUrl = restConfUrl;
964 jsonObj.restConfUser = restConfUser;
965 jsonObj.restConfPassword = restConfPassword;
966 jsonObj.formatXML = formatXML;
967 jsonObj.formatJSON = formatJSON;
968 var updatedSettings = jsonObj;
970 var settingsStr= "module.exports=" + JSON.stringify(updatedSettings,null,4);
971 //console.log("settingsStr:" + settingsStr);
972 fs.writeFileSync(settingsFile,settingsStr);
973 var svcLogicPropStr = "" ;
974 svcLogicPropStr += "org.onap.ccsdk.sli.dbtype=jdbc" + "\n";
975 svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.url=jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "\n";
976 svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.database=" + dbName + "\n";
977 svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.user=" + dbUser + "\n";
978 svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.password=" + dbPassword;
980 //create svclogic.properties file in the conf dir
981 var svcPropFile = userDir + "/conf/svclogic.properties";
982 fs.writeFileSync(svcPropFile,svcLogicPropStr);
984 res.send({"status": "success"});
986 console.log("Error:" + e);
987 res.send({"status": "error"});
993 app.post("/deleteYangFile",
996 var qs = require('querystring');
997 //console.log("Received the request:");
999 req.on('data', function (data) {
1002 req.on('end',function(){
1003 var post = qs.parse(body);
1004 //console.dir(body);
1005 var fileName = post["fileName"];
1006 var appDir = path.dirname(require.main.filename);
1007 var yangFilePath = appDir + "/yangFiles/" + fileName;
1009 fs.unlinkSync(yangFilePath);
1010 res.send({"status" :"SUCCESS"});
1012 console.log("error" + err);
1013 res.send({"status" :"ERROR"});
1015 //console.log("prevPassword:" + settings.httpAuth.pass );
1020 app.post("/updatePassword",
1023 var qs = require('querystring');
1024 //console.log("Received the request:");
1026 req.on('data', function (data) {
1029 req.on('end',function(){
1030 var post = qs.parse(body);
1031 //console.dir(body);
1032 var password = post["password"];
1033 //console.log("prevPassword:" + settings.httpAuth.pass );
1034 //console.log("New password:" + password);
1035 var crypto = require("crypto");
1036 var cryptPasswd = crypto.createHash('md5').update(password,'utf8').digest('hex')
1037 var appDir = path.dirname(require.main.filename);
1038 var userDir = appDir + "/" + settings.userDir;
1039 //console.log("userDir:" + userDir);
1040 /*var newSettings = settings;
1041 newSettings.httpAuth.pass = cryptPasswd;
1042 var updatedSettings = JSON.stringify(settings,null,4);
1043 var settingsStr = "module.exports=" + updatedSettings;
1044 console.log(updatedSettings);
1047 var settingsFile = userDir + "/customSettings.js";
1048 //console.log("settingsFile:" + settingsFile);
1049 //var buf = fs.readFileSync(settingsFile, "utf8");
1050 var jsonObj = require(settingsFile);
1051 //console.log("jsonObj:" + JSON.stringify(jsonObj));
1052 jsonObj.httpAuth.pass = cryptPasswd;
1053 jsonObj.httpAdminAuth.pass = cryptPasswd;
1054 jsonObj.httpNodeAuth.pass = cryptPasswd;
1055 jsonObj.flowFile = jsonObj.flowFile.replace(appDir + "/",'');
1056 var updatedSettings = jsonObj;
1058 delete updatedSettings.httpRoot;
1059 delete updatedSettings.disableEditor;
1060 delete updatedSettings.httpAdminRoot;
1061 delete updatedSettings.httpAdminAuth;
1062 delete updatedSettings.httpNodeRoot;
1063 delete updatedSettings.httpNodeAuth;
1064 delete updatedSettings.uiHost;
1065 delete updatedSettings.version;
1067 var settingsStr= "module.exports=" + JSON.stringify(updatedSettings,null,4);
1068 //console.log("settingsStr:" + settingsStr);
1069 fs.writeFileSync(settingsFile,settingsStr);
1070 settings.httpAuth.pass = cryptPasswd;
1071 res.send({"status": "success"});
1073 console.log("Error:" + e);
1074 res.send({"status": "error"});
1080 var appDir = path.dirname(require.main.filename);
1081 var yangDir = appDir + "/yangFiles" ;
1082 var diskStorage = multer.diskStorage({
1083 destination: function (req, file, callback) {
1084 callback(null, yangDir);
1086 filename: function (req, file, callback) {
1087 //callback(null, file.fieldname + '-' + Date.now());
1088 callback(null, file.originalname);
1091 var upload = multer({ storage : diskStorage}).single('yangFile');
1093 app.post('/api/uploadyang',function(req,res){
1094 upload(req,res,function(err) {
1097 return res.end("Error uploading file." + err);
1100 var fileName = req.file.originalname;
1101 var yangFileFullPath = appDir + "/yangFiles/" + fileName;
1102 console.log("yangFileFullPath:" + yangFileFullPath);
1103 var commandToExec ="";
1104 if(fileName != null){
1105 var matchedArr = fileName.match(/.zip$/);
1106 if(matchedArr != null && matchedArr.length >0){
1107 console.log("uploaded zip file" + fileName);
1108 //commandToExec = appDir + "/tools/generate_props_from_yangs_zip.sh " + yangFileFullPath ;
1109 commandToExec = appDir + "/tools/generate_props_from_yang.sh " + yangFileFullPath ;
1111 commandToExec = appDir + "/tools/generate_props_from_yang.sh " + yangFileFullPath ;
1112 console.log("uploaded file" + fileName);
1115 var exec = require('child_process').exec;
1116 console.log("commandToExec:" + commandToExec);
1117 var child = exec(commandToExec ,function (error,stdout,stderr){
1119 console.log("Error occured:" + error);
1120 var msg = "File " + fileName + " could not be processed successfully.";
1122 console.log("stderr:" + stderr);
1123 res.json({"sliValuesObj" : [],"message":msg});
1125 res.json({"sliValuesObj" : [],"message":msg});
1129 console.log("stderr:" + stderr);
1132 console.log("stdout:" + stdout);
1134 var msg = "File " + fileName + " processed successfully.";
1135 var generatedJSDir=appDir + "/generatedJS";
1136 var sliValuesObj =[];
1137 //var glob = require("glob");
1138 //glob(generatedJSDir + "/**/*.js", null, function (er, files) {
1140 var sliValuesObj =[];
1141 for(var i=0;files!= null && i<files.length;i++){
1142 var f = files[i].replace( new RegExp(generatedJSDir + "/", "g" ), "" );
1143 console.log("loading file " + f);
1145 sliValuesObj.push(require(files[i]));
1146 //console.dir(sliValuesObj);
1148 console.log("Error:Could not load file " + files[i]);
1151 res.json({"sliValuesObj" : sliValuesObj,"message":msg});
1154 res.json({"sliValuesObj" : sliValuesObj,"message":msg});
1160 function getFormattedDate(){
1162 var mm = d.getMonth() + 1;
1163 var dd = d.getDate();
1164 var yyyy = d.getYear() + 1900;
1165 var hr = d.getHours();
1166 var min = d.getMinutes();
1167 var sec = d.getSeconds();
1168 if(mm<10) mm = "0" + mm;
1169 if(dd<10) dd = "0" + dd;
1170 if(hr<10) hr = "0" + hr;
1171 if(min<10) min = "0" + min;
1172 if(sec<10) sec = "0" + sec;
1173 var formatedValue = yyyy + "-" + mm + "-" + dd + "_" + hr + ":" + min + ":" + sec;
1174 return formatedValue;
1178 app.post("/saveTestDGInput",
1179 express.json({'limit':'16mb'}),
1181 var qs = require('querystring');
1183 req.on('data', function (data) {
1186 req.on('end', function () {
1187 var appDir = path.dirname(require.main.filename);
1188 var inputFilesDir = appDir + "/" + "inputFiles";
1189 if (!fs.existsSync(inputFilesDir)){
1190 fs.mkdirSync(inputFilesDir);
1192 var post = qs.parse(body);
1193 var moduleName = post['moduleName'];
1194 var rpcName = post['rpcName'];
1195 var fullFileName = inputFilesDir + "/" +moduleName + "_" + rpcName + "_" + getFormattedDate();
1196 var inputStr = post['inputStr'];
1197 writeToFile(fullFileName,inputStr);
1202 app.post("/getInputFiles",function(req,res) {
1203 var qs = require('querystring');
1205 req.on('data', function (data) {
1208 req.on('end', function () {
1209 var appDir = path.dirname(require.main.filename);
1210 var inputFilesDir = appDir + "/" + "inputFiles";
1211 if (!fs.existsSync(inputFilesDir)){
1212 fs.mkdirSync(inputFilesDir);
1214 var post = qs.parse(body);
1215 var moduleName = post['moduleName'];
1216 var rpcName = post['rpcName'];
1217 var glob = require("glob");
1218 var filePatt = "/**/" + moduleName + "_" + rpcName + "*";
1219 glob(inputFilesDir + filePatt, null, function (er, files) {
1221 for(var i=0;files!= null && i<files.length;i++){
1222 var f = files[i].replace( new RegExp(inputFilesDir + "/", "g" ), "" );
1225 res.json({"files" : filesList});
1230 app.post("/deleteInputFile",
1233 var qs = require('querystring');
1235 req.on('data', function (data) {
1238 req.on('end',function(){
1239 var post = qs.parse(body);
1240 var fileName = post["fileName"];
1241 var appDir = path.dirname(require.main.filename);
1242 var filePath = appDir + "/inputFiles/" + fileName;
1244 fs.unlinkSync(filePath);
1245 res.send({"status" :"SUCCESS"});
1247 console.log("error" + err);
1248 res.send({"status" :"ERROR"});
1250 //console.log("prevPassword:" + settings.httpAuth.pass );
1254 app.post("/loadInputFile",
1257 var qs = require('querystring');
1259 req.on('data', function (data) {
1262 req.on('end',function(){
1263 var post = qs.parse(body);
1264 var fileName = post["fileName"];
1265 //console.log("fileName" + fileName);
1266 var appDir = path.dirname(require.main.filename);
1267 var filePath = appDir + "/inputFiles/" + fileName;
1268 //console.log("filePath:" + filePath);
1270 fs.readFile(filePath, 'utf8', function (err,data) {
1272 return console.log(err);
1274 res.json({'input':data});
1277 console.log("error" + err);
1278 res.json({"status" :"ERROR"});
1283 app.get("/getYangFiles",function(req,res) {
1284 var appDir = path.dirname(require.main.filename);
1285 var yangFilesDir=appDir + "/yangFiles";
1286 var glob = require("glob")
1287 glob(yangFilesDir + "/**/*.yang", null, function (er, files) {
1289 for(var i=0;files!= null && i<files.length;i++){
1290 var f = files[i].replace( new RegExp(yangFilesDir + "/", "g" ), "" );
1294 res.json({"files" : filesList});
1300 function reportAddedModules(info) {
1301 comms.publish("node/added",info,false);
1302 if (info.length > 0) {
1303 util.log("[red] Added node types:");
1304 for (var i=0;i<info.length;i++) {
1305 for (var j=0;j<info[i].types.length;j++) {
1306 util.log("[red] - "+
1307 (info[i].module?info[i].module+":":"")+
1309 (info[i].err?" : "+info[i].err:"")
1317 function reportRemovedModules(removedNodes) {
1318 comms.publish("node/removed",removedNodes,false);
1319 util.log("[red] Removed node types:");
1320 for (var j=0;j<removedNodes.length;j++) {
1321 for (var i=0;i<removedNodes[j].types.length;i++) {
1322 util.log("[red] - "+(removedNodes[i].module?removedNodes[i].module+":":"")+removedNodes[j].types[i]);
1325 return removedNodes;
1328 function installModule(module) {
1329 //TODO: ensure module is 'safe'
1330 return when.promise(function(resolve,reject) {
1331 if (/[\s;]/.test(module)) {
1332 reject(new Error("Invalid module name"));
1335 util.log("[red] Installing module: "+module);
1336 var child = exec('npm install --production '+module, function(err, stdin, stdout) {
1338 var lookFor404 = new RegExp(" 404 .*"+module+"$","m");
1339 if (lookFor404.test(stdout)) {
1340 util.log("[red] Installation of module "+module+" failed: module not found");
1341 var e = new Error();
1345 util.log("[red] Installation of module "+module+" failed:");
1346 util.log("------------------------------------------");
1347 console.log(err.toString());
1348 util.log("------------------------------------------");
1349 reject(new Error("Install failed"));
1352 util.log("[red] Installed module: "+module);
1353 resolve(redNodes.addModule(module).then(reportAddedModules));
1359 function uninstallModule(module) {
1360 var list = redNodes.removeModule(module);
1361 return when.promise(function(resolve,reject) {
1362 if (/[\s;]/.test(module)) {
1363 reject(new Error("Invalid module name"));
1366 util.log("[red] Removing module: "+module);
1367 var child = exec('npm remove '+module, function(err, stdin, stdout) {
1369 util.log("[red] Removal of module "+module+" failed:");
1370 util.log("------------------------------------------");
1371 console.log(err.toString());
1372 util.log("------------------------------------------");
1373 reject(new Error("Removal failed"));
1375 util.log("[red] Removed module: "+module);
1376 reportRemovedModules(list);
1384 var defer = when.defer();
1386 storage.init(settings).then(function() {
1387 settings.load(storage).then(function() {
1388 console.log("\nWelcome to Node-RED\n===================\n");
1389 if (settings.version) {
1390 util.log("[red] Version: "+settings.version);
1392 util.log("[red] Loading palette nodes");
1393 redNodes.init(settings,storage);
1394 redNodes.load().then(function() {
1396 var nodes = redNodes.getNodeList();
1397 var nodeErrors = nodes.filter(function(n) { return n.err!=null;});
1398 var nodeMissing = nodes.filter(function(n) { return n.module && n.enabled && !n.loaded && !n.err;});
1399 if (nodeErrors.length > 0) {
1400 util.log("------------------------------------------");
1401 if (settings.verbose) {
1402 for (i=0;i<nodeErrors.length;i+=1) {
1403 util.log("["+nodeErrors[i].name+"] "+nodeErrors[i].err);
1406 util.log("[red] Failed to register "+nodeErrors.length+" node type"+(nodeErrors.length==1?"":"s"));
1407 util.log("[red] Run with -v for details");
1409 util.log("------------------------------------------");
1411 if (nodeMissing.length > 0) {
1412 util.log("[red] Missing node modules:");
1413 var missingModules = {};
1414 for (i=0;i<nodeMissing.length;i++) {
1415 var missing = nodeMissing[i];
1416 missingModules[missing.module] = (missingModules[missing.module]||[]).concat(missing.types);
1419 for (i in missingModules) {
1420 if (missingModules.hasOwnProperty(i)) {
1421 util.log("[red] - "+i+": "+missingModules[i].join(", "));
1422 if (settings.autoInstallModules) {
1423 installModule(i).otherwise(function(err) {
1424 // Error already reported. Need the otherwise handler
1425 // to stop the error propagating any further
1430 if (!settings.autoInstallModules) {
1431 util.log("[red] Removing modules from config");
1432 redNodes.cleanNodeList();
1437 redNodes.loadFlows();
1438 }).otherwise(function(err) {
1443 }).otherwise(function(err) {
1447 return defer.promise;
1451 redNodes.stopFlows();
1461 module.exports.__defineGetter__("app", function() { return app });
1462 module.exports.__defineGetter__("nodeApp", function() { return nodeApp });
1463 module.exports.__defineGetter__("server", function() { return server });