Read about our upcoming Code of Conduct on this issue

dashboard.vue 18.3 KB
Newer Older
1
<script>
2
3
4
import _ from 'underscore';
import { mapActions, mapState } from 'vuex';
import VueDraggable from 'vuedraggable';
5
6
7
8
import {
  GlButton,
  GlDropdown,
  GlDropdownItem,
9
  GlFormGroup,
10
11
12
13
  GlModal,
  GlModalDirective,
  GlTooltipDirective,
} from '@gitlab/ui';
14
import { __, s__ } from '~/locale';
15
import Icon from '~/vue_shared/components/icon.vue';
16
import { getParameterValues, mergeUrlParams } from '~/lib/utils/url_utility';
17
import invalidUrl from '~/lib/utils/invalid_url';
18
import PanelType from 'ee_else_ce/monitoring/components/panel_type.vue';
19
import MonitorTimeSeriesChart from './charts/time_series.vue';
20
import MonitorSingleStatChart from './charts/single_stat.vue';
Mike Greiling's avatar
Mike Greiling committed
21
22
import GraphGroup from './graph_group.vue';
import EmptyState from './empty_state.vue';
Simon Knox's avatar
Simon Knox committed
23
24
import { sidebarAnimationDuration, timeWindows } from '../constants';
import { getTimeDiff, getTimeWindow } from '../utils';
25

26
27
let sidebarMutationObserver;

Mike Greiling's avatar
Mike Greiling committed
28
29
export default {
  components: {
30
    VueDraggable,
31
    MonitorTimeSeriesChart,
32
33
    MonitorSingleStatChart,
    PanelType,
Mike Greiling's avatar
Mike Greiling committed
34
35
    GraphGroup,
    EmptyState,
36
    Icon,
Adriel Santiago's avatar
Adriel Santiago committed
37
    GlButton,
38
39
    GlDropdown,
    GlDropdownItem,
40
    GlFormGroup,
41
42
43
    GlModal,
  },
  directives: {
44
45
    GlModal: GlModalDirective,
    GlTooltip: GlTooltipDirective,
Mike Greiling's avatar
Mike Greiling committed
46
47
  },
  props: {
48
    externalDashboardUrl: {
Adriel Santiago's avatar
Adriel Santiago committed
49
50
51
52
      type: String,
      required: false,
      default: '',
    },
Mike Greiling's avatar
Mike Greiling committed
53
54
55
56
    hasMetrics: {
      type: Boolean,
      required: false,
      default: true,
Filipa Lacerda's avatar
Filipa Lacerda committed
57
    },
Mike Greiling's avatar
Mike Greiling committed
58
59
60
61
    showPanels: {
      type: Boolean,
      required: false,
      default: true,
62
    },
Mike Greiling's avatar
Mike Greiling committed
63
64
65
    documentationPath: {
      type: String,
      required: true,
66
    },
Mike Greiling's avatar
Mike Greiling committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    settingsPath: {
      type: String,
      required: true,
    },
    clustersPath: {
      type: String,
      required: true,
    },
    tagsPath: {
      type: String,
      required: true,
    },
    projectPath: {
      type: String,
      required: true,
    },
    metricsEndpoint: {
      type: String,
      required: true,
    },
87
    deploymentsEndpoint: {
Mike Greiling's avatar
Mike Greiling committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
      type: String,
      required: false,
      default: null,
    },
    emptyGettingStartedSvgPath: {
      type: String,
      required: true,
    },
    emptyLoadingSvgPath: {
      type: String,
      required: true,
    },
    emptyNoDataSvgPath: {
      type: String,
      required: true,
    },
    emptyUnableToConnectSvgPath: {
      type: String,
      required: true,
    },
108
109
110
111
    environmentsEndpoint: {
      type: String,
      required: true,
    },
112
113
114
115
    currentEnvironmentName: {
      type: String,
      required: true,
    },
116
117
118
119
120
121
122
    customMetricsAvailable: {
      type: Boolean,
      required: false,
      default: false,
    },
    customMetricsPath: {
      type: String,
123
124
      required: false,
      default: invalidUrl,
125
126
127
    },
    validateQueryPath: {
      type: String,
128
129
      required: false,
      default: invalidUrl,
130
    },
131
132
133
134
135
    dashboardEndpoint: {
      type: String,
      required: false,
      default: invalidUrl,
    },
136
137
138
139
140
    currentDashboard: {
      type: String,
      required: false,
      default: '',
    },
141
142
143
144
145
    smallEmptyState: {
      type: Boolean,
      required: false,
      default: false,
    },
146
147
148
149
150
151
152
153
154
155
    alertsEndpoint: {
      type: String,
      required: false,
      default: null,
    },
    prometheusAlertsAvailable: {
      type: Boolean,
      required: false,
      default: false,
    },
156
157
158
159
160
    rearrangePanelsAvailable: {
      type: Boolean,
      required: false,
      default: false,
    },
Mike Greiling's avatar
Mike Greiling committed
161
162
163
164
  },
  data() {
    return {
      state: 'gettingStarted',
Jose Vargas's avatar
Jose Vargas committed
165
      elWidth: 0,
166
      selectedTimeWindow: '',
167
      selectedTimeWindowKey: '',
168
      formIsValid: null,
Simon Knox's avatar
Simon Knox committed
169
      timeWindows: {},
170
      isRearrangingPanels: false,
Mike Greiling's avatar
Mike Greiling committed
171
172
    };
  },
173
174
175
176
  computed: {
    canAddMetrics() {
      return this.customMetricsAvailable && this.customMetricsPath.length;
    },
177
178
179
180
181
182
    ...mapState('monitoringDashboard', [
      'groups',
      'emptyState',
      'showEmptyState',
      'environments',
      'deploymentData',
183
184
      'metricsWithData',
      'useDashboardEndpoint',
185
      'allDashboards',
186
      'additionalPanelTypesEnabled',
187
    ]),
188
189
190
    firstDashboard() {
      return this.allDashboards[0] || {};
    },
191
    selectedDashboardText() {
192
      return this.currentDashboard || this.firstDashboard.display_name;
193
    },
194
195
196
    showRearrangePanelsBtn() {
      return !this.showEmptyState && this.rearrangePanelsAvailable;
    },
197
198
199
200
201
202
    addingMetricsAvailable() {
      return IS_EE && this.canAddMetrics && !this.showEmptyState;
    },
    alertWidgetAvailable() {
      return IS_EE && this.prometheusAlertsAvailable && this.alertsEndpoint;
    },
203
  },
Mike Greiling's avatar
Mike Greiling committed
204
  created() {
205
    this.setEndpoints({
Mike Greiling's avatar
Mike Greiling committed
206
      metricsEndpoint: this.metricsEndpoint,
207
      environmentsEndpoint: this.environmentsEndpoint,
208
      deploymentsEndpoint: this.deploymentsEndpoint,
209
      dashboardEndpoint: this.dashboardEndpoint,
210
      currentDashboard: this.currentDashboard,
211
      projectPath: this.projectPath,
Mike Greiling's avatar
Mike Greiling committed
212
213
214
    });
  },
  beforeDestroy() {
215
216
217
    if (sidebarMutationObserver) {
      sidebarMutationObserver.disconnect();
    }
Mike Greiling's avatar
Mike Greiling committed
218
219
220
  },
  mounted() {
    if (!this.hasMetrics) {
221
      this.setGettingStartedEmptyState();
Mike Greiling's avatar
Mike Greiling committed
222
    } else {
Simon Knox's avatar
Simon Knox committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
      const defaultRange = getTimeDiff();
      const start = getParameterValues('start')[0] || defaultRange.start;
      const end = getParameterValues('end')[0] || defaultRange.end;

      const range = {
        start,
        end,
      };

      this.timeWindows = timeWindows;
      this.selectedTimeWindowKey = getTimeWindow(range);
      this.selectedTimeWindow = this.timeWindows[this.selectedTimeWindowKey];

      this.fetchData(range);
237

238
239
240
241
242
243
      sidebarMutationObserver = new MutationObserver(this.onSidebarMutation);
      sidebarMutationObserver.observe(document.querySelector('.layout-page'), {
        attributes: true,
        childList: false,
        subtree: false,
      });
Mike Greiling's avatar
Mike Greiling committed
244
245
246
    }
  },
  methods: {
247
248
249
250
    ...mapActions('monitoringDashboard', [
      'fetchData',
      'setGettingStartedEmptyState',
      'setEndpoints',
251
      'setDashboardEnabled',
252
    ]),
253
254
255
256
257
258
259
260
    chartsWithData(charts) {
      if (!this.useDashboardEndpoint) {
        return charts;
      }
      return charts.filter(chart =>
        chart.metrics.some(metric => this.metricsWithData.includes(metric.metric_id)),
      );
    },
261
262
263
264
265
266
267
268
269
270
271
272
273
    csvText(graphData) {
      const chartData = graphData.queries[0].result[0].values;
      const yLabel = graphData.y_label;
      const header = `timestamp,${yLabel}\r\n`; // eslint-disable-line @gitlab/i18n/no-non-i18n-strings
      return chartData.reduce((csv, data) => {
        const row = data.join(',');
        return `${csv}${row}\r\n`;
      }, header);
    },
    downloadCsv(graphData) {
      const data = new Blob([this.csvText(graphData)], { type: 'text/plain' });
      return window.URL.createObjectURL(data);
    },
274
    // TODO: BEGIN, Duplicated code with panel_type until feature flag is removed
275
    // Issue number: https://gitlab.com/gitlab-org/gitlab-foss/issues/63845
276
277
278
279
280
281
282
    getGraphAlerts(queries) {
      if (!this.allAlerts) return {};
      const metricIdsForChart = queries.map(q => q.metricId);
      return _.pick(this.allAlerts, alert => metricIdsForChart.includes(alert.metricId));
    },
    getGraphAlertValues(queries) {
      return Object.values(this.getGraphAlerts(queries));
283
    },
284
    showToast() {
285
      this.$toast.show(__('Link copied'));
286
    },
287
    // TODO: END
288
289
290
291
292
    removeGraph(metrics, graphIndex) {
      // At present graphs will not be removed, they should removed using the vuex store
      // See https://gitlab.com/gitlab-org/gitlab/issues/27835
      metrics.splice(graphIndex, 1);
    },
293
294
    generateLink(group, title, yLabel) {
      const dashboard = this.currentDashboard || this.firstDashboard.path;
295
      const params = _.pick({ dashboard, group, title, y_label: yLabel }, value => value != null);
296
297
      return mergeUrlParams(params, window.location.href);
    },
298
299
300
    hideAddMetricModal() {
      this.$refs.addMetricModal.hide();
    },
301
302
303
304
    onSidebarMutation() {
      setTimeout(() => {
        this.elWidth = this.$el.clientWidth;
      }, sidebarAnimationDuration);
Filipa Lacerda's avatar
Filipa Lacerda committed
305
    },
306
307
308
    toggleRearrangingPanels() {
      this.isRearrangingPanels = !this.isRearrangingPanels;
    },
309
310
311
312
313
314
    setFormValidity(isValid) {
      this.formIsValid = isValid;
    },
    submitCustomMetricsForm() {
      this.$refs.customMetricsForm.submit();
    },
315
316
317
    activeTimeWindow(key) {
      return this.timeWindows[key] === this.selectedTimeWindow;
    },
318
    setTimeWindowParameter(key) {
Simon Knox's avatar
Simon Knox committed
319
320
      const { start, end } = getTimeDiff(key);
      return `?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`;
321
    },
Jose Ivan Vargas's avatar
Jose Ivan Vargas committed
322
323
324
    groupHasData(group) {
      return this.chartsWithData(group.metrics).length > 0;
    },
Mike Greiling's avatar
Mike Greiling committed
325
  },
326
327
328
329
  addMetric: {
    title: s__('Metrics|Add metric'),
    modalId: 'add-metric',
  },
Mike Greiling's avatar
Mike Greiling committed
330
};
331
</script>
332

333
<template>
334
  <div class="prometheus-graphs">
335
336
337
338
339
340
341
342
    <div class="gl-p-3 pb-0 border-bottom bg-gray-light">
      <div class="row">
        <template v-if="environmentsEndpoint">
          <gl-form-group
            :label="__('Dashboard')"
            label-size="sm"
            label-for="monitor-dashboards-dropdown"
            class="col-sm-12 col-md-4 col-lg-2"
343
          >
344
345
346
347
348
            <gl-dropdown
              id="monitor-dashboards-dropdown"
              class="mb-0 d-flex js-dashboards-dropdown"
              toggle-class="dropdown-menu-toggle"
              :text="selectedDashboardText"
349
            >
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
              <gl-dropdown-item
                v-for="dashboard in allDashboards"
                :key="dashboard.path"
                :active="dashboard.path === currentDashboard"
                active-class="is-active"
                :href="`?dashboard=${dashboard.path}`"
                >{{ dashboard.display_name || dashboard.path }}</gl-dropdown-item
              >
            </gl-dropdown>
          </gl-form-group>

          <gl-form-group
            :label="s__('Metrics|Environment')"
            label-size="sm"
            label-for="monitor-environments-dropdown"
            class="col-sm-6 col-md-4 col-lg-2"
366
          >
367
368
369
370
371
372
            <gl-dropdown
              id="monitor-environments-dropdown"
              class="mb-0 d-flex js-environments-dropdown"
              toggle-class="dropdown-menu-toggle"
              :text="currentEnvironmentName"
              :disabled="environments.length === 0"
373
            >
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
              <gl-dropdown-item
                v-for="environment in environments"
                :key="environment.id"
                :active="environment.name === currentEnvironmentName"
                active-class="is-active"
                :href="environment.metrics_path"
                >{{ environment.name }}</gl-dropdown-item
              >
            </gl-dropdown>
          </gl-form-group>

          <gl-form-group
            v-if="!showEmptyState"
            :label="s__('Metrics|Show last')"
            label-size="sm"
            label-for="monitor-time-window-dropdown"
            class="col-sm-6 col-md-4 col-lg-2"
391
          >
392
393
394
395
396
            <gl-dropdown
              id="monitor-time-window-dropdown"
              class="mb-0 d-flex js-time-window-dropdown"
              toggle-class="dropdown-menu-toggle"
              :text="selectedTimeWindow"
397
            >
398
399
400
401
402
403
404
              <gl-dropdown-item
                v-for="(value, key) in timeWindows"
                :key="key"
                :active="activeTimeWindow(key)"
                :href="setTimeWindowParameter(key)"
                active-class="active"
                >{{ value }}</gl-dropdown-item
405
              >
406
407
408
409
410
            </gl-dropdown>
          </gl-form-group>
        </template>

        <gl-form-group
411
          v-if="addingMetricsAvailable || showRearrangePanelsBtn || externalDashboardUrl.length"
412
413
          label-for="prometheus-graphs-dropdown-buttons"
          class="dropdown-buttons col-lg d-lg-flex align-items-end"
414
        >
415
          <div id="prometheus-graphs-dropdown-buttons">
416
417
418
419
420
421
422
423
424
            <gl-button
              v-if="showRearrangePanelsBtn"
              :pressed="isRearrangingPanels"
              variant="default"
              class="mr-2 mt-1 js-rearrange-button"
              @click="toggleRearrangingPanels"
            >
              {{ __('Arrange charts') }}
            </gl-button>
425
426
427
            <gl-button
              v-if="addingMetricsAvailable"
              v-gl-modal="$options.addMetric.modalId"
428
429
              variant="outline-success"
              class="mr-2 mt-1 js-add-metric-button"
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
            >
              {{ $options.addMetric.title }}
            </gl-button>
            <gl-modal
              v-if="addingMetricsAvailable"
              ref="addMetricModal"
              :modal-id="$options.addMetric.modalId"
              :title="$options.addMetric.title"
            >
              <form ref="customMetricsForm" :action="customMetricsPath" method="post">
                <custom-metrics-form-fields
                  :validate-query-path="validateQueryPath"
                  form-operation="post"
                  @formValidation="setFormValidity"
                />
              </form>
              <div slot="modal-footer">
                <gl-button @click="hideAddMetricModal">{{ __('Cancel') }}</gl-button>
                <gl-button
                  :disabled="!formIsValid"
                  variant="success"
                  @click="submitCustomMetricsForm"
                >
                  {{ __('Save changes') }}
                </gl-button>
              </div>
            </gl-modal>

            <gl-button
              v-if="externalDashboardUrl.length"
              class="mt-1 js-external-dashboard-link"
              variant="primary"
              :href="externalDashboardUrl"
              target="_blank"
              rel="noopener noreferrer"
            >
              {{ __('View full dashboard') }}
              <icon name="external-link" />
            </gl-button>
          </div>
        </gl-form-group>
471
      </div>
Jose's avatar
Jose committed
472
    </div>
473

474
475
    <div v-if="!showEmptyState">
      <graph-group
Simon Knox's avatar
Simon Knox committed
476
        v-for="(groupData, index) in groups"
Tristan Read's avatar
Tristan Read committed
477
        :key="`${groupData.group}.${groupData.priority}`"
478
479
        :name="groupData.group"
        :show-panels="showPanels"
Jose Ivan Vargas's avatar
Jose Ivan Vargas committed
480
        :collapse-group="groupHasData(groupData)"
481
      >
482
        <template v-if="additionalPanelTypesEnabled">
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
          <vue-draggable
            :list="groupData.metrics"
            group="metrics-dashboard"
            :component-data="{ attrs: { class: 'row mx-0 w-100' } }"
            :disabled="!isRearrangingPanels"
          >
            <div
              v-for="(graphData, graphIndex) in groupData.metrics"
              :key="`panel-type-${graphIndex}`"
              class="col-12 col-lg-6 px-2 mb-2 draggable"
              :class="{ 'draggable-enabled': isRearrangingPanels }"
            >
              <div class="position-relative draggable-panel js-draggable-panel">
                <div
                  v-if="isRearrangingPanels"
                  class="draggable-remove js-draggable-remove p-2 w-100 position-absolute d-flex justify-content-end"
                  @click="removeGraph(groupData.metrics, graphIndex)"
                >
                  <a class="mx-2 p-2 draggable-remove-link" :aria-label="__('Remove')"
                    ><icon name="close"
                  /></a>
                </div>

                <panel-type
                  :clipboard-text="
                    generateLink(groupData.group, graphData.title, graphData.y_label)
                  "
                  :graph-data="graphData"
                  :dashboard-width="elWidth"
                  :alerts-endpoint="alertsEndpoint"
                  :prometheus-alerts-available="prometheusAlertsAvailable"
                  :index="`${index}-${graphIndex}`"
                />
              </div>
            </div>
          </vue-draggable>
519
520
        </template>
        <template v-else>
521
          <monitor-time-series-chart
522
523
            v-for="(graphData, graphIndex) in chartsWithData(groupData.metrics)"
            :key="graphIndex"
524
            class="col-12 col-lg-6 pb-3"
525
526
527
528
529
            :graph-data="graphData"
            :deployment-data="deploymentData"
            :thresholds="getGraphAlertValues(graphData.queries)"
            :container-width="elWidth"
            :project-path="projectPath"
530
            group-id="monitor-time-series-chart"
531
          >
532
533
534
535
            <div
              class="d-flex align-items-center"
              :class="alertWidgetAvailable ? 'justify-content-between' : 'justify-content-end'"
            >
536
537
538
539
540
541
542
543
544
545
              <alert-widget
                v-if="alertWidgetAvailable && graphData"
                :modal-id="`alert-modal-${index}-${graphIndex}`"
                :alerts-endpoint="alertsEndpoint"
                :relevant-queries="graphData.queries"
                :alerts-to-manage="getGraphAlerts(graphData.queries)"
                @setAlerts="setAlerts"
              />
              <gl-dropdown
                v-gl-tooltip
546
                class="ml-2 mr-3"
547
548
549
550
551
552
553
554
                toggle-class="btn btn-transparent border-0"
                :right="true"
                :no-caret="true"
                :title="__('More actions')"
              >
                <template slot="button-content">
                  <icon name="ellipsis_v" class="text-secondary" />
                </template>
555
556
557
                <gl-dropdown-item :href="downloadCsv(graphData)" download="chart_metrics.csv">
                  {{ __('Download CSV') }}
                </gl-dropdown-item>
558
559
560
561
562
563
564
565
566
                <gl-dropdown-item
                  class="js-chart-link"
                  :data-clipboard-text="
                    generateLink(groupData.group, graphData.title, graphData.y_label)
                  "
                  @click="showToast"
                >
                  {{ __('Generate link to chart') }}
                </gl-dropdown-item>
567
568
569
570
571
572
573
574
                <gl-dropdown-item
                  v-if="alertWidgetAvailable"
                  v-gl-modal="`alert-modal-${index}-${graphIndex}`"
                >
                  {{ __('Alerts') }}
                </gl-dropdown-item>
              </gl-dropdown>
            </div>
575
          </monitor-time-series-chart>
576
        </template>
577
578
579
580
581
582
583
584
585
586
587
588
      </graph-group>
    </div>
    <empty-state
      v-else
      :selected-state="emptyState"
      :documentation-path="documentationPath"
      :settings-path="settingsPath"
      :clusters-path="clustersPath"
      :empty-getting-started-svg-path="emptyGettingStartedSvgPath"
      :empty-loading-svg-path="emptyLoadingSvgPath"
      :empty-no-data-svg-path="emptyNoDataSvgPath"
      :empty-unable-to-connect-svg-path="emptyUnableToConnectSvgPath"
589
      :compact="smallEmptyState"
590
    />
591
592
  </div>
</template>