UNPKG

25.1 kBJavaScriptView Raw
1/**
2 * Created by Harendra Kumar on 9/29/2016.
3 * purpose:Parsing instrument profile, and maintaining a hashMap.
4 */
5
6var instrumentationProfiles = []; //Array for all instrumentationProfiles , conatin all instrumentationProfiles
7var fileBasedKeyword = []; //Array for all fileBasedKeyword , conatin all files
8var list = []; //tis is an array that can store each file data
9
10var btManager = require('./BT/btManager.js')
11var btRuleList = require('./BT/btPatternRule.js') ;
12var btGlobalRule = require ('./BT/btGlobalRule.js');
13var btConfig = require('./BT/btConfig');
14
15var agentSetting= require("./agent-setting");
16var ndMthMonitor = require('./method-monitor/ndMethodMonitor.js');
17var ndExceptionMonitor = require('./exception/ndExceptionMonitor'),
18 backendRecord = require('./backend/backendRecord'),
19 NDHttpConditionStats = require('./HttpHeader/NDHttpConditionStats'),
20 NDSessionCaptureSettings = require('./HttpHeader/NDSessionCaptureSettings'),
21 instrumentationProfileParser = require('./njstrace/instrumentationProfleParser'),
22 ndKeywordFileModelObj = require('./ndKeywordFileModel'),
23 entryPonitManager = require('./utils/NDEntryPointManager');
24var NDConnectionManager = require("./NDConnectionManager");
25var instProfMsg = "";
26var builtinCoreModules = [ 'assert','buffer','child_process','cluster','crypto','dgram','dns','domain','events','fs','http','https','net','os','path','punycode','querystring', 'readline','stream','string_decoder','tls','tty','url','util','vm','zlib','smalloc' ];
27var instPrfCount = 0;
28var instrProfMap ={},keyWordModel= new Object();
29var coreInstrProfMap = {};
30var keywordName = null;
31var multiInstrProfCount = 1; //Counter for instrumentation profile , should be start from 1, because by default first instrumentation profile req send automatically
32var multiFileKeywordCount = 0; //Counter for keywordbased file, should be start from 0
33var util = require('./util');
34var currKeyword;
35var connTimeout = undefined
36
37function instrProfileParser() {}
38
39instrProfileParser.resetInstrListOnStart = function () {
40 instrumentationProfiles = [];
41 fileBasedKeyword = [];
42 multiInstrProfCount = 1;
43 multiFileKeywordCount = 0;
44 clearTimeout(connTimeout);connTimeout = undefined
45}
46
47instrProfileParser.getInstrMap = function () {
48 return instrProfMap;
49}
50
51instrProfileParser.removeFilebasedKeyword = function(keywordName) {
52 delete keyWordModel[keywordName]
53}
54
55instrProfileParser.parseInstrProfile = function(data){
56 try {
57 var instrData = JSON.parse(data);
58
59 for (var i in instrData) {
60 instrProfMap[instrData[i].modulename] = instrData[i];
61 for (j in builtinCoreModules) {
62 if (instrData[i].modulename === builtinCoreModules[j]) {
63 delete instrProfMap[instrData[i].modulename];
64 coreInstrProfMap[instrData[i].modulename] = instrData[i];
65 }
66 }
67 }
68 }
69 catch(err){
70 util.logger.error(agentSetting.currentTestRun,'| Error in parseInstrProfile',err)
71 }
72}
73
74function checkFileBasedKeywordAndMakeConn(clientSocket,makeDataAutoConnection){
75 if(fileBasedKeyword.length && multiFileKeywordCount < fileBasedKeyword.length ) {
76 currKeyword = fileBasedKeyword[multiFileKeywordCount].keywordName
77 getFileContent(fileBasedKeyword[multiFileKeywordCount], clientSocket, currKeyword,makeDataAutoConnection)
78 }
79 else {
80 currKeyword = ""; // After all req send for all file,cleaning curr keyword name
81 multiFileKeywordCount = 0;
82 fileBasedKeyword = []; //Clearing Array of all keywords based file
83 if(!agentSetting.runTimeChange)
84 instrProfileParser.sendRespAndMakeConn(clientSocket,makeDataAutoConnection)
85 else if(agentSetting.runTimeChange){ //runtime change will be true, if it is applied but file is same then we have to handle that case
86 agentSetting.runTimeChange =false;
87 try {
88 if(clientSocket) {
89 clientSocket.write("nd_control_rep:action=modify;result=Ok;" + '\n');
90 util.logger.info(agentSetting.currentTestRun + " | nd_control_rep:action=modify;result=Ok;" + '\n');
91 }
92 }
93 catch(e){
94 util.logger.error(agentSetting.currentTestRun,'| Error in parseInstrProfile',err)
95 }
96 }
97 }
98}
99
100function getFileContent(allFields,clientSocket,keywordName,makeDataAutoConnection) {
101 var oldModel = keyWordModel[keywordName];
102 var fileContent = [];
103 var KeywithValue ;
104
105 try
106 {
107 KeywithValue = allFields.value && allFields.value.split("=");
108
109 var newFileName = new ndKeywordFileModelObj();
110
111 newFileName.ndKeywordFileModel(keywordName,KeywithValue[1]);
112
113 keyWordModel[newFileName.keywordName] = newFileName;
114 keyWordModel[newFileName.keywordName].settings = allFields;
115 instrProfileParser.compareAndGetFileContents(oldModel,newFileName,clientSocket,makeDataAutoConnection,keyWordModel[newFileName.keywordName]);
116
117 }
118 catch (err) {
119 util.logger.warn(err);
120 }
121}
122instrProfileParser.compareAndGetFileContents = function(oldModel,newModel, clientSocket,makeDataAutoConnection,allFields) {
123 try {
124 var isChanged = false;
125 if (!newModel) {
126 util.logger.info(agentSetting.currentTestRun, " | File Info is not present for ", newModel.keywordName, ",So requesting for next keyword");
127 multiFileKeywordCount++
128
129 checkFileBasedKeywordAndMakeConn(clientSocket, makeDataAutoConnection)
130 return;
131 }
132
133 if (oldModel) {
134 if ((newModel.lmd != oldModel.lmd) || (newModel.size != oldModel.size) || (newModel.fileName != oldModel.fileName)) {
135 isChanged = true;
136 util.logger.info(agentSetting.currentTestRun, " | File Missmatched : lmd prev :" + oldModel.lmd + " ,Size : " + oldModel.size + " ,Name : " + oldModel.fileName + "\n New file lmd : " + newModel.lmd + " ,Size : " + newModel.size + " ,Name : " + newModel.fileName);
137 }
138 else
139 isChanged = false;
140 }
141 else
142 isChanged = true;
143
144 if (isChanged) {
145 try {
146 // Sending message for retrieving new file.
147 if(newModel.keywordName == 'BTRuleConfig')
148 agentSetting.isdumpBtMetaData = true;
149 util.logger.info(agentSetting.currentTestRun, " | File is different ", isChanged, "Requesting for File", newModel.keywordName);
150 multiFileKeywordCount++
151 allFields.settings.isReqSent = true;
152 startTimer(allFields,clientSocket,makeDataAutoConnection)
153 clientSocket.write("nd_control_req:action=send_file;keyword=" + newModel.keywordName + ";" + '\n');
154 util.logger.info(agentSetting.currentTestRun + " | nd_control_req:action=send_file;keyword=" + newModel.keywordName + ";" + '\n');
155 }
156 catch (err) {
157 util.logger.warn(err);
158 }
159 }
160 else {
161 util.logger.info(agentSetting.currentTestRun, " | File is same for keyword", newModel.keywordName, ": lmd prev :" + oldModel.lmd + " ,Size : " + oldModel.size + " ,Name : " + oldModel.fileName + "\n New file lmd : " + newModel.lmd + " ,Size : " + newModel.size + " ,Name : " + newModel.fileName);
162 multiFileKeywordCount++
163 checkFileBasedKeywordAndMakeConn(clientSocket, makeDataAutoConnection)
164 }
165 }
166 catch(e){
167 agentSetting.runTimeChange=false
168 util.logger.info(agentSetting.currentTestRun + " | exception in compareAndGetFileContents",e);
169 }
170}
171
172instrProfileParser.readFileBasedKeywordContent = function (data,clientSocket,makeDataAutoConnection,comingKeyword) {
173 try {
174 if (comingKeyword && comingKeyword != currKeyword) {
175 util.logger.info(agentSetting.currentTestRun + " | Data is reading for keyword ",comingKeyword, " and current keyword was ",currKeyword);
176 connTimeout && clearTimeout(connTimeout);connTimeout = undefined;
177 data=''
178 if(keyWordModel[currKeyword] && keyWordModel[currKeyword].settings.isCritical) {
179 util.logger.info(agentSetting.currentTestRun + " | Request for Critical file ",currKeyword," but get the response of non -critical file",comingKeyword," So ignoring this and again requesting for critical file");
180 startTimer(keyWordModel[currKeyword], clientSocket, makeDataAutoConnection)
181 return;
182 }else{
183 delete keyWordModel[currKeyword]
184 checkFileBasedKeywordAndMakeConn(clientSocket,makeDataAutoConnection)
185 return ;
186 }
187 }
188 connTimeout && clearTimeout(connTimeout);connTimeout = undefined;
189 list= data.split('\n');
190 if (list.length) {
191 if (currKeyword == "ndMethodMonFile") {
192 util.logger.info(agentSetting.currentTestRun + " | Reading method monitor file");
193 ndMthMonitor.parseMethodMonitor(list);
194 }
195 else if (currKeyword == "ndExceptionMonFile") {
196 util.logger.info(agentSetting.currentTestRun + " | Reading ExceptionMon file");
197 ndExceptionMonitor.parseExceptionMonitoringList(list);
198 }
199 else if (currKeyword == "BTTConfig") {
200 util.logger.info(agentSetting.currentTestRun + " | Reading BTTConfig file");
201 btConfig.parseThresholdFile(list);
202 }
203 else if (currKeyword == "BTRuleConfig") {
204 util.logger.info(agentSetting.currentTestRun + " | Reading BTRuleConfig file");
205 btConfig.parseBTRuleConfigfile(list);
206 }
207 else if (currKeyword == "ndBackendNamingRulesFile") {
208 util.logger.info(agentSetting.currentTestRun + " | Reading ndBackendNamingRulesFile file");
209 backendRecord.parseBackendPointsNamingInfo(list);
210 }else if (currKeyword == "HTTPStatsCondCfg") {
211 util.logger.info(agentSetting.currentTestRun + " | Reading HTTPStatsCondCfg file");
212 NDHttpConditionStats.manageAllSpecifiedConditions(list);
213 }else if (currKeyword == "captureCustomData") {
214 util.logger.info(agentSetting.currentTestRun + " | Reading captureCustomData file");
215 NDSessionCaptureSettings.parseCustomData(list);
216 }else if (currKeyword == "NDEntryPointsFile") {
217 util.logger.info(agentSetting.currentTestRun + " | Reading NDEntryPointsFile file");
218 entryPonitManager.parseEntryPointFile(list);
219 instrProfileParser.checkAndInstrumentLoggerObject();
220 }
221
222 list = []
223
224 checkFileBasedKeywordAndMakeConn(clientSocket,makeDataAutoConnection)
225 }
226 }
227 catch (err) {
228 agentSetting.runTimeChange=false
229 util.logger.warn(err)
230 }
231}
232
233function startTimer(allFields,clientSocket,makeDataAutoConnection){
234 connTimeout=setTimeout(function () {
235 if(allFields.settings.isCritical){
236 util.logger.info(agentSetting.currentTestRun + " | Data is not coming of critical file - ",allFields.keywordName,", So breaking control connection.")
237 allFields.settings.isReqSent = false;
238 clientSocket.destroy();
239 delete clientSocket;
240 clientSocket = undefined;
241 NDConnectionManager.checkProtocolAndMakeConnection();
242 currKeyword = connTimeout = undefined;
243 delete keyWordModel[allFields.keywordName];
244 if(agentSetting.isdumpBtMetaData)
245 agentSetting.isdumpBtMetaData = false
246 return;
247 }else{
248 util.logger.info(agentSetting.currentTestRun + " | Data is not coming of file - ",allFields.keywordName);
249 connTimeout=undefined;
250 delete keyWordModel[allFields.keywordName]
251 checkFileBasedKeywordAndMakeConn(clientSocket,makeDataAutoConnection);
252 }
253 },60000);
254}
255
256function setFileMetaData(keywordName,metadata,isCritical){
257 return {
258 keywordName:keywordName,
259 value:metadata,
260 isCritical:isCritical,
261 isReqSent:false,
262 isResReceived:false
263 }
264}
265instrProfileParser.processInstrFileList = function (clientMsg,clientSocket,makeDataAutoConnection,isRunTimeChane) {
266
267 try {
268 instrProfileParser.resetInstrListOnStart()
269 var allFields = clientMsg;
270
271 var profilefield = [];
272 for (var i = 0; i < allFields.length; i++) {
273 if (allFields[i].toString().startsWith("InstrProfile=") || allFields[i].toString().indexOf("InstrProfile=/") != -1 || allFields[i].toString().startsWith("instrProfile=") || allFields[i].toString().indexOf("instrProfile=/") != -1) {
274 profilefield = allFields[i].toString().split("=")[1];
275 if(profilefield === '-' || profilefield.indexOf('.json') == -1) {
276 continue ;
277 }
278
279 instrumentationProfiles.push(profilefield);
280
281 util.logger.info(instrumentationProfiles)
282 }
283 else if (allFields[i].toString().startsWith("BTRuleConfig=")) {
284 keywordName = "BTRuleConfig";
285 if(allFields[i].toString().indexOf("BTRuleConfig=NA") != -1){
286 btGlobalRule.clearGlobalObj();
287 btConfig.isPatternBasedRulePresnt = false;
288 btManager.clear();
289 btRuleList.clearList();
290 btConfig.resetBtId();
291 instrProfileParser.removeFilebasedKeyword('BTRuleConfig')
292 continue ;
293 }
294 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],true))
295 }
296 else if (allFields[i].toString().startsWith("BTTConfig=")) {
297
298 if(allFields[i].toString().indexOf("BTTConfig=NA") != -1) {
299 btManager.clearthresholdmap();
300 instrProfileParser.removeFilebasedKeyword('BTTConfig')
301 continue;
302 }
303
304 keywordName = "BTTConfig";
305 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
306 }
307 else if (allFields[i].toString().startsWith("ndMethodMonFile=")) {
308 keywordName = "ndMethodMonFile";
309
310 if(allFields[i].toString().indexOf("ndMethodMonFile=NA") != -1) {
311 ndMthMonitor.clearMMList();
312 ndMthMonitor.clearMmMap();
313 instrProfileParser.removeFilebasedKeyword('ndMethodMonFile')
314 continue;
315 }
316 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
317 }
318 else if (allFields[i].toString().startsWith("ndExceptionMonFile=")) {
319 keywordName = "ndExceptionMonFile";
320
321 if(allFields[i].toString().indexOf("ndExceptionMonFile=NA") != -1) {
322
323 ndExceptionMonitor.clearExceptionMonList();
324 ndExceptionMonitor.clearExceptionMonMap();
325 instrProfileParser.removeFilebasedKeyword('ndExceptionMonFile')
326 continue;
327 }
328 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
329 }
330 else if(allFields[i].trim().startsWith('ndBackendNamingRulesFile') && (allFields[i].indexOf("ndBackendNamingRulesFile=NA") === -1)) {
331
332 keywordName = 'ndBackendNamingRulesFile';
333 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
334 }
335 else if(allFields[i].trim().startsWith("HTTPStatsCondCfg=") && (allFields[i].indexOf("HTTPStatsCondCfg=NA") === -1)){
336 keywordName = 'HTTPStatsCondCfg';
337 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
338 }
339 else if(allFields[i].trim().startsWith("captureCustomData=") && (allFields[i].indexOf("captureCustomData=NA") === -1)){
340 keywordName = 'captureCustomData';
341 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
342 }
343 else if(allFields[i].trim().startsWith("NDEntryPointsFile=") && (allFields[i].indexOf("NDEntryPointsFile=NA") === -1)) {
344 keywordName = 'NDEntryPointsFile';
345 fileBasedKeyword.push(setFileMetaData(keywordName,allFields[i],false))
346 }
347 }
348 /*To continue on error,invalid file sent by ndc,their is a timeout that will send start_instrumenattion message and
349 * create connection */
350
351 /*if(!agentSetting.runTimeChange && !connTimeout) {
352 connTimeout = setTimeout(function () {
353 util.logger.info(agentSetting.currentTestRun + " | Creating connection after timeout")
354 instrProfileParser.sendRespAndMakeConn(clientSocket, makeDataAutoConnection)
355 },agentSetting.startInstrResTimeout)
356 }*/
357 if(instrumentationProfiles.length) {
358 try {
359 if (clientSocket) {
360 clientSocket.write("nd_control_req:action=send_instrumentation_profile;status=200;instrProfile=" + instrumentationProfiles[0].toString() + "" + '\n');
361 util.logger.info(agentSetting.currentTestRun + " | nd_control_req:action=send_instrumentation_profile;status=200;instrProfile=" + instrumentationProfiles[0].toString() + "" + '\n');
362 }
363 } catch(err){
364 util.logger.error('Cant able to write on contol socket',err)
365 }
366 }
367 else if(!instrumentationProfiles.length && fileBasedKeyword.length && multiFileKeywordCount < fileBasedKeyword.length)
368 {
369 currKeyword = fileBasedKeyword[multiFileKeywordCount].keywordName
370 getFileContent(fileBasedKeyword[multiFileKeywordCount], clientSocket, currKeyword,makeDataAutoConnection)
371 }else{
372 if(agentSetting.runTimeChange){
373 try{
374 agentSetting.runTimeChange=false;
375 if (clientSocket) {
376 clientSocket.write("nd_control_rep:action=modify;result=Ok;" + '\n');
377 util.logger.info(agentSetting.currentTestRun + " | nd_control_rep:action=modify;result=Ok;" + '\n');
378 }
379 } catch(err){
380 agentSetting.runTimeChange=false;
381 util.logger.error('Cant able to write on contol socket',err)
382 }
383 }
384 else if(!agentSetting.runTimeChange)
385 instrProfileParser.sendRespAndMakeConn(clientSocket,makeDataAutoConnection)
386 }
387 }
388 catch(err){
389 agentSetting.runTimeChange=false
390 util.logger.warn(err)}
391}
392
393instrProfileParser.processInstrFile = function (list,clientSocket,makeDataAutoConnection) {
394
395 try {
396 if(list && list.length)
397 process.nextTick(function() {try { instrumentationProfileParser.parseRunTimeInstrumentationProfile(list) }catch(E){util.logger.error("Error in Run time instrumentaion",E)}})
398
399 if (instrumentationProfiles.length && multiInstrProfCount < instrumentationProfiles.length) {
400 try {
401 if (clientSocket) {
402 clientSocket.write("nd_control_req:action=send_instrumentation_profile;status=200;instrProfile=" + instrumentationProfiles[multiInstrProfCount].toString() + "" + '\n');
403 util.logger.info(agentSetting.currentTestRun + " | nd_control_req:action=send_instrumentation_profile;status=200;instrProfile=" + instrumentationProfiles[multiInstrProfCount].toString() + "" + '\n');
404 }
405 } catch(err){
406 util.logger.error('Cant able to write on contol socket',err)
407 }
408 multiInstrProfCount++;
409 }
410 else{
411 // All instrumentation has been received .Cleaning all values
412 instrumentationProfiles = []
413 multiInstrProfCount = 1;
414
415 checkFileBasedKeywordAndMakeConn(clientSocket,makeDataAutoConnection)
416 }
417 }
418 catch (err) {
419 agentSetting.runTimeChange=false
420 util.logger.warn(err)
421 }
422}
423
424instrProfileParser.sendRespAndMakeConn = function(clientSocket,makeDataAutoConnection){
425 if(agentSetting.isTestRunning &&!agentSetting.dataConnHandler && !agentSetting.autoSensorConnHandler){
426
427 util.logger.info(agentSetting.currentTestRun + " | Invoking Data , Auto connection and sending start_instr response")
428
429 if(!agentSetting.startInstrResponse) {
430 try {
431 if (clientSocket) {
432 clientSocket.write("nd_control_rep:action=start_instrumentation;status=" + agentSetting.status + ";result=Ok;" + '\n')
433 util.logger.info(agentSetting.currentTestRun + " | nd_control_rep:action=start_instrumentation;status=" + agentSetting.status + ";result=Ok;" + '\n')
434 }
435 }
436 catch(err){
437 util.logger.error('Cant able to write on contol socket',err)
438 }
439 agentSetting.startInstrResponse = true;
440 clearTimeout(connTimeout);connTimeout = undefined
441 makeDataAutoConnection();
442 }
443 agentSetting.isToInstrument = true;
444 }
445 else{
446 agentSetting.runTimeChange=false
447 clearTimeout(connTimeout);connTimeout = undefined
448 util.logger.warn(agentSetting.currentTestRun + " |Agent is already connected, So ignoring to avoid making of data and auto connections")
449 }
450}
451
452instrProfileParser.findModuleInInstrProfile = function(module){
453 if(module === ['http' || 'pg' || 'memcache' || 'redis' || 'mongodb'])
454 return false;
455
456 var moduleData = instrProfMap[module]
457 var coreData = coreInstrProfMap[module]
458
459 if((moduleData && moduleData.instrument == true) ||( coreData && coreData.instrument == true)) //(coreData.instrument == true || moduleData.instrument == true) ) {
460 {
461 util.logger.warn("Core module is to be instrumented : ",module)
462 return true;
463 }
464 else
465 return false;
466}
467instrProfileParser.checkAndInstrumentLoggerObject = function() {
468 if (agentSetting.enableUpdateLogMsgForNF) {
469 if (entryPonitManager.entryPointMap['CONSOLE'] && entryPonitManager.entryPointMap['CONSOLE'].enable == 1) {
470 var instrumentConsole = require('./nodetime/lib/probes/console');
471 agentSetting.mapForConsoleMeths = {};
472 var methArr = entryPonitManager.entryPointMap['CONSOLE'].method.split(",");
473 for (var i in methArr)
474 agentSetting.mapForConsoleMeths[methArr[i]] = true;
475 if (!console._isInstrumented) {
476 instrumentConsole.instrumentLoggerObj(console, methArr);
477 console._isInstrumented = true;
478 }
479 } else {
480 agentSetting.mapForConsoleMeths = {};
481 }
482 if (entryPonitManager.entryPointMap['WINSTON'] && entryPonitManager.entryPointMap['WINSTON'].enable == 1 && entryPonitManager.entryPointMap['WINSTON'].method) {
483 agentSetting.mapForWinstonLogMeths = {};
484 var methArr = entryPonitManager.entryPointMap['WINSTON'].method.split(",");
485 for (var i in methArr)
486 agentSetting.mapForWinstonLogMeths[methArr[i]] = true;
487 } else {
488 agentSetting.mapForWinstonLogMeths = {};
489 }
490 }
491}
492
493instrProfileParser.isValidExpectedFileMetaData = function(expectedFileMetaData,clientSocket,makeDataAutoConnection,callback){
494
495 try{
496 if(typeof expectedFileMetaData == 'object' ){
497
498 if(! (expectedFileMetaData.size > 0)) {
499 if(expectedFileMetaData.type == 'instrumentationProfile'){
500
501 instrumentationProfiles = []
502 multiInstrProfCount = 1;
503 checkFileBasedKeywordAndMakeConn(clientSocket,makeDataAutoConnection)
504
505 callback(false)
506 }
507 }else
508 callback(true);
509 }
510 }catch(e){
511 util.logger.error(agentSetting.currentTestRun,' | ')
512 }
513
514}
515
516module.exports = instrProfileParser;