All files / lib swsElasticEmitter.js

74.77% Statements 80/107
49.15% Branches 29/59
100% Functions 10/10
76.19% Lines 80/105

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            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       1x   1x 1x                 1x 1x 1x                       1x     26x 3x             1x       16x             16x                     1x   16x       16x     16x 16x     16x 16x   16x   16x         1x   3x       3x   3x               3x             3x 3x     3x         3x 3x       1x    
/**
 * ElasticSearch Emitter. Store Request/Response records in Elasticsearch
 */
 
'use strict';
 
var os = require('os');
var util = require('util');
var http = require('http');
var url = require('url');
var request = require('request');
 
var debug = require('debug')('sws:elastic');
var swsUtil = require('./swsUtil');
var moment = require('moment');
 
var indexTemplate = require('../schema/elasticsearch/api_index_template.json');
 
 
const ES_MAX_BUFF = 50;
 
// ElasticSearch Emitter. Store Request/Response records in Elasticsearch
function swsElasticEmitter() {
 
    // Options
    this.options = null;
 
    this.indexBuffer = '';
    this.bufferCount = 0;
    this.lastFlush = 0;
 
    this.elasticURL = null;
    this.elasticURLBulk = null;
    this.elasticProto = null;
    this.elasticHostname = null;
    this.elasticPort = null;
 
    this.elasticUsername = null;
    this.elasticPassword = null;
 
    this.indexPrefix = "api-";
 
    this.enabled = false;
}
 
// Initialize
swsElasticEmitter.prototype.initialize = function (swsOptions) {
 
    Iif(typeof swsOptions === 'undefined') return;
    Iif(!swsOptions) return;
 
    this.options = swsOptions;
 
    // Set or detect hostname
    Iif(!(swsUtil.supportedOptions.elasticsearch in swsOptions)) {
        debug('Elasticsearch is disabled');
        return;
    }
 
    this.elasticURL = swsOptions[swsUtil.supportedOptions.elasticsearch];
 
    Iif (!this.elasticURL) {
        debug('Elasticsearch url is invalid');
        return;
    }
 
    this.elasticURLBulk = this.elasticURL +'/_bulk';
 
    Eif(swsUtil.supportedOptions.elasticsearchIndexPrefix in swsOptions) {
        this.indexPrefix = swsOptions[swsUtil.supportedOptions.elasticsearchIndexPrefix];
    }
 
    Eif(swsUtil.supportedOptions.elasticsearchUsername in swsOptions) {
        this.elasticUsername = swsOptions[swsUtil.supportedOptions.elasticsearchUsername];
    }
 
    Eif(swsUtil.supportedOptions.elasticsearchPassword in swsOptions) {
        this.elasticPassword = swsOptions[swsUtil.supportedOptions.elasticsearchPassword];
    }
 
    // Check / Initialize schema
    this.initTemplate();
 
    this.enabled = true;
 
};
 
// initialize index template
swsElasticEmitter.prototype.initTemplate = function(rrr) {
 
    var that = this;
 
    var requiredTemplateVersion = indexTemplate.version;
 
    // Check if there is a template
    var templateURL = this.elasticURL+'/_template/template_api';
    var getOptions = {url:templateURL, json:true};
    var putOptions = {url:templateURL, json:indexTemplate};
 
    Iif (this.elasticUsername && this.elasticPassword) {
        var auth = {
            username: this.elasticUsername,
            password: this.elasticPassword,
        }
        getOptions.auth = auth;
        putOptions.auth = auth;
    }
 
    request.get(getOptions, function (error, response, body) {
        Iif(error) {
            debug("Error querying template:", JSON.stringify(error) );
        }else {
 
            var initializeNeeded = false;
 
            Eif(response.statusCode === 404){
                initializeNeeded = true;
            }else if(response.statusCode === 200){
                if( 'template_api' in body ) {
                    if (!('version' in body.template_api) || (body.template_api.version < requiredTemplateVersion)) {
                        initializeNeeded = true;
                    }
                }
            }
 
            Eif(initializeNeeded){
                request.put(putOptions, function (error, response, body) {
                    Iif(error) {
                        debug("Failed to update template:", JSON.stringify(error));
                    }
                });
            }
 
        }
    });
 
};
 
// Update timeline and stats per tick
swsElasticEmitter.prototype.tick = function (ts,totalElapsedSec) {
 
    // Flush if buffer is not empty and not flushed in more than 1 second
    if( (this.bufferCount > 0) && ((ts-this.lastFlush) >= 1000) ){
        this.flush();
    }
 
};
 
 
// Pre-process RRR
swsElasticEmitter.prototype.preProcessRecord = function(rrr){
 
 
    // handle custom attributes
    Iif('attrs' in rrr){
        var attrs = rrr.attrs;
        for(var attrname in attrs){
            attrs[attrname] = swsUtil.swsStringValue(attrs[attrname]);
        }
    }
 
    Iif('attrsint' in rrr){
        var intattrs = rrr.attrsint;
        for(var intattrname in intattrs){
            intattrs[intattrname] = swsUtil.swsNumValue(intattrs[intattrname]);
        }
    }
 
};
 
 
// Index Request Response Record
swsElasticEmitter.prototype.processRecord = function(rrr){
 
    Iif(!this.enabled){
        return;
    }
 
    this.preProcessRecord(rrr);
 
    // Create metadata
    var indexName = this.indexPrefix+moment(rrr['@timestamp']).utc().format('YYYY.MM.DD');
    var meta = {index:{_index:indexName,_type:'api',_id:rrr.id}};
 
    // Add to buffer
    this.indexBuffer += JSON.stringify(meta) + '\n';
    this.indexBuffer += JSON.stringify(rrr) + '\n';
 
    this.bufferCount++;
 
    Iif( this.bufferCount >= ES_MAX_BUFF ) {
        this.flush();
    }
};
 
swsElasticEmitter.prototype.flush = function(){
 
    Iif(!this.enabled){
        return;
    }
 
    this.lastFlush = Date.now();
 
    var options = {
        url: this.elasticURLBulk,
        headers: {
            'Content-Type': 'application/x-ndjson'
        },
        body: this.indexBuffer
    };
 
    Iif (this.elasticUsername && this.elasticPassword) {
        options.auth = {
            username: this.elasticUsername,
            password: this.elasticPassword,
        }
    }
 
    request.post(options, function (error, response, body) {
        Iif (error) {
            debug("Indexing Error:", JSON.stringify(error) );
        }
        Iif (response && ('statusCode' in response) && (response.statusCode !== 200)) {
            debug('Indexing Error: %d %s',response.statusCode, response.message);
        }
    });
 
    this.indexBuffer = '';
    this.bufferCount = 0;
 
};
 
module.exports = swsElasticEmitter;