wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
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
#!/usr/bin/env node
// -*- mode: js -*-
 
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var readline = require('readline');
var sprintf = require('util').format;
 
var nopt = require('nopt');
 
 
///--- Globals
 
var BUCKETS = {};
var REQUEST_IDS = {};
 
var OPTS = {
    'average': Boolean,
    'help': Boolean,
    'end': Date,
    'max-latency': Number,
    'max-requests': Number,
    'output': String,
    'percentile': [Number, Array],
    'period': Number,
    'requests': Boolean,
    'start': Date
};
 
var SHORT_OPTS = {
    'a': ['--average'],
    'h': ['--help'],
    'i': ['--period'],
    'e': ['--end'],
    'l': ['--max-latency'],
    'n': ['--max-requests'],
    'o': ['--output'],
    'p': ['--percentile'],
    'r': ['--requests'],
    's': ['--start']
};
 
 
///--- Functions
 
function percentile(p, vals) {
    p = parseInt(p, 10);
    return vals[(Math.round(((p / 100) * vals.length) + 1 / 2) - 1)].latency;
}
 
 
function report(buckets, output) {
    Object.keys(buckets).sort(function (a, b) {
        return parseInt(a, 10) - parseInt(b, 10);
    }).forEach(function (k) {
            var avg = 0;
            var perc = [];
            var req = buckets[k].length;
            var sum = 0;
            var t = Math.round(buckets[k]._time);
 
            buckets[k] = buckets[k].sort(function (a, b) {
                return a.latency - b.latency;
            });
 
            buckets[k].forEach(function (v) {
                sum += v.latency;
            });
 
            if (sum > 0 && req > 0) {
                if (output.average)
                    output.average.push([t, Math.round(sum / req)]);
                if (output.requests)
                    output.requests.push([t, buckets[k].length]);
                Object.keys(output.percentile).forEach(function (p) {
                    var _p = percentile(p, buckets[k]);
                    output.percentile[p].push([t, _p]);
                });
            }
        });
 
    return output;
}
 
 
function usage(code, message) {
    var str = '';
    Object.keys(SHORT_OPTS).forEach(function (k) {
        if (!Array.isArray(SHORT_OPTS[k]))
            return;
 
        var opt = SHORT_OPTS[k][0].replace('--', '');
        var type = OPTS[opt].name || 'string';
        if (type && type === 'boolean')
            type = '';
        type = type.toLowerCase();
 
        str += ' [--' + opt + ' ' + type + ']';
    });
    str += ' [file ...]';
 
    if (message)
        console.error(message);
 
    console.error('usage: ' + path.basename(process.argv[1]) + str);
    process.exit(code);
}
 
 
///--- Mainline
 
var parsed;
 
try {
    parsed = nopt(OPTS, SHORT_OPTS, process.argv, 2);
} catch (e) {
    usage(1, e.toString());
}
 
if (parsed.help)
    usage(0);
if (!parsed.average && !parsed.percentile)
    usage(1, '--average or --percentile required');
if (parsed.argv.remain.length < 1)
    usage(1, 'log file required');
 
var config = {
    average: parsed.average || false,
    maxLatency: parsed['max-latency'] || 1000,
    maxRequests: parsed['max-requests'] || 10000,
    percentile: parsed.percentile || [],
    period: parsed.period || 60,
    requests: parsed.requests || false,
    start: parsed.start ? (parsed.start.getTime() / 1000) : 0,
    end: parsed.end ? (parsed.end.getTime() / 1000) : Number.MAX_VALUE
};
 
var buckets = {};
 
var done = 0;
parsed.argv.remain.forEach(function (f) {
    var stream = readline.createInterface({
        input: fs.createReadStream(f),
        output: null
    })
    stream.on('line', function (l) {
        var record;
        var t = -1;
 
        try {
            record = JSON.parse(l);
        } catch (e) {
        }
 
        if (!record)
            return;
 
        var t = -1;
        if (record.time)
            t = (new Date(record.time).getTime() / 1000);
 
        if (record._audit !== true ||
            REQUEST_IDS[record.req_id] ||
            t < config.start ||
            t > config.end) {
 
            console.error('Skipping %s', l);
        }
 
        REQUEST_IDS[record.req_id] = true;
        record.time = t;
 
        var b = Math.round(record.time / config.period) + '';
        if (!buckets[b])
            buckets[b] = [];
 
        buckets[b].push(record);
        buckets[b]._time = record.time // good enough
    });
 
    stream.on('end', function () {
        if (++done === parsed.argv.remain.length) {
            console.error('Generating report...');
 
            var output = {
                average: config.average ? [] : false,
                requests: config.requests ? [] : false,
                percentile: {}
            };
            config.percentile.forEach(function (p) {
                output.percentile[p] = [];
            });
 
            output = report(buckets, output);
            var finalOutput = [];
            if (output.average) {
                finalOutput.push({
                    name: 'avg',
                    values: output.average
                });
            }
            if (output.requests) {
                finalOutput.push({
                    name: 'n',
                    values: output.requests
                });
            }
            Object.keys(output.percentile).forEach(function (k) {
                finalOutput.push({
                    name: 'p' + k,
                    values: output.percentile[k]
                });
            });
 
            console.log(JSON.stringify(finalOutput));
        }
    });
});