summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/monitoring/stores/mutations.js
blob: 8bd53a24b61d55cf1489304db4814ec06fb46a5b (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
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
import Vue from 'vue';
import pick from 'lodash/pick';
import { slugify } from '~/lib/utils/text_utility';
import * as types from './mutation_types';
import { normalizeMetric, normalizeQueryResult } from './utils';
import { BACKOFF_TIMEOUT } from '../../lib/utils/common_utils';
import { metricStates } from '../constants';
import httpStatusCodes from '~/lib/utils/http_status';

const normalizePanelMetrics = (metrics, defaultLabel) =>
  metrics.map(metric => ({
    ...normalizeMetric(metric),
    label: metric.label || defaultLabel,
  }));

/**
 * Locate and return a metric in the dashboard by its id
 * as generated by `uniqMetricsId()`.
 * @param {String} metricId Unique id in the dashboard
 * @param {Object} dashboard Full dashboard object
 */
const findMetricInDashboard = (metricId, dashboard) => {
  let res = null;
  dashboard.panel_groups.forEach(group => {
    group.panels.forEach(panel => {
      panel.metrics.forEach(metric => {
        if (metric.metric_id === metricId) {
          res = metric;
        }
      });
    });
  });
  return res;
};

/**
 * Set a new state for a metric.
 *
 * Initally metric data is not populated, so `Vue.set` is
 * used to add new properties to the metric.
 *
 * @param {Object} metric - Metric object as defined in the dashboard
 * @param {Object} state - New state
 * @param {Array|null} state.result - Array of results
 * @param {String} state.error - Error code from metricStates
 * @param {Boolean} state.loading - True if the metric is loading
 */
const setMetricState = (metric, { result = null, loading = false, state = null }) => {
  Vue.set(metric, 'result', result);
  Vue.set(metric, 'loading', loading);
  Vue.set(metric, 'state', state);
};

/**
 * Maps a backened error state to a `metricStates` constant
 * @param {Object} error - Error from backend response
 */
const emptyStateFromError = error => {
  if (!error) {
    return metricStates.UNKNOWN_ERROR;
  }

  // Special error responses
  if (error.message === BACKOFF_TIMEOUT) {
    return metricStates.TIMEOUT;
  }

  // Axios error responses
  const { response } = error;
  if (response && response.status === httpStatusCodes.SERVICE_UNAVAILABLE) {
    return metricStates.CONNECTION_FAILED;
  } else if (response && response.status === httpStatusCodes.BAD_REQUEST) {
    // Note: "error.response.data.error" may contain Prometheus error information
    return metricStates.BAD_QUERY;
  }

  return metricStates.UNKNOWN_ERROR;
};

export default {
  /**
   * Dashboard panels structure and global state
   */
  [types.REQUEST_METRICS_DATA](state) {
    state.emptyState = 'loading';
    state.showEmptyState = true;
  },
  [types.RECEIVE_METRICS_DATA_SUCCESS](state, dashboard) {
    state.dashboard = {
      ...dashboard,
      panel_groups: dashboard.panel_groups.map((group, i) => {
        const key = `${slugify(group.group || 'default')}-${i}`;
        let { panels = [] } = group;

        // each panel has metric information that needs to be normalized
        panels = panels.map(panel => ({
          ...panel,
          metrics: normalizePanelMetrics(panel.metrics, panel.y_label),
        }));

        return {
          ...group,
          panels,
          key,
        };
      }),
    };

    if (!state.dashboard.panel_groups.length) {
      state.emptyState = 'noData';
    }
  },
  [types.RECEIVE_METRICS_DATA_FAILURE](state, error) {
    state.emptyState = error ? 'unableToConnect' : 'noData';
    state.showEmptyState = true;
  },

  /**
   * Deployments and environments
   */
  [types.RECEIVE_DEPLOYMENTS_DATA_SUCCESS](state, deployments) {
    state.deploymentData = deployments;
  },
  [types.RECEIVE_DEPLOYMENTS_DATA_FAILURE](state) {
    state.deploymentData = [];
  },
  [types.REQUEST_ENVIRONMENTS_DATA](state) {
    state.environmentsLoading = true;
  },
  [types.RECEIVE_ENVIRONMENTS_DATA_SUCCESS](state, environments) {
    state.environmentsLoading = false;
    state.environments = environments;
  },
  [types.RECEIVE_ENVIRONMENTS_DATA_FAILURE](state) {
    state.environmentsLoading = false;
    state.environments = [];
  },

  /**
   * Individual panel/metric results
   */
  [types.REQUEST_METRIC_RESULT](state, { metricId }) {
    const metric = findMetricInDashboard(metricId, state.dashboard);
    setMetricState(metric, {
      loading: true,
      state: metricStates.LOADING,
    });
  },
  [types.RECEIVE_METRIC_RESULT_SUCCESS](state, { metricId, result }) {
    if (!metricId) {
      return;
    }

    state.showEmptyState = false;

    const metric = findMetricInDashboard(metricId, state.dashboard);
    if (!result || result.length === 0) {
      setMetricState(metric, {
        state: metricStates.NO_DATA,
      });
    } else {
      const normalizedResults = result.map(normalizeQueryResult);
      setMetricState(metric, {
        result: Object.freeze(normalizedResults),
        state: metricStates.OK,
      });
    }
  },
  [types.RECEIVE_METRIC_RESULT_FAILURE](state, { metricId, error }) {
    if (!metricId) {
      return;
    }
    const metric = findMetricInDashboard(metricId, state.dashboard);
    setMetricState(metric, {
      state: emptyStateFromError(error),
    });
  },
  [types.SET_ENDPOINTS](state, endpoints = {}) {
    const endpointKeys = [
      'metricsEndpoint',
      'deploymentsEndpoint',
      'dashboardEndpoint',
      'dashboardsEndpoint',
      'currentDashboard',
      'projectPath',
      'logsPath',
    ];
    Object.entries(pick(endpoints, endpointKeys)).forEach(([key, value]) => {
      state[key] = value;
    });
  },
  [types.SET_TIME_RANGE](state, timeRange) {
    state.timeRange = timeRange;
  },
  [types.SET_GETTING_STARTED_EMPTY_STATE](state) {
    state.emptyState = 'gettingStarted';
  },
  [types.SET_NO_DATA_EMPTY_STATE](state) {
    state.showEmptyState = true;
    state.emptyState = 'noData';
  },
  [types.SET_ALL_DASHBOARDS](state, dashboards) {
    state.allDashboards = dashboards || [];
  },
  [types.SET_SHOW_ERROR_BANNER](state, enabled) {
    state.showErrorBanner = enabled;
  },
  [types.SET_PANEL_GROUP_METRICS](state, payload) {
    const panelGroup = state.dashboard.panel_groups.find(pg => payload.key === pg.key);
    panelGroup.panels = payload.panels;
  },
  [types.SET_ENVIRONMENTS_FILTER](state, searchTerm) {
    state.environmentsSearchTerm = searchTerm;
  },
};