summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/monitoring/stores/actions.js
blob: 5b2bd1f149391c1c7af4995e0044e5faa7967f53 (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
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
import * as Sentry from '@sentry/browser';
import * as types from './mutation_types';
import axios from '~/lib/utils/axios_utils';
import createFlash from '~/flash';
import { convertToFixedRange } from '~/lib/utils/datetime_range';
import { gqClient, parseEnvironmentsResponse, removeLeadingSlash } from './utils';
import trackDashboardLoad from '../monitoring_tracking_helper';
import getEnvironments from '../queries/getEnvironments.query.graphql';
import getAnnotations from '../queries/getAnnotations.query.graphql';
import statusCodes from '../../lib/utils/http_status';
import {
  backOff,
  convertObjectPropsToCamelCase,
  isFeatureFlagEnabled,
} from '../../lib/utils/common_utils';
import { s__, sprintf } from '../../locale';

import { PROMETHEUS_TIMEOUT, ENVIRONMENT_AVAILABLE_STATE } from '../constants';

function prometheusMetricQueryParams(timeRange) {
  const { start, end } = convertToFixedRange(timeRange);

  const timeDiff = (new Date(end) - new Date(start)) / 1000;
  const minStep = 60;
  const queryDataPoints = 600;

  return {
    start_time: start,
    end_time: end,
    step: Math.max(minStep, Math.ceil(timeDiff / queryDataPoints)),
  };
}

function backOffRequest(makeRequestCallback) {
  return backOff((next, stop) => {
    makeRequestCallback()
      .then(resp => {
        if (resp.status === statusCodes.NO_CONTENT) {
          next();
        } else {
          stop(resp);
        }
      })
      .catch(stop);
  }, PROMETHEUS_TIMEOUT);
}

function getPrometheusMetricResult(prometheusEndpoint, params) {
  return backOffRequest(() => axios.get(prometheusEndpoint, { params }))
    .then(res => res.data)
    .then(response => {
      if (response.status === 'error') {
        throw new Error(response.error);
      }

      return response.data.result;
    });
}

// Setup

export const setGettingStartedEmptyState = ({ commit }) => {
  commit(types.SET_GETTING_STARTED_EMPTY_STATE);
};

export const setInitialState = ({ commit }, initialState) => {
  commit(types.SET_INITIAL_STATE, initialState);
};

export const setTimeRange = ({ commit }, timeRange) => {
  commit(types.SET_TIME_RANGE, timeRange);
};

export const filterEnvironments = ({ commit, dispatch }, searchTerm) => {
  commit(types.SET_ENVIRONMENTS_FILTER, searchTerm);
  dispatch('fetchEnvironmentsData');
};

export const setShowErrorBanner = ({ commit }, enabled) => {
  commit(types.SET_SHOW_ERROR_BANNER, enabled);
};

// All Data

export const fetchData = ({ dispatch }) => {
  dispatch('fetchEnvironmentsData');
  dispatch('fetchDashboard');
  /**
   * Annotations data is not yet fetched. This will be
   * ready after the BE piece is implemented.
   * https://gitlab.com/gitlab-org/gitlab/-/issues/211330
   */
  if (isFeatureFlagEnabled('metrics_dashboard_annotations')) {
    dispatch('fetchAnnotations');
  }
};

// Metrics dashboard

export const fetchDashboard = ({ state, commit, dispatch }) => {
  dispatch('requestMetricsDashboard');

  const params = {};
  if (state.currentDashboard) {
    params.dashboard = state.currentDashboard;
  }

  return backOffRequest(() => axios.get(state.dashboardEndpoint, { params }))
    .then(resp => resp.data)
    .then(response => dispatch('receiveMetricsDashboardSuccess', { response }))
    .catch(error => {
      Sentry.captureException(error);

      commit(types.SET_ALL_DASHBOARDS, error.response?.data?.all_dashboards ?? []);
      dispatch('receiveMetricsDashboardFailure', error);

      if (state.showErrorBanner) {
        if (error.response.data && error.response.data.message) {
          const { message } = error.response.data;
          createFlash(
            sprintf(
              s__('Metrics|There was an error while retrieving metrics. %{message}'),
              { message },
              false,
            ),
          );
        } else {
          createFlash(s__('Metrics|There was an error while retrieving metrics'));
        }
      }
    });
};

export const requestMetricsDashboard = ({ commit }) => {
  commit(types.REQUEST_METRICS_DASHBOARD);
};
export const receiveMetricsDashboardSuccess = ({ commit, dispatch }, { response }) => {
  const { all_dashboards, dashboard, metrics_data } = response;

  commit(types.SET_ALL_DASHBOARDS, all_dashboards);
  commit(types.RECEIVE_METRICS_DASHBOARD_SUCCESS, dashboard);
  commit(types.SET_ENDPOINTS, convertObjectPropsToCamelCase(metrics_data));

  return dispatch('fetchDashboardData');
};
export const receiveMetricsDashboardFailure = ({ commit }, error) => {
  commit(types.RECEIVE_METRICS_DASHBOARD_FAILURE, error);
};

// Metrics

/**
 * Loads timeseries data: Prometheus data points and deployment data from the project
 * @param {Object} Vuex store
 */
export const fetchDashboardData = ({ state, dispatch, getters }) => {
  dispatch('fetchDeploymentsData');

  if (!state.timeRange) {
    createFlash(s__(`Metrics|Invalid time range, please verify.`), 'warning');
    return Promise.reject();
  }

  const defaultQueryParams = prometheusMetricQueryParams(state.timeRange);

  const promises = [];
  state.dashboard.panelGroups.forEach(group => {
    group.panels.forEach(panel => {
      panel.metrics.forEach(metric => {
        promises.push(dispatch('fetchPrometheusMetric', { metric, defaultQueryParams }));
      });
    });
  });

  return Promise.all(promises)
    .then(() => {
      const dashboardType = state.currentDashboard === '' ? 'default' : 'custom';
      trackDashboardLoad({
        label: `${dashboardType}_metrics_dashboard`,
        value: getters.metricsWithData().length,
      });
    })
    .catch(() => {
      createFlash(s__(`Metrics|There was an error while retrieving metrics`), 'warning');
    });
};

/**
 * Returns list of metrics in data.result
 * {"status":"success", "data":{"resultType":"matrix","result":[]}}
 *
 * @param {metric} metric
 */
export const fetchPrometheusMetric = ({ commit }, { metric, defaultQueryParams }) => {
  const queryParams = { ...defaultQueryParams };
  if (metric.step) {
    queryParams.step = metric.step;
  }

  commit(types.REQUEST_METRIC_RESULT, { metricId: metric.metricId });

  return getPrometheusMetricResult(metric.prometheusEndpointPath, queryParams)
    .then(result => {
      commit(types.RECEIVE_METRIC_RESULT_SUCCESS, { metricId: metric.metricId, result });
    })
    .catch(error => {
      Sentry.captureException(error);

      commit(types.RECEIVE_METRIC_RESULT_FAILURE, { metricId: metric.metricId, error });
      // Continue to throw error so the dashboard can notify using createFlash
      throw error;
    });
};

// Deployments

export const fetchDeploymentsData = ({ state, dispatch }) => {
  if (!state.deploymentsEndpoint) {
    return Promise.resolve([]);
  }
  return axios
    .get(state.deploymentsEndpoint)
    .then(resp => resp.data)
    .then(response => {
      if (!response || !response.deployments) {
        createFlash(s__('Metrics|Unexpected deployment data response from prometheus endpoint'));
      }

      dispatch('receiveDeploymentsDataSuccess', response.deployments);
    })
    .catch(error => {
      Sentry.captureException(error);
      dispatch('receiveDeploymentsDataFailure');
      createFlash(s__('Metrics|There was an error getting deployment information.'));
    });
};
export const receiveDeploymentsDataSuccess = ({ commit }, data) => {
  commit(types.RECEIVE_DEPLOYMENTS_DATA_SUCCESS, data);
};
export const receiveDeploymentsDataFailure = ({ commit }) => {
  commit(types.RECEIVE_DEPLOYMENTS_DATA_FAILURE);
};

// Environments

export const fetchEnvironmentsData = ({ state, dispatch }) => {
  dispatch('requestEnvironmentsData');
  return gqClient
    .mutate({
      mutation: getEnvironments,
      variables: {
        projectPath: removeLeadingSlash(state.projectPath),
        search: state.environmentsSearchTerm,
        states: [ENVIRONMENT_AVAILABLE_STATE],
      },
    })
    .then(resp =>
      parseEnvironmentsResponse(resp.data?.project?.data?.environments, state.projectPath),
    )
    .then(environments => {
      if (!environments) {
        createFlash(
          s__('Metrics|There was an error fetching the environments data, please try again'),
        );
      }

      dispatch('receiveEnvironmentsDataSuccess', environments);
    })
    .catch(err => {
      Sentry.captureException(err);
      dispatch('receiveEnvironmentsDataFailure');
      createFlash(s__('Metrics|There was an error getting environments information.'));
    });
};
export const requestEnvironmentsData = ({ commit }) => {
  commit(types.REQUEST_ENVIRONMENTS_DATA);
};
export const receiveEnvironmentsDataSuccess = ({ commit }, data) => {
  commit(types.RECEIVE_ENVIRONMENTS_DATA_SUCCESS, data);
};
export const receiveEnvironmentsDataFailure = ({ commit }) => {
  commit(types.RECEIVE_ENVIRONMENTS_DATA_FAILURE);
};

export const fetchAnnotations = ({ state, dispatch }) => {
  dispatch('requestAnnotations');

  return gqClient
    .mutate({
      mutation: getAnnotations,
      variables: {
        projectPath: removeLeadingSlash(state.projectPath),
        dashboardId: state.currentDashboard,
        environmentName: state.currentEnvironmentName,
      },
    })
    .then(resp => resp.data?.project?.environment?.metricDashboard?.annotations)
    .then(annotations => {
      if (!annotations) {
        createFlash(s__('Metrics|There was an error fetching annotations. Please try again.'));
      }

      dispatch('receiveAnnotationsSuccess', annotations);
    })
    .catch(err => {
      Sentry.captureException(err);
      dispatch('receiveAnnotationsFailure');
      createFlash(s__('Metrics|There was an error getting annotations information.'));
    });
};

// While this commit does not update the state it will
// eventually be useful to show a loading state
export const requestAnnotations = ({ commit }) => commit(types.REQUEST_ANNOTATIONS);
export const receiveAnnotationsSuccess = ({ commit }, data) =>
  commit(types.RECEIVE_ANNOTATIONS_SUCCESS, data);
export const receiveAnnotationsFailure = ({ commit }) => commit(types.RECEIVE_ANNOTATIONS_FAILURE);

// Dashboard manipulation

/**
 * Set a new array of metrics to a panel group
 * @param {*} data An object containing
 *   - `key` with a unique panel key
 *   - `metrics` with the metrics array
 */
export const setPanelGroupMetrics = ({ commit }, data) => {
  commit(types.SET_PANEL_GROUP_METRICS, data);
};

export const duplicateSystemDashboard = ({ state }, payload) => {
  const params = {
    dashboard: payload.dashboard,
    file_name: payload.fileName,
    branch: payload.branch,
    commit_message: payload.commitMessage,
  };

  return axios
    .post(state.dashboardsEndpoint, params)
    .then(response => response.data)
    .then(data => data.dashboard)
    .catch(error => {
      Sentry.captureException(error);

      const { response } = error;

      if (response && response.data && response.data.error) {
        throw sprintf(s__('Metrics|There was an error creating the dashboard. %{error}'), {
          error: response.data.error,
        });
      } else {
        throw s__('Metrics|There was an error creating the dashboard.');
      }
    });
};

// prevent babel-plugin-rewire from generating an invalid default during karma tests
export default () => {};