All files / lib swsProcessor.js

88.18% Statements 194/220
53.4% Branches 55/103
92.31% Functions 12/13
90.82% Lines 188/207

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464              1x 1x   1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x               1x     1x           1x     1x     1x     1x     1x     1x     1x     1x     1x     1x     1x     1x     1x     1x     1x       1x   1x   1x   1x   1x   1x   1x     1x                 1x 1x 1x 1x 1x 1x         3x 3x 3x 3x 3x 3x 3x             16x   16x   16x                                                   16x 16x 16x 52x           16x 16x 16x         16x   16x 16x 16x   16x   16x 16x 16x 16x 16x 16x     16x 16x 16x 16x 16x 16x 16x     16x 16x 12x                 16x 16x 16x     16x 16x 16x     16x 16x 16x     16x       32x 32x 32x   32x       16x 16x 16x   16x       16x 16x 16x       16x 16x   16x         16x         16x 16x 16x                                     16x     16x   16x 16x 4x     16x 16x 16x 16x 16x 16x 16x 16x 16x     16x     16x           16x     16x     16x         16x   16x   16x 16x 16x     16x 16x     16x   16x 16x       16x                 16x         16x     16x     16x     16x     16x     16x     16x     16x 16x       16x                 9x 9x   9x     9x 9x     9x 9x         9x     9x 9x 9x     9x 9x 9x 9x 9x   9x 9x 10x 10x           9x 9x 9x 9x 9x 9x 9x   9x 8x 8x       9x         1x 1x  
/**
 * Created by sv2 on 2/18/17.
 * swagger-stats Processor. Processes requests / responses and maintains metrics
 */
 
'use strict';
 
const os = require('os');
const util = require('util');
 
const debug = require('debug')('sws:processor');
const debugrrr = require('debug')('sws:rrr');
 
const swsSettings = require('./swssettings');
const swsUtil = require('./swsUtil');
const pathToRegexp = require('path-to-regexp');
const moment = require('moment');
 
const swsReqResStats = require('./swsReqResStats');
const SwsSysStats = require('./swssysstats');
const SwsCoreStats = require('./swsCoreStats');
const swsErrors = require('./swsErrors');
const swsTimeline = require('./swsTimeline');
const swsAPIStats = require('./swsAPIStats');
const swsLastErrors = require('./swsLastErrors');
const swsLongestRequests = require('./swsLongestReq');
const swsElasticsearchEmitter = require('./swsElasticEmitter');
 
// swagger-stats Processor. Processes requests / responses and maintains metrics
class SwsProcessor {
 
    constructor() {
 
        // Timestamp when collecting statistics started
        this.startts = Date.now();
 
        // Name: Should be name of the service provided by this component
        this.name = 'sws';
 
        // Options
        //this.options = null;
 
        // Version of this component
        this.version = '';
 
        // This node hostname
        this.nodehostname = '';
 
        // Node name: there could be multiple nodes in this service
        this.nodename = '';
 
        // Node address: there could be multiple nodes in this service
        this.nodeaddress = '';
 
        // onResponseFinish callback, if specified in options
        this.onResponseFinish = null;
 
        // If set to true via options, track only API defined in swagger spec
        this.swaggerOnly = false;
 
        // System statistics
        this.sysStats = new SwsSysStats();
 
        // Core statistics
        this.coreStats = new SwsCoreStats();
 
        // Core Egress statistics
        this.coreEgressStats = new SwsCoreStats();
 
        // Timeline
        this.timeline = new swsTimeline();
 
        // API Stats
        this.apiStats = new swsAPIStats();
 
        // Errors
        this.errorsStats = new swsErrors();
 
        // Last Errors
        this.lastErrors = new swsLastErrors();
 
        // Longest Requests
        this.longestRequests = new swsLongestRequests();
 
        // ElasticSearch Emitter
        this.elasticsearchEmitter = new swsElasticsearchEmitter();
    }
 
    init() {
        this.processOptions();
 
        this.sysStats.initialize();
 
        this.coreStats.initialize();
 
        this.coreEgressStats.initialize('egress_');
 
        this.timeline.initialize(swsSettings);
 
        this.apiStats.initialize(swsSettings);
 
        this.elasticsearchEmitter.initialize(swsSettings);
 
        // Start tick
        this.timer = setInterval(this.tick, 200, this);
    }
 
    // Stop
    stop() {
        clearInterval(this.timer);
    }
 
    processOptions() {
        this.name = swsSettings.name;
        this.hostname = swsSettings.hostname;
        this.version = swsSettings.version;
        this.ip = swsSettings.ip;
        this.onResponseFinish = swsSettings.onResponseFinish;
        this.swaggerOnly = swsSettings.swaggerOnly;
    };
 
    // Tick - called with specified interval to refresh timelines
    tick(that) {
        let ts = Date.now();
        let totalElapsedSec = (ts - that.startts)/1000;
        that.sysStats.tick(ts,totalElapsedSec);
        that.coreStats.tick(ts,totalElapsedSec);
        that.timeline.tick(ts,totalElapsedSec);
        that.apiStats.tick(ts,totalElapsedSec);
        that.elasticsearchEmitter.tick(ts,totalElapsedSec);
    };
 
    // Collect all data for request/response pair
    // TODO Support option to add arbitrary extra properties to sws request/response record
    collectRequestResponseData(res) {
 
        var req = res._swsReq;
 
        var codeclass = swsUtil.getStatusCodeClass(res.statusCode);
 
        var rrr = {
            'path': req.sws.originalUrl,
            'method': req.method,
            'query' : req.method + ' ' + req.sws.originalUrl,
            'startts': 0,
            'endts': 0,
            'responsetime': 0,
            "node": {
                "name": this.name,
                "version": this.version,
                "hostname": this.hostname,
                "ip": this.ip
            },
            "http": {
                "request": {
                    "url" : req.url
                },
                "response": {
                    'code': res.statusCode,
                    'class': codeclass,
                    'phrase': res.statusMessage
                }
            }
        };
 
        // Request Headers
        Eif ("headers" in req) {
            rrr.http.request.headers = {};
            for(var hdr in req.headers){
                rrr.http.request.headers[hdr] = req.headers[hdr];
            }
            // TODO Split Cookies
        }
 
        // Response Headers
        var responseHeaders = res.getHeaders();
        Eif (responseHeaders){
            rrr.http.response.headers = responseHeaders;
        }
 
        // Additional details from collected info per request / response pair
 
        Eif ("sws" in req) {
 
            rrr.ip = req.sws.ip;
            rrr.real_ip = req.sws.real_ip;
            rrr.port = req.sws.port;
 
            rrr["@timestamp"] = moment(req.sws.startts).toISOString();
            //rrr.end = moment(req.sws.endts).toISOString();
            rrr.startts = req.sws.startts;
            rrr.endts = req.sws.endts;
            rrr.responsetime = req.sws.duration;
            rrr.http.request.clength = req.sws.req_clength;
            rrr.http.response.clength = req.sws.res_clength;
            rrr.http.request.route_path = req.sws.route_path;
 
            // Add detailed swagger API info
            rrr.api = {};
            rrr.api.path = req.sws.api_path;
            rrr.api.query = req.method + ' ' + req.sws.api_path;
            Eif( 'swagger' in req.sws ) rrr.api.swagger = req.sws.swagger;
            Eif( 'deprecated' in req.sws ) rrr.api.deprecated = req.sws.deprecated;
            Eif( 'operationId' in req.sws ) rrr.api.operationId = req.sws.operationId;
            Iif( 'tags' in req.sws ) rrr.api.tags = req.sws.tags;
 
            // Get API parameter values per definition in swagger spec
            var apiParams = this.apiStats.getApiOpParameterValues(req.sws.api_path,req.method,req,res);
            if(apiParams!==null){
                rrr.api.params = apiParams;
            }
 
            // TODO Support Arbitrary extra properties added to request under sws
            // So app can add any custom data to request, and it will be emitted in record
 
        }
 
        // Express/Koa parameters: req.params (router) and req.body (body parser)
        Eif (req.hasOwnProperty("params")) {
            rrr.http.request.params = {};
            swsUtil.swsStringRecursive(rrr.http.request.params, req.params);
        }
 
        Eif (req.sws && req.sws.hasOwnProperty("query")) {
            rrr.http.request.query = {};
            swsUtil.swsStringRecursive(rrr.http.request.query, req.sws.query);
        }
 
        Eif (req.hasOwnProperty("body")) {
            rrr.http.request.body = Object.assign({}, req.body);
            swsUtil.swsStringRecursive(rrr.http.request.body, req.body);
        }
 
        return rrr;
    };
 
    getRemoteIP(req ) {
        let ip = '';
        try {
            ip = req.connection.remoteAddress;
        }catch(e){}
        return ip;
    };
 
    getPort(req ) {
        let p = 0;
        try{
            p = req.connection.localPort;
        }catch(e){}
        return p;
    };
 
    getRemoteRealIP(req ) {
        var remoteaddress = null;
        var xfwd = req.headers['x-forwarded-for'];
        Iif (xfwd) {
            var fwdaddrs = xfwd.split(','); // Could be "client IP, proxy 1 IP, proxy 2 IP"
            remoteaddress = fwdaddrs[0];
        }
        Eif (!remoteaddress) {
            remoteaddress = this.getRemoteIP(req);
        }
        return remoteaddress;
    };
 
    getResponseContentLength(req, res){
 
        Iif ("contentLength" in res && res['_contentLength'] !== null ){
            return res['_contentLength'];
        }
 
        // Try to get header
        let hcl = res.getHeader('content-length');
        Eif( (hcl !== undefined) && hcl && !isNaN(hcl)) {
            return parseInt(hcl);
        }
 
        // If this does not work, calculate using bytesWritten
        // taking into account res._header
        let initial = req.sws.initialBytesWritten || 0;
        let written = req.socket.bytesWritten - initial;
        if('_header' in res){
            const hbuf = Buffer.from(res['_header']);
            let hslen = hbuf.length;
            written -= hslen;
        }
        return written;
    }
 
 
    processRequest(req, res) {
 
        // Placeholder for sws-specific attributes
        req.sws = req.sws || {};
 
        // Setup sws props and pass to stats processors
        var ts = Date.now();
 
        var reqContentLength = 0;
        if('content-length' in req.headers) {
            reqContentLength = parseInt(req.headers['content-length']);
        }
 
        req.sws.originalUrl = req.originalUrl || req.url;
        req.sws.track = true;
        req.sws.startts = ts;
        req.sws.timelineid = Math.floor( ts/ this.timeline.settings.bucket_duration );
        req.sws.req_clength = reqContentLength;
        req.sws.ip = this.getRemoteIP(req);
        req.sws.real_ip = this.getRemoteRealIP(req);
        req.sws.port = this.getPort(req);
        req.sws.initialBytesWritten = req.socket.bytesWritten;
 
        // Try to match to API right away
        this.apiStats.matchRequest(req);
 
        // if no match, and tracking of non-swagger requests is disabled, return
        Iif( !req.sws.match && this.swaggerOnly){
            req.sws.track = false;
            return;
        }
 
        // Core stats
        this.coreStats.countRequest(req, res);
 
        // Timeline
        this.timeline.countRequest(req, res);
 
        // TODO Check if needed
        this.apiStats.countRequest(req, res);
    };
 
    processResponse(res) {
 
        let req = res._swsReq;
 
        req.sws = req.sws || {};
 
        let startts = req.sws.startts || 0;
        req.sws.endts = Date.now();
        req.sws.duration = req.sws.endts - startts;
        //let timelineid = req.sws.timelineid || 0;
 
        Eif("inflightTimer" in req.sws) {
            clearTimeout(req.sws.inflightTimer);
        }
 
        req.sws.res_clength = this.getResponseContentLength(req,res);
 
        var route_path = '';
        Iif( 'route_path' in req.sws ){
            // Route path could be pre-set in sws by previous handlers/hooks ( Fastify )
            route_path = req.sws.route_path;
        }
        Iif (("route" in req) && ("path" in req.route)) {
            // Capture route path for the request, if set by router (Express)
            if (("baseUrl" in req) && (req.baseUrl != undefined)) route_path = req.baseUrl;
            route_path += req.route.path;
            req.sws.route_path = route_path;
        }
 
        // If request was not matched to Swagger API, set API path:
        // Use route_path, if exist; if not, use sws.originalUrl
        Iif(!('api_path' in req.sws)){
            req.sws.api_path = (route_path!=''?route_path:req.sws.originalUrl);
        }
 
        // Pass through Core Statistics
        this.coreStats.countResponse(res);
 
        // Pass through Timeline
        this.timeline.countResponse(res);
 
        // Pass through API Statistics
        this.apiStats.countResponse(res);
 
        // Pass through Errors
        this.errorsStats.countResponse(res);
 
        // Collect request / response record
        var rrr = this.collectRequestResponseData(res);
 
        // Pass through last errors
        this.lastErrors.processReqResData(rrr);
 
        // Pass through longest request
        this.longestRequests.processReqResData(rrr);
 
        // Pass to app if callback is specified
        Eif(this.onResponseFinish !== null ){
            this.onResponseFinish(req,res,rrr);
        }
 
        // Push Request/Response Data to Emitter(s)
        this.elasticsearchEmitter.processRecord(rrr);
 
        //debugrrr('%s', JSON.stringify(rrr));
    };
 
 
    // Get stats according to fields and params specified in query
    getStats( query ) {
 
        query = typeof query !== 'undefined' ? query: {};
        query = query !== null ? query: {};
 
        var statfields = [];    // Default
 
        // Check if we have query parameter "fields"
        Eif ('fields' in query) {
            Iif (query.fields instanceof Array) {
                statfields = query.fields;
            } else {
                var fieldsstr = query.fields;
                statfields = fieldsstr.split(',');
            }
        }
 
        // sys, ingress and egress core statistics are returned always
        let result = {
            startts: this.startts
        };
        result.all = this.coreStats.getStats();
        result.egress = this.coreEgressStats.getStats();
        result.sys = this.sysStats.getStats();
 
        // add standard properties, returned always
        result.name = this.name;
        result.version = this.version;
        result.hostname = this.hostname;
        result.ip = this.ip;
        result.apdexThreshold = swsSettings.apdexThreshold;
 
        var fieldMask = 0;
        for(var i=0;i<statfields.length;i++){
            var fld = statfields[i];
            Eif( fld in swsUtil.swsStatFields ) fieldMask |= swsUtil.swsStatFields[fld];
        }
 
        //console.log('Field mask:' + fieldMask.toString(2) );
 
        // Populate per mask
        Iif( fieldMask & swsUtil.swsStatFields.method )  result.method = this.coreStats.getMethodStats();
        Iif( fieldMask & swsUtil.swsStatFields.timeline )  result.timeline = this.timeline.getStats();
        Iif( fieldMask & swsUtil.swsStatFields.lasterrors )  result.lasterrors = this.lastErrors.getStats();
        Iif( fieldMask & swsUtil.swsStatFields.longestreq )  result.longestreq = this.longestRequests.getStats();
        if( fieldMask & swsUtil.swsStatFields.apidefs )  result.apidefs = this.apiStats.getAPIDefs();
        if( fieldMask & swsUtil.swsStatFields.apistats )  result.apistats = this.apiStats.getAPIStats();
        Iif( fieldMask & swsUtil.swsStatFields.errors )  result.errors = this.errorsStats.getStats();
 
        if( fieldMask & swsUtil.swsStatFields.apiop ) {
            Eif(("path" in query) && ("method" in query)) {
                result.apiop = this.apiStats.getAPIOperationStats(query.path, query.method);
            }
        }
 
        return result;
    };
 
}
 
let swsProcessor = new SwsProcessor();
module.exports = swsProcessor;