f2b4815e5cd03abd6f31a62bdb2202b5c1bc3814
[ccsdk/distribution.git] / dgbuilder / nodes / dge / dgemain / dgstart.js
1 /**
2  * Copyright 2013 IBM Corp.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  **/
16
17
18 module.exports = function(RED) {
19     "use strict";
20     var util = require("util");
21     var vm = require("vm");
22     //var dgxml=require("/home/users/schinthakayala/nodered/sheshi/dgxml/dgxml2");
23     var _=require('lodash');
24     var fs=require('fs');
25     var path = require('path');
26     var appDir = path.dirname(require.main.filename);
27     var userDir = appDir + "/" + RED.settings.userDir;
28     var dbHost = RED.settings.dbHost;
29     var request = require('request');
30     var sharedDir = appDir + "/" + RED.settings.sharedDir;
31     var xmlDir = appDir + "/" + RED.settings.xmlPath;
32
33     //console.log("appDir:" + appDir);
34     //var dgeraw=fs.readFileSync(appDir + "/dge.json").toString();
35     //var dgejson=JSON.parse(dgeraw);
36     //var uploadUrl=dgejson.slaHost + dgejson.uploadUrl;
37     //var slaUrl=dgejson.slaHost + dgejson.slaUrl;
38     //var uploadUrl=RED.settings.slaHost +  RED.settings.uploadUrl;
39     //var slaUrl=RED.settings.slaHost + RED.settings.slaUrl;
40     var uploadUrl="";
41     var slaUrl="";
42     //console.log("Upload url: " + uploadUrl);
43
44     function dgstart(n) {
45         RED.nodes.createNode(this,n);
46         this.name = n.name;
47         this.topic = n.topic;
48     }
49
50     function writeHtmlToFile(fileName,str){
51       var localfile = appDir + "/" + RED.settings.htmlPath + fileName;
52         try{
53            fs.writeFileSync(localfile,str);
54         }catch(e){
55                 console.log("Error:" + e);
56         }
57     }    
58
59     function writeXmlToFile(fileName,str){
60       var localfile = appDir + "/" + RED.settings.xmlPath + fileName;
61         try{
62            fs.writeFileSync(localfile,str);
63         }catch(e){
64                 console.log("Error:" + e);
65         }
66     }    
67
68     function sendXml(fileName,res) {
69       var needle, localfile, data;
70       needle = require('needle')
71       localfile = appDir + "/" + RED.settings.xmlPath + fileName;
72         console.log("localfile:" + localfile);
73       data={
74         uploadedfile: { file: localfile, content_type: 'text/xml' }
75       }
76       needle.post(uploadUrl, data, { multipart: true }, function(err, resp, body) {
77         //console.log(body)
78         if(resp != undefined && resp != null){
79                 console.log("resp Code for sendXml:" + resp.statusCode);
80         }
81         fs.unlink(localfile, function (error) {
82            if (error) {
83                  console.log("Error deleting file "+localfile);
84            }else{
85                  //console.log("deleted file:" + localfile);
86            }    
87         });
88
89         if(err){
90                 console.log("Error posting to slaUrl:" + slaUrl);       
91                 console.log("Error:" +err);
92                 res.json({"error":err});
93         }else{
94                 //console.dir(resp);
95                 //console.log("slaUrl:" + slaUrl);      
96                 res.json({"url":slaUrl});
97         }
98
99       });
100     }    
101
102     function oldsendXml(fileName) {
103       console.log("In sendXML for file: " + fileName);
104       var fileStream, formdata, localfile;
105       localfile = appDir + "/" + RED.settings.xmlPath + fileName;
106
107       formdata = {
108         MAX_FILE_SIZE: "100000",
109         uploadedfile: {
110           options: {
111             contentType: 'audio/mpeg'
112           }
113         }
114
115       };
116
117       console.log("Attempting to upload file: " + localfile);
118       console.log("Sending to: " + uploadUrl);
119       formdata.uploadedfile.value = fs.createReadStream(localfile);
120       fileStream = formdata.uploadedfile.value;
121
122 //console.log("Formdata:");
123 //console.dir(formdata);
124
125       request.post({
126         url: uploadUrl,
127         proxy: false,
128         formData: formdata
129         }, function(err, resp, body) {
130         fileStream.close();
131         console.log("err: " + err);
132         return console.log("body: " + body);
133       });
134
135     };
136
137     RED.nodes.registerType("dgstart",dgstart);
138 /*
139     RED.httpAdmin.post("/uploadxml", function(req,res) {
140         console.dir(req);
141         console.log("USER:" + req.user);
142       console.log("Got request to upload xml to SDN-C.");
143       console.log("Requested filename to upload: " + req.params.fileName);
144       console.log("Requested xml to upload: " + req.params.xmlStr);
145         writeToFile( req.params.fileName,req.params.xmlStr);
146         
147       sendXml(req.params.fileName,res);
148       // res.send("Attempt complete.");
149       // res.redirect(slaUrl);
150     });
151 */
152
153     RED.httpAdmin.post("/OldUploadxml", function(req,res) {
154         //console.dir(req);
155         //console.log("USER:" + req.user);
156         var qs = require('querystring');
157         var body = '';
158         req.on('data', function (data) {
159             body += data;
160             // Too much POST data, kill the connection!
161             /*if (body.length > 1e6)
162                 request.connection.destroy();
163                 */
164         });
165         req.on('end', function () {
166                 //console.log("BODY:" + body);
167                 var d = new Date().getTime();
168                 var user = req.user;
169                 var fileName= user + "_" + d +".xml";
170                 var post = qs.parse(body);
171                 //console.log(JSON.stringify(post));
172             // use post['blah'], etc.
173                 var localfile = appDir + "/" + RED.settings.xmlPath + fileName;
174                 //console.log("localfile:" + localfile);        
175                 var xmlStr = post['flowXml'];
176                 writeXmlToFile(fileName,xmlStr);
177                 sendXml(fileName,res);
178                 
179             });
180
181         });
182
183     RED.httpAdmin.post("/uploadxml", function(req,res) {
184         //console.dir(req);
185         //console.log("USER:" + req.user);
186         var qs = require('querystring');
187         var body = '';
188         req.on('data', function (data) {
189             body += data;
190             // Too much POST data, kill the connection!
191             /*if (body.length > 1e6)
192                 request.connection.destroy();
193                 */
194         });
195         req.on('end', function () {
196                 //console.log("BODY:" + body);
197                 var d = new Date().getTime();
198                 var user = req.user;
199                 var fileName= user + "_" + d +".xml";
200                 var post = qs.parse(body);
201                 //console.log(JSON.stringify(post));
202             // use post['blah'], etc.
203                 var localfile = appDir + "/" + RED.settings.xmlPath + fileName;
204                 //console.log("localfile:" + localfile);        
205                 var xmlStr = post['flowXml'];
206                 var moduleName = post['module'];
207                 var rpc = post['rpc'];
208                 writeXmlToFile(fileName,xmlStr);
209                 uploadDG(localfile,moduleName,rpc,res);
210             });
211
212         });
213
214
215 function uploadDG(filePath,moduleName,rpc,res){
216         console.log("called uploadDG...");
217         var exec = require('child_process').exec;
218         var commandToExec = appDir + "/svclogic/svclogic.sh load " + filePath + " " + userDir + "/conf/svclogic.properties";
219         console.log("commandToExec:" + commandToExec);
220         var child = exec(commandToExec ,function (error,stdout,stderr){
221                 //console.log(error);
222                 console.log("stdout:" + stdout);
223                 console.log("stderr:" +  stderr);
224                 if(error){
225                         console.log("Error occured:" + error);
226                         if(stderr){
227                                 //console.log("stderr:" + stderr);
228                                 res.send(500,{'error':error,'stderr':stderr});
229                         }else{
230                                 res.send(500,{'error':error});
231                         }
232                         //console.log("stdout :" + stdout);
233                 }else{
234                         if(stdout ){
235                                 //console.log("output:" + stdout);
236                                 if(stdout.indexOf('Compiler error') != -1){
237                                         //console.log("compileError occured.");
238                                         
239                                         var resp = {
240                                                         'stdout':stdout,
241                                                         'stderr':"COMPILE_ERROR",
242                                                         'url':dbHost,
243                                                         'module':moduleName,
244                                                         'rpc':rpc
245                                                    }            
246                                         res.send(500,resp);
247                                 }else{
248                                         res.send(200,{'stdout':stdout,'stderr':stderr,"url":dbHost,"module" : moduleName,"rpc" : rpc});
249                                 }
250                         }
251                         if(stderr && !stdout){
252                                 //console.log("stderr:" + stderr);
253                                 if(stderr.indexOf("Saving SvcLogicGraph to database") != -1){
254                                         res.send(200,{'error':error,'stdout' :'','stderr':stderr,"url":dbHost,"module" : moduleName,"rpc" : rpc});
255                                 }else{
256                                         res.send(500,{'error':error,'stdout' :'','stderr':stderr});
257                                 }
258                         }
259                 }
260         });
261 }
262
263     RED.httpAdmin.get("/displayXml", function(req,res) {
264                         var _module = req.query._module;
265                         var rpc = req.query.rpc;
266                         var version = req.query.version;
267                         var mode = req.query.mode;
268                         var d = new Date().getTime();
269                         displayXml(_module,rpc,version,mode,res);
270             });
271
272 function displayXml(_module,rpc,version,mode,res){
273         var exec = require('child_process').exec;
274         var msg = {
275                 '_module' : _module,
276                 'rpc' : rpc,
277                 'version' : version,
278                 'mode' : mode
279         }
280         var commandToExec = appDir + "/svclogic/svclogic.sh get-source "   + _module + " " 
281                                 + rpc + " " + mode + " " + version + " " + userDir + "/conf/svclogic.properties";
282         console.log("commandToExec:" + commandToExec);
283         var child = exec(commandToExec ,{'maxBuffer':16*1024*1024},function (error,stdout,stderr){
284                 if(error){
285                         console.log("Error occured:" + error);
286                         if(stderr){
287                                 //console.log("stderr:" + stderr);
288                                 res.send(500,{'error':error,'stderr':stderr,'msg':msg});
289                         }else{
290                                 res.send(500,{'error':error,'msg':msg});
291                         }
292                 }else{
293                         if(stderr){
294                                 console.log("stderr:" + stderr);
295                         }
296                         if(stdout){
297                                 res.send({'xmldata' : "<xmp>" + stdout + "</xmp>"});
298                         }
299                 }
300         });
301 }
302
303
304     RED.httpAdmin.post("/downloadDGXml", function(req,res) {
305                 //console.dir(req);
306                 var qs = require('querystring');
307                 var body = '';
308                 req.on('data', function (data) {
309                         body += data;
310                 });
311
312                 req.on('end', function () {
313                         var post = qs.parse(body);
314                         var _module = post._module;
315                         var rpc = post.rpc;
316                         var version = post.version;
317                         var mode = post.mode;
318                         var d = new Date().getTime();
319                         downloadDGXml(_module,rpc,version,mode,res);
320                 });
321             });
322
323 function downloadDGXml(_module,rpc,version,mode,res){
324         var exec = require('child_process').exec;
325         var msg = {
326                 '_module' : _module,
327                 'rpc' : rpc,
328                 'version' : version,
329                 'mode' : mode
330         }
331         var commandToExec = appDir + "/svclogic/svclogic.sh get-source "   + _module + " " 
332                                 + rpc + " " + mode + " " + version + " " + userDir + "/conf/svclogic.properties";
333         console.log("commandToExec:" + commandToExec);
334         var child = exec(commandToExec ,function (error,stdout,stderr){
335                 if(error){
336                         console.log("Error occured:" + error);
337                         if(stderr){
338                                 //console.log("stderr:" + stderr);
339                                 res.send(500,{'error':error,'stderr':stderr,'msg':msg});
340                         }else{
341                                 res.send(500,{'error':error,'msg':msg});
342                         }
343                 }else{
344                         if(stderr){
345                                 console.log("stderr:" + stderr);
346                         }
347                         if(stdout){
348                                 //console.log("output:" + stdout);
349                                 //var newOutput = "<pre>" + stdout.replace(/\n/g,'<br>') + "</pre>";
350                                 //res.json({'stdout': stdout ,'stderr':stderr,"msg":msg});
351                                 //res.set('Content-Type', 'text/xml');
352                                 //res.set('Content-Type', 'application/octet-stream');
353                                 //res.end("<code>" + stdout + "</code>" ); 
354                                 //var newOutput ="<html><body>" + stdout  + "</body></html>";
355                                 //res.send(new Buffer( "<code>" +  newOutput + "</code>" ) ); 
356                                 //res.send(newOutput); 
357
358                                 /*
359                                 var xslStr = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">' +
360                                         '<xsl:output omit-xml-declaration="yes" indent="yes"/>' + 
361                                         '<xsl:template match="node()|@*">' +
362                                         '<xsl:copy>' +
363                                         '<xsl:apply-templates select="node()|@*"/>' +
364                                         '</xsl:copy>' +
365                                         '</xsl:template>' +
366                                         '</xsl:stylesheet>';
367                                 */
368
369                                 var formatted_date = getCurrentDate();
370                                 var fileName= "db_" + _module + "_" +rpc+ "_" + version + "_" +  formatted_date + ".html";
371                                 var file = xmlDir + "/" + fileName;
372                                 var xmlStr = '<xmp>' + stdout + "</xmp>";
373                                 //var xmlStr =  "<![CDATA[" + stdout + "]]";
374                                 //var xmlStr =   stdout.replace(/</g,"&lt;");
375                                 //xmlStr =   xmlStr.replace(/>/g,"&gt;");
376                                 //xmlStr =   xmlStr.replace(/\n>/g,"<br>");
377                                 //xmlStr =   xmlStr.replace(/\t>/g,"&nbsp;&nbsp;&nbsp;");
378                 
379                                 writeToFile(file,"<html><body>" +xmlStr+ "</body></html>");
380                                 //console.log("xmlStr:" + xmlStr);
381                                 res.setHeader('Content-disposition', 'attachment; filename=' + file);
382                                 //res.setHeader('Content-type', 'text/html');
383                                 res.setHeader('Content-type', 'text/xml');
384                                 res.download(file);
385                         }
386                 }
387         });
388 }
389
390
391     RED.httpAdmin.get("/displayAsGv", function(req,res) {
392                 var _module = req.query._module;
393                 var rpc = req.query.rpc;
394                 var version = req.query.version;
395                 var mode = req.query.mode;
396                 var d = new Date().getTime();
397                 displayAsGv(_module,rpc,version,mode,res);
398             });
399
400 function displayAsGv(_module,rpc,version,mode,res){
401         var exec = require('child_process').exec;
402         var msg = {
403                 '_module' : _module,
404                 'rpc' : rpc,
405                 'version' : version,
406                 'mode' : mode
407         }
408         var commandToExec = appDir + "/svclogic/svclogic.sh print " +
409                  _module + " " + rpc + " " + mode + " " + version + " "
410             //+ userDir + "/conf/svclogic.properties | dot -Tpng ";
411                                 //the label="""" is giving an error so replacing it with "null" 
412             + userDir + "/conf/svclogic.properties |sed -e 's%label=\"\"\"\"%label=\"null\"%g'| dot -Tsvg ";
413         console.log("commandToExec:" + commandToExec);
414             //+ userDir + "/conf/svclogic.properties | dot -Tsvg ";
415         //var child = exec(commandToExec ,function (error,stdout,stderr){
416         //var child = exec(commandToExec ,{maxBuffer:16*1024*1024},function (error,stdout,stderr){
417         //var child = exec(commandToExec ,{encoding:'base64',maxBuffer:20*1024*1024},function (error,stdout,stderr){
418         var child = exec(commandToExec ,{maxBuffer:20*1024*1024},function (error,stdout,stderr){
419                 if(error){
420                         console.log("Error occured:" + error);
421                         if(stderr){
422                                 console.log("stderr:" + stderr);
423                                 res.send(500,{'error':error,'stderr':stderr,"msg":msg});
424                         }else{
425                                 res.send(500,{'error':error,"msg":msg});
426                         }
427                 }else{
428                         if(stderr){
429                                 console.log("stderr:" + stderr);
430                                 //To convert base64 to ascii
431                                 //console.log(new Buffer(stderr, 'base64').toString('ascii'));
432                         }
433                         if(stdout){
434                                 //console.log(stdout.length);
435                                 //console.log("output:" + stdout);
436                                 //var svg_html =  stdout ;
437                                 //var image = "<img src='data:image/png;base64," + stdout + "'>";
438                                 //var image = "<iframe width='1200' height='750' src='data:image/png;base64," + stdout + "'></frame>";
439                                 //var image = "<iframe width='1200' height='750' src='data:image/svg+xml;base64," + stdout + "'></frame>";
440                                 //var image = "<iframe width='1200' height='750' src='data:image/gif;base64," + stdout + "'></frame>";
441                                 var image = "<iframe width='1200' height='750' src='data:image/svg+xml;UTF-8," + stdout + "'></frame>";
442                                 //console.log(image);
443                                 res.send({'svg_html':image});
444                         }
445                 }
446         });
447 }
448
449     RED.httpAdmin.post("/shareFlow", function(req,res) {
450         //console.dir(req);
451         //console.log("USER:" + req.user);
452         var qs = require('querystring');
453         var body = '';
454         req.on('data', function (data) {
455             body += data;
456             // Too much POST data, kill the connection!
457             /*if (body.length > 1e6)
458                 request.connection.destroy();
459                 */
460         });
461         req.on('end', function () {
462                 var post = qs.parse(body);
463                 
464                 var nodeSet = JSON.parse(post['flowData']);
465                 var activeWorkspace=post['activeWorkspace'];
466                 var methodName = "";
467                 var moduleName = "";
468                 for(var i=0;nodeSet != null && i<nodeSet.length;i++){
469                         var node = nodeSet[i];  
470                         if(node.type == 'module' ){
471                                 moduleName= node.name;
472                                 moduleName=moduleName.replace(/ /g,"-");
473                         }
474                         if(node.type == 'method' ){
475                                 methodName= node.name;
476                                 methodName=methodName.replace(/ /g,"-");
477                         }
478                 }
479                 //console.log("BODY:" + body);
480                 var d = new Date().getTime();
481                 var user = req.user;
482                 var fileName= moduleName + "_" +methodName+".json";
483                 var localfile = sharedDir + "/" + fileName;
484                 //console.log("localfile:" + localfile);        
485                 
486                 writeToFile(localfile,JSON.stringify(nodeSet));
487                 res.send({"fileName": fileName}); 
488             });
489
490         });
491
492
493     RED.httpAdmin.post("/sendEmail", function(req,res) {
494         //console.dir(req);
495         console.log("USER:" + req.user);
496         var fromAddr = RED.settings.emailAddress;
497         var toAddr =  RED.settings.emailAddress;
498         var qs = require('querystring');
499         var body = '';
500         req.on('data', function (data) {
501             body += data;
502             // Too much POST data, kill the connection!
503             /*if (body.length > 1e6)
504                 request.connection.destroy();
505                 */
506         });
507         req.on('end', function () {
508                 //console.log("BODY:" + body);
509                 var d = new Date().getTime();
510                 var user = req.user;
511                 var fileName= user + "_" + d +".html";
512                 var post = qs.parse(body);
513                 //console.log(JSON.stringify(post));
514             // use post['blah'], etc.
515                 var localfile = appDir + "/" + RED.settings.htmlPath + fileName;
516                 //console.log("localfile:" + localfile);        
517                 var nodemailer = require("nodemailer");
518                 nodemailer.sendmail = true;
519                 var transporter = nodemailer.createTransport();
520                 var ua = req.headers['user-agent'];
521                 var host = req.headers.host;
522                 var fullHtml="<!doctype html><html><head>" + post['flowHtml'];
523                         //fullHtml+="<div style='fill:both'></div>";
524                         fullHtml+="<div style='margin-left:10px;'><p>XML</p><br><textarea rows='50' cols='150'>" + post['flowXml'] + "</textarea>";
525                         fullHtml+="<p>JSON</p><br><textarea rows='50' cols='150'>" + post['flowJson'] + "</textarea></div>";
526                         fullHtml+="</body></html>";
527                 writeHtmlToFile(fileName,fullHtml);
528                 
529                 transporter.sendMail({
530                         from: fromAddr,
531                         to: toAddr,
532                         html: "<p>DG Node Flow. click on the attachment to view</p>",
533                         subject: 'Node flow from  Host:<' + host + '>',
534                         attachments : [{'filename': fileName,
535                                         'contentType': "text/html",
536                                         /*'filePath': localfile*/
537                                         'content': fs.createReadStream(localfile)
538                                       }]
539
540             }, function(err, response) {
541                         var fullPathtoFileName = appDir + "/" + RED.settings.htmlPath + fileName;
542                 fs.unlink(fullPathtoFileName, function (error) {
543                         if (error) {
544                                 console.log("Error deleting file "+fullPathtoFileName);
545                         }else{
546                                 //console.log("deleted file:" + fullPathtoFileName);
547                         }       
548                 });
549
550                 if(err){
551                         console.log("Error:" + err);
552                         res.json(err);
553                 }else{
554                         res.json(response);
555                 }
556                 console.log(response);
557             });
558
559         });
560
561                 
562         });
563 /*
564     RED.httpAdmin.post("/doxml/:id", function(req,res) {
565             var node = RED.nodes.getNode(req.params.id);
566             if (node != null) {
567                 try {
568                     // node.receive();
569                     //console.log("doxml was called for node: ");
570                     //console.dir(node);
571                     //console.log("calling getJson");
572                     var nrjson=dgxml.getJson();
573                     console.log("calling nodered2xml");
574                     var results=[];
575                     results=dgxml.nodered2xml(nrjson,node.id);
576                     var nrxml=results[0];
577                     fileName=results[1];
578                     console.log("Got this filename: " + fileName);
579                     // res.send(200);
580                     console.log("appDir: " + appDir);
581                     fs.writeFileSync(appDir + "/public/xml/"+fileName,nrxml);
582                     // res.send("XML generated! See help on right for link.");
583                     res.send(fileName);
584                 } catch(err) {
585                     res.send(500);
586                     node.error("doxml failed:"+err);
587                     console.log(err.stack);
588                 }
589             } else {
590                 res.send(404);
591             }
592     });
593 */
594 }

© 2017 ONAP. Copyright © The Linux Foundation ®. All Rights Reserved.
The Linux Foundation has registered trademarks and uses trademarks.
For a list of trademarks of The Linux Foundation, please see our Trademark Usage page.
Linux is a registered trademark of Linus Torvalds.
Privacy Policy and Terms of Use