forked from openshift/origin-web-console
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeploymentMetrics.js
530 lines (463 loc) · 16.5 KB
/
deploymentMetrics.js
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
'use strict';
angular.module('openshiftConsole')
.directive('deploymentMetrics', function($interval,
$parse,
$timeout,
$q,
$rootScope,
ChartsService,
ConversionService,
MetricsService) {
return {
restrict: 'E',
scope: {
pods: '=',
// Take in the list of containers rather than reading from the pod spec
// in case pods is empty.
containers: '=',
// Optional: set to 'compact' to show smaller charts (for the overview)
profile: '@',
alerts: '=?'
},
templateUrl: function(elem, attrs) {
if (attrs.profile === 'compact') {
return 'views/directives/metrics-compact.html';
}
return 'views/directives/deployment-metrics.html';
},
link: function(scope) {
var chartByMetric = {};
var intervalPromise;
var updateInterval = 60 * 1000; // 60 seconds
var numDataPoints = 30;
var compact = scope.profile === 'compact';
// Set to true when the route changes so we don't update charts that no longer exist.
var destroyed = false;
scope.uniqueID = _.uniqueId('metrics-');
// Map of metric.type -> podName -> metrics data
var data = {};
// The last data point timestamp we've gotten.
var lastTimestamp;
// Wait until the charts are in view before fetching metrics.
var paused = compact;
// Track when we last requested metrics. When we scroll into view, this
// helps decide whether to update immediately or wait until the next
// interval tick.
var lastUpdated;
// Metrics to display.
scope.metrics = [{
label: "Memory",
units: "MiB",
convert: ConversionService.bytesToMiB,
descriptor: 'memory/usage',
type: 'pod_container',
chartID: "memory-" + scope.uniqueID
}, {
label: "CPU",
units: "millicores",
descriptor: 'cpu/usage_rate',
type: 'pod_container',
chartID: "cpu-" + scope.uniqueID
}, {
label: "Network (Sent)",
units: "KiB/s",
convert: ConversionService.bytesToKiB,
descriptor: 'network/tx_rate',
type: 'pod',
compactLabel: "Network",
compactDatasetLabel: "Sent",
compactType: 'spline',
chartID: "network-tx-" + scope.uniqueID
}, {
label: "Network (Received)",
units: "KiB/s",
convert: ConversionService.bytesToKiB,
descriptor: 'network/rx_rate',
type: 'pod',
compactCombineWith: 'network/tx_rate',
compactDatasetLabel: "Received",
compactType: 'spline',
chartID: "network-rx-" + scope.uniqueID
}];
var metricByID = _.indexBy(scope.metrics, 'descriptor');
// Set to true when any data has been loaded (or failed to load).
scope.loaded = false;
scope.noData = true;
// Track the number of consecutive failures.
var failureCount = 0;
// Get the URL to show in error messages.
MetricsService.getMetricsURL().then(function(url) {
scope.metricsURL = url;
});
// Relative time options.
scope.options = {
rangeOptions: [{
label: "Last hour",
value: 60
}, {
label: "Last 4 hours",
value: 4 * 60
}, {
label: "Last day",
value: 24 * 60
}, {
label: "Last 3 days",
value: 3 * 24 * 60
}, {
label: "Last week",
value: 7 * 24 * 60
}]
};
// Show last hour by default.
scope.options.timeRange = _.head(scope.options.rangeOptions);
scope.options.selectedContainer = _.head(scope.containers);
var createSparklineConfig = function(metric) {
return {
bindto: '#' + metric.chartID,
axis: {
x: {
show: !compact,
type: 'timeseries',
// With default padding you can have negative axis tick values.
padding: {
left: 0,
bottom: 0
},
tick: {
type: 'timeseries',
format: '%a %H:%M'
}
},
y: {
show: !compact,
label: metric.units,
min: 0,
// With default padding you can have negative axis tick values.
padding: {
left: 0,
bottom: 0,
top: 20
},
tick: {
format: function(value) {
return d3.round(value, 3);
}
}
}
},
legend: {
show: !compact && !scope.showAverage
},
point: {
show: false
},
size: {
height: compact ? 35 : 175
},
tooltip: {
format: {
value: function(value) {
return d3.round(value, 2) + " " + metric.units;
}
}
}
};
};
function isNil(point) {
return point.value === null || point.value === undefined;
}
scope.formatUsage = function(usage) {
if (usage < 0.01) {
return '0';
}
if (usage < 1) {
return d3.format('.1r')(usage);
}
return d3.format('.2r')(usage);
};
function averages(metric) {
var label;
if (compact) {
label = metric.compactDatasetLabel || metric.label;
} else {
label = "Average Usage";
}
var averageData = {},
dates = ['Date'],
values = [label],
columns = [dates, values];
var getStats = function(point) {
// Convert start timestamp to a string to use it as a key.
var key = "" + point.start;
if (!averageData[key]) {
averageData[key] = {
total: 0,
count: 0
};
}
return averageData[key];
};
_.each(data[metric.descriptor], function(podData) {
_.each(podData, function(point) {
var stats = getStats(point);
if (!lastTimestamp || lastTimestamp < point.end) {
lastTimestamp = point.end;
}
if (isNil(point)) {
return;
}
stats.total += point.value;
stats.count = stats.count + 1;
});
});
_.each(averageData, function(stats, timestamp) {
var avg;
if (stats.count) {
avg = stats.total / stats.count;
} else {
avg = null;
}
dates.push(Number(timestamp));
values.push(metric.convert ? metric.convert(avg) : avg);
});
if (values.length > 1) {
metric.lastValue = _.last(values) || 0;
}
return columns;
}
function getChartData(newData, metric) {
var columns = [];
var chartData = {
type: 'spline'
};
// If there are too many pods, show only an average line.
if (scope.showAverage) {
_.each(newData[metric.descriptor], function(podData, podName) {
updateData(metric.descriptor, podName, podData);
});
chartData.type = 'area-spline';
if (compact && metric.compactType) {
chartData.type = metric.compactType;
}
chartData.x = 'Date';
chartData.columns = averages(metric);
return chartData;
}
// Iterate over the data for each pod.
_.each(newData[metric.descriptor], function(podData, podName) {
updateData(metric.descriptor, podName, podData);
var dateName = podName + "-dates";
_.set(chartData, ['xs', podName], dateName);
var timestamps = [dateName];
var dataPoints = [podName];
columns.push(timestamps);
columns.push(dataPoints);
// Look at each data point for this pod.
_.each(data[metric.descriptor][podName], function(point) {
timestamps.push(point.start);
if (!lastTimestamp || lastTimestamp < point.end) {
lastTimestamp = point.end;
}
if (isNil(point)) {
dataPoints.push(point.value);
} else {
var value = metric.convert ? metric.convert(point.value) : point.value;
dataPoints.push(value);
}
});
});
// Sort columns by pod names to ensure each pod has the same color in all charts.
chartData.columns = _.sortBy(columns, function(column) {
return column[0];
});
return chartData;
}
function processData(newData) {
if (destroyed) {
return;
}
// Reset the number of failures on a successful request.
failureCount = 0;
// Show an average instead of a multiline chart when there are many pods.
scope.showAverage = _.size(scope.pods) > 5 || compact;
// Iterate over each metric.
_.each(scope.metrics, function(metric) {
var config;
// Get chart data for that metric.
var chartData = getChartData(newData, metric);
var descriptor = metric.descriptor;
if (compact && metric.compactCombineWith) {
descriptor = metric.compactCombineWith;
if (metric.lastValue) {
metricByID[descriptor].lastValue = (metricByID[descriptor].lastValue || 0) + metric.lastValue;
}
}
if (!chartByMetric[descriptor]) {
config = createSparklineConfig(metric);
config.data = chartData;
chartByMetric[descriptor] = c3.generate(config);
} else {
chartByMetric[descriptor].load(chartData);
if (scope.showAverage) {
chartByMetric[descriptor].legend.hide();
} else {
chartByMetric[descriptor].legend.show();
}
}
});
}
function getStartTime() {
if (compact) {
// 15 minutes ago
return "-15mn";
}
return "-" + scope.options.timeRange.value + "mn";
}
function getTimeRangeMillis() {
return scope.options.timeRange.value * 60 * 1000;
}
function getBucketDuration() {
if (compact) {
return "1mn";
}
return Math.floor(getTimeRangeMillis() / numDataPoints) + "ms";
}
function getConfig() {
// Read the namespace from one of the pods since the namespace is not
// passed into the directive.
var pod = _.find(scope.pods, 'metadata.namespace');
if (!pod) {
return;
}
var config = {
pods: scope.pods,
containerName: scope.options.selectedContainer.name,
namespace: pod.metadata.namespace,
bucketDuration: getBucketDuration()
};
// Leave the end time off to use the server's current time as the
// end time. This prevents an issue where the donut chart shows 0
// for current usage if the client clock is ahead of the server
// clock.
if (lastTimestamp) {
config.start = lastTimestamp;
} else {
config.start = getStartTime();
}
return config;
}
// If the first request for metrics fails, show an empty state error message.
// Otherwise show an alert if more than one consecutive request fails.
function metricsFailed(response) {
if (destroyed) {
return;
}
failureCount++;
if (scope.noData) {
// Show an empty state message if the first request for data fails.
scope.metricsError = {
status: _.get(response, 'status', 0),
details: _.get(response, 'data.errorMsg') ||
_.get(response, 'statusText') ||
"Status code " + _.get(response, 'status', 0)
};
return;
}
// If this is the first failure and a previous request succeeded, wait and try again.
if (failureCount < 2) {
return;
}
// Show an alert if we've failed more than once.
// Use scope.$id in the alert ID so that it is unique on pages that
// use the directive multiple times like monitoring.
var alertID = 'metrics-failed-' + scope.uniqueID;
scope.alerts[alertID] = {
type: 'error',
message: 'An error occurred updating metrics.',
links: [{
href: '',
label: 'Retry',
onClick: function() {
delete scope.alerts[alertID];
// Reset failure count to 1 to trigger a retry.
failureCount = 1;
update();
}
}]
};
}
// Make sure there are no errors or missing data before updating.
function canUpdate() {
var noPods = _.isEmpty(scope.pods);
if (noPods) {
// Show the no metrics message.
scope.loaded = true;
return false;
}
return !scope.metricsError && failureCount < 2;
}
function updateData(metricType, podName, podData) {
scope.noData = false;
// Throw out the last data point, which is a partial bucket.
var current = _.initial(podData);
var previous = _.get(data, [metricType, podName]);
if (!previous) {
_.set(data, [metricType, podName], current);
return;
}
// Don't include more than then last `numDataPoints`
var updated = _.takeRight(previous.concat(current), numDataPoints);
_.set(data, [metricType, podName], updated);
}
function update() {
if (paused || !canUpdate()) {
return;
}
lastUpdated = Date.now();
var config = getConfig();
MetricsService.getPodMetrics(config).then(processData, metricsFailed).finally(function() {
// Even on errors mark metrics as loaded to replace the
// "Loading..." message with "No metrics to display."
scope.loaded = true;
});
}
// Updates immediately and then on options changes.
scope.$watch('options', function() {
// Clear the data.
data = {};
lastTimestamp = null;
delete scope.metricsError;
update();
}, true);
// Also update every 30 seconds.
intervalPromise = $interval(update, updateInterval, false);
// Pause or resume metrics updates when the element scrolls into and
// out of view.
scope.updateInView = function(inview) {
paused = !inview;
// Update now if in view and it's been longer than updateInterval.
if (inview && (!lastUpdated || Date.now() > (lastUpdated + updateInterval))) {
update();
}
};
$rootScope.$on('metrics.charts.resize', function(){
$timeout(function() {
_.each(chartByMetric, function(chart) {
chart.flush();
});
}, 0);
});
scope.$on('$destroy', function() {
if (intervalPromise) {
$interval.cancel(intervalPromise);
intervalPromise = null;
}
angular.forEach(chartByMetric, function(chart) {
chart.destroy();
});
chartByMetric = null;
destroyed = true;
});
}
};
});