summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/monitoring/services/monitoring_service.js
blob: 5fcc2c8cfac88f6f829bb9457fd2cdf92f6093d5 (plain)
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
import axios from '../../lib/utils/axios_utils';
import statusCodes from '../../lib/utils/http_status';
import { backOff } from '../../lib/utils/common_utils';
import { s__ } from '../../locale';

const MAX_REQUESTS = 3;

function backOffRequest(makeRequestCallback) {
  let requestCounter = 0;
  return backOff((next, stop) => {
    makeRequestCallback()
      .then(resp => {
        if (resp.status === statusCodes.NO_CONTENT) {
          requestCounter += 1;
          if (requestCounter < MAX_REQUESTS) {
            next();
          } else {
            stop(new Error('Failed to connect to the prometheus server'));
          }
        } else {
          stop(resp);
        }
      })
      .catch(stop);
  });
}

export default class MonitoringService {
  constructor({ metricsEndpoint, deploymentEndpoint, environmentsEndpoint }) {
    this.metricsEndpoint = metricsEndpoint;
    this.deploymentEndpoint = deploymentEndpoint;
    this.environmentsEndpoint = environmentsEndpoint;
  }

  getGraphsData(params = {}) {
    return backOffRequest(() => axios.get(this.metricsEndpoint, { params }))
      .then(resp => resp.data)
      .then(response => {
        if (!response || !response.data || !response.success) {
          throw new Error(s__('Metrics|Unexpected metrics data response from prometheus endpoint'));
        }
        return response.data;
      });
  }

  getDeploymentData() {
    if (!this.deploymentEndpoint) {
      return Promise.resolve([]);
    }
    return backOffRequest(() => axios.get(this.deploymentEndpoint))
      .then(resp => resp.data)
      .then(response => {
        if (!response || !response.deployments) {
          throw new Error(
            s__('Metrics|Unexpected deployment data response from prometheus endpoint'),
          );
        }
        return response.deployments;
      });
  }

  getEnvironmentsData() {
    return axios
      .get(this.environmentsEndpoint)
      .then(resp => resp.data)
      .then(response => {
        if (!response || !response.environments) {
          throw new Error(
            s__('Metrics|There was an error fetching the environments data, please try again'),
          );
        }
        return response.environments;
      });
  }
}