UNPKG

17 kBJavaScriptView Raw
1/**
2 * Created by Sahil on 06-08-2015.
3 */
4
5var agentSetting = require("./agent-setting");
6var threadID = 10;
7var threadSeq = 10.1;
8var util = require('./util');
9var fs = require('fs');
10var path = require('path');
11var flowPathId = "" ;
12var fpid ="";
13var counter = 0 ;
14var flowpath = require('./flowpath/flowpath').Flowpath;
15var cookieParsing = require('./HttpHeader/Cookies');
16//var cookieParsing = require('cookies');
17var StringBuffer = require('./flowpath/StringBuffer').StringBuffer;
18var cavNdSessionDataModel = require('./HttpHeader/cavNdSessionDataModel');
19var big_integer = require('./utils/BigInteger');
20var btConfig = require('./BT/btConfig');
21var btManager = require('./BT/btManager');
22
23/******* Start for CavNV constants ********************/
24const NDNV_SESSION_ID_INDEX = 0,
25 NDNV_TEST_RUN_INDEX = 1,
26 NDNV_PREV_START_TIME_INDEX = 2,
27 NDNV_IS_INSTRUMENTED_SESSION_INDEX = 3,
28 NDNV_CATEGORY_INDEX = 4,
29 NDNV_EXCEPTION_COUNT_INDEX = 5,
30 NDNV_FP_COUNT_IN_SESSION_INDEX = 6;
31
32function flowpathhandler() {}
33
34function handleIncludedAndExcludedCase (context){
35 var curRandomNumber = 1 + parseInt(Math.random() * 100);
36 if (curRandomNumber <= agentSetting.bciInstrSessionPct) {
37 context.cavIncludeFp = true;
38 } else {
39 context.cavIncludeFp = false;
40 }
41}
42
43function setCookieInResp(cookie,req,res,cavNVCookie,isInstrumentedSession){
44 var cookieValueObj = {}; //passing object as third arguments for set.
45 cookieValueObj["path"]="/";
46 if(agentSetting.enableNDSession.cookieDomainName){
47 cookieValueObj["domain"]=agentSetting.enableNDSession.cookieDomainName;
48 }
49 cookie
50 .set(agentSetting.enableNDSession.fPIHeaderName , cavNVCookie, cookieValueObj);
51
52 if(agentSetting.enableNDSession.setHeaderInResponse){
53 var xHeaderValue = fpid +'_'+ agentSetting.currentTestRun +'_'+ '9' +'_'+ (isInstrumentedSession?1:0) ;
54 res.setHeader(agentSetting.enableNDSession.xHeaderName,xHeaderValue)
55 }
56}
57
58function checkFlowpathToIncludeOrExclude(cavNVCookie,context,isInstrumentedSession,isSessionExpired){
59 if ('100' == agentSetting.bciInstrSessionPct) {
60 context.cavIncludeFp = true;
61 } else if ((0 < agentSetting.bciInstrSessionPct) && (100 > agentSetting.bciInstrSessionPct)){
62 if(isInstrumentedSession){
63 if(!isSessionExpired)
64 context.cavIncludeFp = true;
65 else
66 handleIncludedAndExcludedCase(context) //Session is expired, check to include or exclude fp
67 }else{
68 if(!cavNVCookie)
69 handleIncludedAndExcludedCase(context) //1. either session instrumented information is not recieved from cavnv cookie because cookie is null
70 else
71 context.cavIncludeFp = false; //2. cookie is recieved and session is marked as not instrumented. exclude these flowpaths
72 }
73 }
74 else{
75 context.cavIncludeFp = false;
76 }
77}
78
79flowpathhandler.clearCounter =function(){counter=0;};
80
81flowpathhandler.ceateFpId = function()
82{
83 try {
84 var currTimeStamp = new Date().getTime() - (agentSetting.cavEpochDiffInMills);
85
86 var current = counter;
87 if (current == counter) {
88 counter = counter + 1;
89 }
90 // Creating FlowPath_ID
91 // ((flowPathInstanceInitialID + ((currTimeStamp & timeStampMask) << seqNoDigits ) + ((p.data) & seqNumMask)) + '');
92
93 var mask_counter = (big_integer(big_integer(big_integer(currTimeStamp).and(agentSetting.timeStampMask)).shiftLeft(agentSetting.seqNoDigits)).add(big_integer(counter).and(agentSetting.seqNumMask.toString()))).toString()
94 fpid = (big_integer(agentSetting.flowPathInstanceInitialID.toString()).add(mask_counter)).toString();
95
96 }catch(err){util.logger.warn(err)}
97}
98
99flowpathhandler.handleFlowPath = function(req,res,context) {
100 if(!agentSetting.isToInstrument)return;
101 //var header = req.headers['accept'];
102 if (req.hasOwnProperty('url') /*&& (header.indexOf('text/html') > -1 || header.indexOf("*!/!*") > -1)*/ ) {
103 var url = req['url'];
104 var ext = req['url'].split(".").pop(); //it will give the last value after splitting <Extension of url file>
105
106 if(ext == 'css' || ext == 'png' || ext == 'js' ||ext == 'jpeg' ||ext == 'ico'||ext == 'svg') {
107 return;
108 }
109 /*if(url.indexOf('.css') != -1 || url.indexOf('.png') != -1 || url.indexOf('.js') != -1 ||url.indexOf('.jpeg') != -1 ||url.indexOf('.ico') != -1 ||url.indexOf('.svg') != -1)
110 return ;*/
111 var Flowpath = new flowpath();
112 var nsFlowpathInstanceID = req.headers['cavndfpinstance']; //Getting FPID from request i.e parent generated FPID.
113
114 /*var correlationIDHeader = req.headers && (req.headers[agentSetting.correlationIDHeader.toLowerCase()] ||
115 req.headers[agentSetting.correlationIDHeader]);*/
116
117 flowpathhandler.ceateFpId(); //Creating FPID
118 if(!fpid){
119 util.logger.error(agentSetting.currentTestRun, "| Unable to generate fp id.")
120 return;
121 }
122 context.cavTimeInMillis = Flowpath.timeInMillis = (new Date().getTime()) - agentSetting.cavEpochDiffInMills;
123
124 /* if(correlationIDHeader) {
125 var sb = new StringBuffer();
126 sb.clear();
127 Flowpath.correlationIDHeader = agentSetting.encodeURI(sb,correlationIDHeader).toString()
128 sb.clear();
129 }*/
130 agentSetting.checkforCorrelationIdInReqRes(req, Flowpath);
131 var NVSid = undefined,cookies = null,NVPid = undefined,cavNVCookie = null,nvCokkie= null,ndSessionId =0,
132 prevFPStartTime = Number.max_value,isInstrumentedSession = false,
133 idleTime,totalFPCountInSession = 0,isSessionExpired= false;
134 var cookie = new cookieParsing(req,res)
135 if(agentSetting.enableNDSession.enableFPHdrInRep) {
136 cavNVCookie = cookie.get(agentSetting.enableNDSession.fPIHeaderName)
137 NVSid = cookie.get(agentSetting.enableNDSession.NVSid)
138 NVPid = cookie.get(agentSetting.enableNDSession.NVPid)
139 nvCokkie = cookie.get(agentSetting.enableNDSession.NVCookie)
140 if(nvCokkie){
141 var temp = nvCokkie.toString().split('-')
142 if(temp.length >= 2) {
143 NVSid = temp[0];
144 NVPid = temp[1];
145 }
146 }
147 }
148 if(!cavNVCookie) {
149 ndSessionId = fpid;
150 totalFPCountInSession = 0;
151 cavNdSessionDataModel.NDSessionFPCount = totalFPCountInSession + 1;
152 }
153 else{
154 if(agentSetting.enableBciDebug > 3)
155 util.logger.info(agentSetting.currentTestRun + ' | Fetching cookie from the Request Header for Url : ',url,' ,FPID : ',fpid ,' With Value : ',cavNVCookie)
156 if(cavNVCookie.indexOf(",") !== -1) {
157 //if(bciTraceLevel > 1)
158 // NDListener.logBCIError(Server.TestRunIDValue, "NDSys", "handleNewFlowpathNonNs", "Invalid format for cavNVCookie - " + cavNVCookie);
159 ndSessionId = fpid;
160 cavNdSessionDataModel.NDSessionFPCount = totalFPCountInSession + 1;
161 }
162 else {
163 var tmpStr = cavNVCookie.split("-");
164 ndSessionId = (tmpStr[NDNV_SESSION_ID_INDEX]?tmpStr[NDNV_SESSION_ID_INDEX].trim():fpid);
165 //if session id is received as blank then create new session id. need to handle blank cases for static page without flowpaths
166 ndSessionId = ("" === (ndSessionId.trim()) ? fpid : ndSessionId);
167 prevFPStartTime = parseInt(tmpStr[NDNV_PREV_START_TIME_INDEX]?tmpStr[NDNV_PREV_START_TIME_INDEX].trim():0);
168 isInstrumentedSession = (tmpStr[NDNV_IS_INSTRUMENTED_SESSION_INDEX]?tmpStr[NDNV_IS_INSTRUMENTED_SESSION_INDEX].trim():"1");
169
170 idleTime = (new Date().getTime() - agentSetting.cavEpochDiffInMills) - prevFPStartTime;
171 totalFPCountInSession = parseInt(tmpStr[NDNV_FP_COUNT_IN_SESSION_INDEX]?tmpStr[NDNV_FP_COUNT_IN_SESSION_INDEX].trim():0);
172 if(idleTime > agentSetting.enableNDSession.ndSessionIdleTimeOutSecs && agentSetting.enableNDSession.ndSessionIdleTimeOutSecs != 0 ||
173 (totalFPCountInSession >= agentSetting.enableNDSession.maxFPCountInSession && 0 != agentSetting.enableNDSession.maxFPCountInSession)) {
174 ndSessionId = fpid;
175 isSessionExpired = true;
176 totalFPCountInSession = 0;
177 cavNVCookie = null;
178 }
179 cavNdSessionDataModel.NDSessionFPCount = totalFPCountInSession + 1;
180 }
181 }
182 checkFlowpathToIncludeOrExclude(cavNVCookie,context,isInstrumentedSession,isSessionExpired)
183 flowpathhandler.checkIsNSGeneratedFP(nsFlowpathInstanceID,Flowpath, context)
184 flowpathhandler.checkForForcedFpChain(context,Flowpath)
185 isInstrumentedSession = context.cavIncludeFp
186 Flowpath.ndSessionId = ndSessionId
187 Flowpath.NVSid = NVSid; //set these values in flowpath Object.
188 Flowpath.NVPid = NVPid;
189 Flowpath.cavNVCookie = cavNVCookie = cavNdSessionDataModel.encode(ndSessionId,Flowpath.timeInMillis,isInstrumentedSession,agentSetting.currentTestRun)
190 if(agentSetting.enableBciDebug > 3)
191 util.logger.info(agentSetting.currentTestRun + ' | Setting Cookie in Respose Header For Url : ', url , '& FPID : ',fpid ,' with Value : ',cavNVCookie)
192 if(agentSetting.enableNDSession.methodEntryDepth2SetCookie)
193 setCookieInResp(cookie,req,res,cavNVCookie,isInstrumentedSession)
194
195 var btObj = btConfig.executeBTRule(req); //Generating BTObj for every Req i.e {btid : 1, btName: Index ,threshold :{slow:3000, vSlow : 5000}}
196 if(!btObj)
197 return;
198
199 if(!context)return ;
200 context.cavBtObj = btObj;
201
202 var bt_Data = btManager.getBTData(btObj.btId); //Lookup in BtMonitorMap if it is undefined , then creating it i.e {btId : btDetails}
203
204 /*
205 * 1. Checking current request is to be include or exclude , If a Bt reached to its threshold (bciInstrPct) ,
206 * then on basis of dumping percentage we changed btValue from include to exclude or exclude to include .
207 * 2. If some BT is becoming slow or very slow , then we changed its value from exclude to include , and this check
208 * is in continuation local storage .
209 * 3. We check dumping percentage on basis of total coming request to total dumped request .
210 * */
211 if(!cavNVCookie) {
212 if (!bt_Data) {
213 //These cahnges done regarding dynamic slow/vslow threshold for particular BT
214 btManager.createAndUpdateBTRecord(btObj.btId, btObj.btName, undefined, "", "", btObj.threshold.dynamicSlowThresoldPct, btObj.threshold.dynamicVSlowThresoldPct);//If BT object is not created and create it at once
215 bt_Data = btManager.getBTData(btObj.btId);
216 bt_Data.updateTotalAndAvgDumpReq();//This function used for calculate total dump requests
217
218 if (bt_Data.isDumpPctLessThanBCIPct(agentSetting.bciInstrSessionPct)) {
219 context.cavIncludeFp = true;
220 bt_Data.updateTotDumpReq();
221 }
222 else
223 context.cavIncludeFp = false;
224 }
225 else {
226 bt_Data.updateTotalAndAvgDumpReq();
227 if (bt_Data.isDumpPctLessThanBCIPct(agentSetting.bciInstrSessionPct)) {
228 context.cavIncludeFp = true;
229 bt_Data.updateTotDumpReq();
230 }
231 else
232 context.cavIncludeFp = false;
233 }
234 }
235
236 if(agentSetting.enableBciDebug>4)
237 util.logger.info(agentSetting.currentTestRun ,"| Dumping Request header for " , url , ",FPID :",fpid ,':', req.headers)
238
239 var localFlowPathId = flowPathId.toString();
240 /*
241 * Setting Current FPID, flowpathIdForHotSpot, FP_start_time (timeInMillis), in current Request.
242 * */
243
244 context.cavFlowPathId= Flowpath.flowPathId = localFlowPathId;
245 Flowpath.cavCurrReqFPID = context.cavCurrReqFPID = fpid;
246 context.cavHsFlowPathId = fpid;
247 context.seqId = 0; //Initializing Sequence id
248 context.fpTimeWithoutCavepoch = Flowpath.fpTimeWithoutCavepoch = Flowpath.timeInMillis + agentSetting.cavEpochDiffInMills;
249 Flowpath.timeStamp = parseInt(Flowpath.timeInMillis / 1000);
250
251 agentSetting.flowMap[localFlowPathId] = Flowpath ;
252 threadID = process.pid;
253
254 if(agentSetting.flowMap[localFlowPathId].seqPfx != undefined)
255 Flowpath.threadSeq = agentSetting.flowMap[localFlowPathId].seqPfx + ".1";
256 else
257 Flowpath.threadSeq = threadID + ".1";
258
259 var sb = new StringBuffer();
260 sb.clear();
261 Flowpath.threadID = threadID ;
262 Flowpath.id = btObj.btId ;
263 var encodedUri = agentSetting.encodeURI(sb,url).toString()
264 Flowpath.url = encodedUri ;
265 }
266}
267
268flowpathhandler.checkIsNSGeneratedFP = function(nsFlowpathInstanceID,Flowpath,context){
269 /*
270 * Checking for NS genertated FPID
271 * */
272 if(nsFlowpathInstanceID)
273 {
274 //In case of enbaleCaptureNetworkDelay feature true, removing the time stamp
275 if(nsFlowpathInstanceID.indexOf("#") > -1){
276 nsFlowpathInstanceID = nsFlowpathInstanceID.split('#')[0]
277 }
278
279 if(nsFlowpathInstanceID){
280 if(nsFlowpathInstanceID.indexOf("_") == -1) {
281 if(nsFlowpathInstanceID == "F" || nsFlowpathInstanceID == "f"){
282 Flowpath.tlFirstTierFPID = fpid+nsFlowpathInstanceID;
283 flowPathId = fpid;
284 context.cavIncludeFp = true;
285 }else{
286 Flowpath.tlFirstTierFPID = flowPathId = nsFlowpathInstanceID;
287 }
288 if (Flowpath.seqPfx == undefined)
289 Flowpath.seqPfx = Math.floor(Math.random()*(999-1+1)+1);
290 }
291 else {
292 var fp_values = nsFlowpathInstanceID.split("_");
293 // there are 2 cases:
294 // 1. if isNewTierCallOutFormat
295 // 1.1 if tlFirstTierFPID is null : 4893734774158527269_100.10.51
296 // 1.2 if tlFirstTierFPID not null: 4893734774157037605_4893734774158527269_100.10.51
297 // 2. if not isNewTierCallOutFormat: 4893734774158527269_100.10.51
298
299 var seqPfx = "";
300 var tlFirstTierFPID = "";
301 if(fp_values.length > 2) {
302 seqPfx = fp_values[2];
303 flowPathId = fpid + ":" + fp_values[0] + ":" + fp_values[1] ; // format: <currentFPID>:<firstTierFPID>:<parentTierFPID>
304
305 }
306 else {
307 seqPfx = fp_values[1];
308 flowPathId = fpid + ":" + fp_values[0] ; // format: <currentFPID>:<parentTierFPID>
309 }
310 tlFirstTierFPID = fp_values[0];
311
312 // if (Flowpath.seqPfx == undefined && Flowpath.tlFirstTierFPID == undefined ) {
313 if(seqPfx)
314 Flowpath.seqPfx = seqPfx;
315 else
316 Flowpath.seqPfx = Math.floor(Math.random()*(9007199254-1+1)+1);
317
318 if(tlFirstTierFPID)
319 Flowpath.tlFirstTierFPID = tlFirstTierFPID;
320 else
321 Flowpath.tlFirstTierFPID = fpid;
322 // }
323 }
324 }
325 else{
326 flowpathhandler.noChainedFpFound(Flowpath);
327 util.logger.error(agentSetting.currentTestRun, "| No value is received from cavndfpinstance header.")
328 }
329 }
330 else{
331 flowpathhandler.noChainedFpFound(Flowpath);
332 }
333
334}
335flowpathhandler.noChainedFpFound = function(Flowpath){
336 Flowpath.tlFirstTierFPID = flowPathId = fpid.toString() ;
337 if(Flowpath.seqPfx == undefined) {
338 Flowpath.seqPfx = Math.floor(Math.random() * (19999 - 1 + 1) + 1); //Generating random no. (In BCI generating ThreadID)
339 }
340}
341flowpathhandler.checkForForcedFpChain = function(context,Flowpath){
342 if(Flowpath.tlFirstTierFPID.indexOf('F') !== -1){
343 context.cavIncludeFp = true;
344 }
345 else if(Flowpath.tlFirstTierFPID.indexOf('f') !== -1 ){
346 if(!context.cavIncludeFp)Flowpath.dumpForcefullL1FP = true;
347 }
348 else{
349 if(context.cavIncludeFp == true)
350 agentSetting.enableForcedFPChain > 1 ? Flowpath.tlFirstTierFPID += 'F' : (agentSetting.enableForcedFPChain == 1 ? Flowpath.tlFirstTierFPID += 'f' : Flowpath.tlFirstTierFPID += '');
351 }
352}
353
354module.exports = flowpathhandler;