BigW Consortium Gitlab

prometheus_graph.js 12.9 KB
Newer Older
1
/* eslint-disable no-new */
2 3
/* global Flash */

4 5
import d3 from 'd3';
import statusCodes from '~/lib/utils/http_status';
6
import { formatRelevantDigits } from '~/lib/utils/number_utils';
7
import '../flash';
8

9 10
const prometheusContainer = '.prometheus-container';
const prometheusParentGraphContainer = '.prometheus-graphs';
11
const prometheusGraphsContainer = '.prometheus-graph';
12
const prometheusStatesContainer = '.prometheus-state';
13 14 15 16 17 18 19 20
const metricsEndpoint = 'metrics.json';
const timeFormat = d3.time.format('%H:%M');
const dayFormat = d3.time.format('%b %e, %a');
const bisectDate = d3.bisector(d => d.time).left;
const extraAddedWidthParent = 100;

class PrometheusGraph {
  constructor() {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    const $prometheusContainer = $(prometheusContainer);
    const hasMetrics = $prometheusContainer.data('has-metrics');
    this.docLink = $prometheusContainer.data('doc-link');
    this.integrationLink = $prometheusContainer.data('prometheus-integration');

    $(document).ajaxError(() => {});

    if (hasMetrics) {
      this.margin = { top: 80, right: 180, bottom: 80, left: 100 };
      this.marginLabelContainer = { top: 40, right: 0, bottom: 40, left: 0 };
      const parentContainerWidth = $(prometheusGraphsContainer).parent().width() +
      extraAddedWidthParent;
      this.originalWidth = parentContainerWidth;
      this.originalHeight = 330;
      this.width = parentContainerWidth - this.margin.left - this.margin.right;
      this.height = this.originalHeight - this.margin.top - this.margin.bottom;
      this.backOffRequestCounter = 0;
      this.configureGraph();
      this.init();
    } else {
      this.state = '.js-getting-started';
      this.updateState();
    }
44 45 46
  }

  createGraph() {
47 48 49 50
    Object.keys(this.graphSpecificProperties).forEach((key) => {
      const value = this.graphSpecificProperties[key];
      if (value.data.length > 0) {
        this.plotValues(key);
51 52 53 54 55 56
      }
    });
  }

  init() {
    this.getData().then((metricsResponse) => {
57 58 59 60 61 62 63 64 65 66 67 68 69
      let enoughData = true;
      Object.keys(metricsResponse.metrics).forEach((key) => {
        let currentKey;
        if (key === 'cpu_values' || key === 'memory_values') {
          currentKey = metricsResponse.metrics[key];
          if (Object.keys(currentKey).length === 0) {
            enoughData = false;
          }
        }
      });
      if (!enoughData) {
        this.state = '.js-loading';
        this.updateState();
70
      } else {
71 72
        this.transformData(metricsResponse);
        this.createGraph();
73 74 75 76
      }
    });
  }

77
  plotValues(key) {
78 79
    const graphSpecifics = this.graphSpecificProperties[key];

80 81 82 83 84 85
    const x = d3.time.scale()
        .range([0, this.width]);

    const y = d3.scale.linear()
        .range([this.height, 0]);

86 87
    graphSpecifics.xScale = x;
    graphSpecifics.yScale = y;
88

89 90 91
    const prometheusGraphContainer = `${prometheusGraphsContainer}[graph-type=${key}]`;

    const chart = d3.select(prometheusGraphContainer)
92 93 94 95
      .attr('width', this.width + this.margin.left + this.margin.right)
      .attr('height', this.height + this.margin.bottom + this.margin.top)
      .append('g')
        .attr('transform', `translate(${this.margin.left},${this.margin.top})`);
96 97

    const axisLabelContainer = d3.select(prometheusGraphContainer)
98 99
      .attr('width', this.originalWidth)
      .attr('height', this.originalHeight)
100 101 102
      .append('g')
        .attr('transform', `translate(${this.marginLabelContainer.left},${this.marginLabelContainer.top})`);

103 104
    x.domain(d3.extent(graphSpecifics.data, d => d.time));
    y.domain([0, d3.max(graphSpecifics.data.map(metricValue => metricValue.value))]);
105 106

    const xAxis = d3.svg.axis()
107 108 109
      .scale(x)
      .ticks(this.commonGraphProperties.axis_no_ticks)
      .orient('bottom');
110 111

    const yAxis = d3.svg.axis()
112 113 114 115
      .scale(y)
      .ticks(this.commonGraphProperties.axis_no_ticks)
      .tickSize(-this.width)
      .orient('left');
116 117 118 119

    this.createAxisLabelContainers(axisLabelContainer, key);

    chart.append('g')
120 121 122
      .attr('class', 'x-axis')
      .attr('transform', `translate(0,${this.height})`)
      .call(xAxis);
123 124

    chart.append('g')
125 126
      .attr('class', 'y-axis')
      .call(yAxis);
127 128 129 130 131 132 133 134 135 136 137 138

    const area = d3.svg.area()
      .x(d => x(d.time))
      .y0(this.height)
      .y1(d => y(d.value))
      .interpolate('linear');

    const line = d3.svg.line()
    .x(d => x(d.time))
    .y(d => y(d.value));

    chart.append('path')
139 140 141 142
      .datum(graphSpecifics.data)
      .attr('d', area)
      .attr('class', 'metric-area')
      .attr('fill', graphSpecifics.area_fill_color);
143 144

    chart.append('path')
145
      .datum(graphSpecifics.data)
146 147 148 149 150 151 152 153 154 155 156
      .attr('class', 'metric-line')
      .attr('stroke', graphSpecifics.line_color)
      .attr('fill', 'none')
      .attr('stroke-width', this.commonGraphProperties.area_stroke_width)
      .attr('d', line);

    // Overlay area for the mouseover events
    chart.append('rect')
      .attr('class', 'prometheus-graph-overlay')
      .attr('width', this.width)
      .attr('height', this.height)
157
      .on('mousemove', this.handleMouseOverGraph.bind(this, prometheusGraphContainer));
158 159 160 161 162 163 164
  }

  // The legends from the metric
  createAxisLabelContainers(axisLabelContainer, key) {
    const graphSpecifics = this.graphSpecificProperties[key];

    axisLabelContainer.append('line')
165 166 167 168 169 170 171 172 173
      .attr('class', 'label-x-axis-line')
      .attr('stroke', '#000000')
      .attr('stroke-width', '1')
      .attr({
        x1: 10,
        y1: this.originalHeight - this.margin.top,
        x2: (this.originalWidth - this.margin.right) + 10,
        y2: this.originalHeight - this.margin.top,
      });
174 175

    axisLabelContainer.append('line')
176 177 178 179 180 181 182 183 184 185
      .attr('class', 'label-y-axis-line')
      .attr('stroke', '#000000')
      .attr('stroke-width', '1')
      .attr({
        x1: 10,
        y1: 0,
        x2: 10,
        y2: this.originalHeight - this.margin.top,
      });

186
    axisLabelContainer.append('rect')
187 188 189 190 191
      .attr('class', 'rect-axis-text')
      .attr('x', 0)
      .attr('y', 50)
      .attr('width', 30)
      .attr('height', 150);
192 193

    axisLabelContainer.append('text')
194 195 196 197
      .attr('class', 'label-axis-text')
      .attr('text-anchor', 'middle')
      .attr('transform', `translate(15, ${(this.originalHeight - this.margin.top) / 2}) rotate(-90)`)
      .text(graphSpecifics.graph_legend_title);
198 199

    axisLabelContainer.append('rect')
200 201 202 203 204
      .attr('class', 'rect-axis-text')
      .attr('x', (this.originalWidth / 2) - this.margin.right)
      .attr('y', this.originalHeight - 100)
      .attr('width', 30)
      .attr('height', 80);
205 206

    axisLabelContainer.append('text')
207 208 209 210 211
      .attr('class', 'label-axis-text')
      .attr('x', (this.originalWidth / 2) - this.margin.right)
      .attr('y', this.originalHeight - this.margin.top)
      .attr('dy', '.35em')
      .text('Time');
212 213 214 215 216

    // Legends

    // Metric Usage
    axisLabelContainer.append('rect')
217 218 219 220 221
      .attr('x', this.originalWidth - 170)
      .attr('y', (this.originalHeight / 2) - 60)
      .style('fill', graphSpecifics.area_fill_color)
      .attr('width', 20)
      .attr('height', 35);
222 223

    axisLabelContainer.append('text')
224 225 226 227
      .attr('class', 'text-metric-title')
      .attr('x', this.originalWidth - 140)
      .attr('y', (this.originalHeight / 2) - 50)
      .text('Average');
228 229

    axisLabelContainer.append('text')
230 231 232
      .attr('class', 'text-metric-usage')
      .attr('x', this.originalWidth - 140)
      .attr('y', (this.originalHeight / 2) - 25);
233 234
  }

235
  handleMouseOverGraph(prometheusGraphContainer) {
236
    const rectOverlay = document.querySelector(`${prometheusGraphContainer} .prometheus-graph-overlay`);
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
    const currentXCoordinate = d3.mouse(rectOverlay)[0];

    Object.keys(this.graphSpecificProperties).forEach((key) => {
      const currentGraphProps = this.graphSpecificProperties[key];
      const timeValueOverlay = currentGraphProps.xScale.invert(currentXCoordinate);
      const overlayIndex = bisectDate(currentGraphProps.data, timeValueOverlay, 1);
      const d0 = currentGraphProps.data[overlayIndex - 1];
      const d1 = currentGraphProps.data[overlayIndex];
      const evalTime = timeValueOverlay - d0.time > d1.time - timeValueOverlay;
      const currentData = evalTime ? d1 : d0;
      const currentTimeCoordinate = currentGraphProps.xScale(currentData.time);
      const currentPrometheusGraphContainer = `${prometheusGraphsContainer}[graph-type=${key}]`;
      const maxValueFromData = d3.max(currentGraphProps.data.map(metricValue => metricValue.value));
      const maxMetricValue = currentGraphProps.yScale(maxValueFromData);

      // Clear up all the pieces of the flag
      d3.selectAll(`${currentPrometheusGraphContainer} .selected-metric-line`).remove();
      d3.selectAll(`${currentPrometheusGraphContainer} .circle-metric`).remove();
      d3.selectAll(`${currentPrometheusGraphContainer} .rect-text-metric`).remove();
      d3.selectAll(`${currentPrometheusGraphContainer} .text-metric`).remove();

      const currentChart = d3.select(currentPrometheusGraphContainer).select('g');
      currentChart.append('line')
      .attr('class', 'selected-metric-line')
      .attr({
        x1: currentTimeCoordinate,
        y1: currentGraphProps.yScale(0),
        x2: currentTimeCoordinate,
        y2: maxMetricValue,
      });

      currentChart.append('circle')
269 270 271 272 273
        .attr('class', 'circle-metric')
        .attr('fill', currentGraphProps.line_color)
        .attr('cx', currentTimeCoordinate)
        .attr('cy', currentGraphProps.yScale(currentData.value))
        .attr('r', this.commonGraphProperties.circle_radius_metric);
274 275 276

      // The little box with text
      const rectTextMetric = currentChart.append('g')
277 278
        .attr('class', 'rect-text-metric')
        .attr('translate', `(${currentTimeCoordinate}, ${currentGraphProps.yScale(currentData.value)})`);
279 280

      rectTextMetric.append('rect')
281 282 283 284 285
        .attr('class', 'rect-metric')
        .attr('x', currentTimeCoordinate + 10)
        .attr('y', maxMetricValue)
        .attr('width', this.commonGraphProperties.rect_text_width)
        .attr('height', this.commonGraphProperties.rect_text_height);
286 287

      rectTextMetric.append('text')
288 289 290 291
        .attr('class', 'text-metric')
        .attr('x', currentTimeCoordinate + 35)
        .attr('y', maxMetricValue + 35)
        .text(timeFormat(currentData.time));
292 293

      rectTextMetric.append('text')
294 295 296 297
        .attr('class', 'text-metric-date')
        .attr('x', currentTimeCoordinate + 15)
        .attr('y', maxMetricValue + 15)
        .text(dayFormat(currentData.time));
298

299
      let currentMetricValue = formatRelevantDigits(currentData.value);
300 301 302
      if (key === 'cpu_values') {
        currentMetricValue = `${currentMetricValue}%`;
      } else {
303
        currentMetricValue = `${currentMetricValue} MB`;
304
      }
305

306
      d3.select(`${currentPrometheusGraphContainer} .text-metric-usage`)
307
        .text(currentMetricValue);
308
    });
309 310 311 312 313 314 315
  }

  configureGraph() {
    this.graphSpecificProperties = {
      cpu_values: {
        area_fill_color: '#edf3fc',
        line_color: '#5b99f7',
316 317
        graph_legend_title: 'CPU Usage (Cores)',
        data: [],
318 319
        xScale: {},
        yScale: {},
320 321 322 323
      },
      memory_values: {
        area_fill_color: '#fca326',
        line_color: '#fc6d26',
324 325
        graph_legend_title: 'Memory Usage (MB)',
        data: [],
326 327
        xScale: {},
        yScale: {},
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
      },
    };

    this.commonGraphProperties = {
      area_stroke_width: 2,
      median_total_characters: 8,
      circle_radius_metric: 5,
      rect_text_width: 90,
      rect_text_height: 40,
      axis_no_ticks: 3,
    };
  }

  getData() {
    const maxNumberOfRequests = 3;
    return gl.utils.backOff((next, stop) => {
      $.ajax({
        url: metricsEndpoint,
        dataType: 'json',
      })
      .done((data, statusText, resp) => {
        if (resp.status === statusCodes.NO_CONTENT) {
          this.backOffRequestCounter = this.backOffRequestCounter += 1;
          if (this.backOffRequestCounter < maxNumberOfRequests) {
            next();
          } else {
            stop({
              status: resp.status,
              metrics: data,
            });
          }
        } else {
          stop({
            status: resp.status,
            metrics: data,
          });
        }
      }).fail(stop);
    })
    .then((resp) => {
      if (resp.status === statusCodes.NO_CONTENT) {
        return {};
      }
      return resp.metrics;
    })
373 374 375 376
    .catch(() => {
      this.state = '.js-unable-to-connect';
      this.updateState();
    });
377 378 379
  }

  transformData(metricsResponse) {
380 381 382
    Object.keys(metricsResponse.metrics).forEach((key) => {
      if (key === 'cpu_values' || key === 'memory_values') {
        const metricValues = (metricsResponse.metrics[key])[0];
383
        if (metricValues !== undefined) {
384 385 386 387 388
          this.graphSpecificProperties[key].data = metricValues.values.map(metric => ({
            time: new Date(metric[0] * 1000),
            value: metric[1],
          }));
        }
389
      }
390 391
    });
  }
392 393 394 395 396 397 398

  updateState() {
    const $statesContainer = $(prometheusStatesContainer);
    $(prometheusParentGraphContainer).hide();
    $(`${this.state}`, $statesContainer).removeClass('hidden');
    $(prometheusStatesContainer).show();
  }
399 400 401
}

export default PrometheusGraph;