Read about our upcoming Code of Conduct on this issue

dashboard.vue 17.4 KB
Newer Older
1
<script>
2
import { debounce, pickBy } from 'lodash';
3
import { mapActions, mapState, mapGetters } from 'vuex';
4
import VueDraggable from 'vuedraggable';
5
6
7
8
import {
  GlButton,
  GlDropdown,
  GlDropdownItem,
9
  GlFormGroup,
10
  GlModal,
11
  GlSearchBoxByType,
12
13
14
  GlModalDirective,
  GlTooltipDirective,
} from '@gitlab/ui';
15
import PanelType from 'ee_else_ce/monitoring/components/panel_type.vue';
16
import { s__ } from '~/locale';
17
import createFlash from '~/flash';
18
import glFeatureFlagsMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
19
import { getParameterValues, mergeUrlParams, redirectTo } from '~/lib/utils/url_utility';
20
import invalidUrl from '~/lib/utils/invalid_url';
21
22
23
import Icon from '~/vue_shared/components/icon.vue';
import { getTimeRange } from '~/vue_shared/components/date_time_picker/date_time_picker_lib';
import DateTimePicker from '~/vue_shared/components/date_time_picker/date_time_picker.vue';
24

Mike Greiling's avatar
Mike Greiling committed
25
26
import GraphGroup from './graph_group.vue';
import EmptyState from './empty_state.vue';
27
import GroupEmptyState from './group_empty_state.vue';
28
29
import DashboardsDropdown from './dashboards_dropdown.vue';

30
import TrackEventDirective from '~/vue_shared/directives/track_event';
31
import { getAddMetricTrackingOptions } from '../utils';
32

33
34
import { datePickerTimeWindows, metricStates } from '../constants';

35
const defaultTimeRange = getTimeRange();
36

Mike Greiling's avatar
Mike Greiling committed
37
38
export default {
  components: {
39
    VueDraggable,
40
    PanelType,
41
    Icon,
Adriel Santiago's avatar
Adriel Santiago committed
42
    GlButton,
43
44
    GlDropdown,
    GlDropdownItem,
45
    GlSearchBoxByType,
46
    GlFormGroup,
47
    GlModal,
48

49
    DateTimePicker,
50
51
52
53
    GraphGroup,
    EmptyState,
    GroupEmptyState,
    DashboardsDropdown,
54
55
  },
  directives: {
56
57
    GlModal: GlModalDirective,
    GlTooltip: GlTooltipDirective,
58
    TrackEvent: TrackEventDirective,
Mike Greiling's avatar
Mike Greiling committed
59
  },
60
  mixins: [glFeatureFlagsMixin()],
Mike Greiling's avatar
Mike Greiling committed
61
  props: {
62
    externalDashboardUrl: {
Adriel Santiago's avatar
Adriel Santiago committed
63
64
65
66
      type: String,
      required: false,
      default: '',
    },
Mike Greiling's avatar
Mike Greiling committed
67
68
69
70
    hasMetrics: {
      type: Boolean,
      required: false,
      default: true,
Filipa Lacerda's avatar
Filipa Lacerda committed
71
    },
72
73
74
75
76
    showHeader: {
      type: Boolean,
      required: false,
      default: true,
    },
Mike Greiling's avatar
Mike Greiling committed
77
78
79
80
    showPanels: {
      type: Boolean,
      required: false,
      default: true,
81
    },
Mike Greiling's avatar
Mike Greiling committed
82
83
84
    documentationPath: {
      type: String,
      required: true,
85
    },
Mike Greiling's avatar
Mike Greiling committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    settingsPath: {
      type: String,
      required: true,
    },
    clustersPath: {
      type: String,
      required: true,
    },
    tagsPath: {
      type: String,
      required: true,
    },
    projectPath: {
      type: String,
      required: true,
    },
102
103
104
105
    defaultBranch: {
      type: String,
      required: true,
    },
Mike Greiling's avatar
Mike Greiling committed
106
107
108
109
    metricsEndpoint: {
      type: String,
      required: true,
    },
110
    deploymentsEndpoint: {
Mike Greiling's avatar
Mike Greiling committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
      type: String,
      required: false,
      default: null,
    },
    emptyGettingStartedSvgPath: {
      type: String,
      required: true,
    },
    emptyLoadingSvgPath: {
      type: String,
      required: true,
    },
    emptyNoDataSvgPath: {
      type: String,
      required: true,
    },
127
128
129
130
    emptyNoDataSmallSvgPath: {
      type: String,
      required: true,
    },
Mike Greiling's avatar
Mike Greiling committed
131
132
133
134
    emptyUnableToConnectSvgPath: {
      type: String,
      required: true,
    },
135
136
137
138
    currentEnvironmentName: {
      type: String,
      required: true,
    },
139
140
141
142
143
144
145
    customMetricsAvailable: {
      type: Boolean,
      required: false,
      default: false,
    },
    customMetricsPath: {
      type: String,
146
147
      required: false,
      default: invalidUrl,
148
149
150
    },
    validateQueryPath: {
      type: String,
151
152
      required: false,
      default: invalidUrl,
153
    },
154
155
156
157
158
    dashboardEndpoint: {
      type: String,
      required: false,
      default: invalidUrl,
    },
159
160
161
162
163
    dashboardsEndpoint: {
      type: String,
      required: false,
      default: invalidUrl,
    },
164
165
166
167
168
    currentDashboard: {
      type: String,
      required: false,
      default: '',
    },
169
170
171
172
173
    smallEmptyState: {
      type: Boolean,
      required: false,
      default: false,
    },
174
175
176
177
178
179
180
181
182
183
    alertsEndpoint: {
      type: String,
      required: false,
      default: null,
    },
    prometheusAlertsAvailable: {
      type: Boolean,
      required: false,
      default: false,
    },
184
185
186
187
188
    rearrangePanelsAvailable: {
      type: Boolean,
      required: false,
      default: false,
    },
Mike Greiling's avatar
Mike Greiling committed
189
190
191
192
  },
  data() {
    return {
      state: 'gettingStarted',
193
      formIsValid: null,
194
195
      startDate: getParameterValues('start')[0] || defaultTimeRange.start,
      endDate: getParameterValues('end')[0] || defaultTimeRange.end,
196
      hasValidDates: true,
197
      datePickerTimeWindows,
198
      isRearrangingPanels: false,
Mike Greiling's avatar
Mike Greiling committed
199
200
    };
  },
201
202
203
204
  computed: {
    canAddMetrics() {
      return this.customMetricsAvailable && this.customMetricsPath.length;
    },
205
    ...mapState('monitoringDashboard', [
206
      'dashboard',
207
208
209
      'emptyState',
      'showEmptyState',
      'deploymentData',
210
      'useDashboardEndpoint',
211
      'allDashboards',
212
      'additionalPanelTypesEnabled',
213
    ]),
214
    ...mapGetters('monitoringDashboard', ['getMetricStates', 'filteredEnvironments']),
215
    firstDashboard() {
216
      return this.allDashboards.length > 0 ? this.allDashboards[0] : {};
217
    },
218
219
220
    selectedDashboard() {
      return this.allDashboards.find(d => d.path === this.currentDashboard) || this.firstDashboard;
    },
221
222
223
    showRearrangePanelsBtn() {
      return !this.showEmptyState && this.rearrangePanelsAvailable;
    },
224
225
226
    addingMetricsAvailable() {
      return IS_EE && this.canAddMetrics && !this.showEmptyState;
    },
227
228
229
230
231
232
233
234
    hasHeaderButtons() {
      return (
        this.addingMetricsAvailable ||
        this.showRearrangePanelsBtn ||
        this.selectedDashboard.can_edit ||
        this.externalDashboardUrl.length
      );
    },
235
236
237
    shouldRenderSearchableEnvironmentsDropdown() {
      return this.glFeatures.searchableEnvironmentsDropdown;
    },
238
  },
Mike Greiling's avatar
Mike Greiling committed
239
  created() {
240
    this.setEndpoints({
Mike Greiling's avatar
Mike Greiling committed
241
      metricsEndpoint: this.metricsEndpoint,
242
      deploymentsEndpoint: this.deploymentsEndpoint,
243
      dashboardEndpoint: this.dashboardEndpoint,
244
      dashboardsEndpoint: this.dashboardsEndpoint,
245
      currentDashboard: this.currentDashboard,
246
      projectPath: this.projectPath,
Mike Greiling's avatar
Mike Greiling committed
247
248
249
250
    });
  },
  mounted() {
    if (!this.hasMetrics) {
251
      this.setGettingStartedEmptyState();
Mike Greiling's avatar
Mike Greiling committed
252
    } else {
253
254
255
256
      this.fetchData({
        start: this.startDate,
        end: this.endDate,
      });
Mike Greiling's avatar
Mike Greiling committed
257
258
259
    }
  },
  methods: {
260
261
262
263
    ...mapActions('monitoringDashboard', [
      'fetchData',
      'setGettingStartedEmptyState',
      'setEndpoints',
264
      'setPanelGroupMetrics',
265
      'setEnvironmentsSearchTerm',
266
    ]),
267
    updatePanels(key, panels) {
268
      this.setPanelGroupMetrics({
269
        panels,
270
271
272
        key,
      });
    },
273
    removePanel(key, panels, graphIndex) {
274
      this.setPanelGroupMetrics({
275
        panels: panels.filter((v, i) => i !== graphIndex),
276
277
        key,
      });
278
    },
279
280
281
282
283
284
285
286
287
288

    onDateTimePickerApply(params) {
      redirectTo(mergeUrlParams(params, window.location.href));
    },
    onDateTimePickerInvalid() {
      createFlash(
        s__(
          'Metrics|Link contains an invalid time window, please verify the link to see the requested time range.',
        ),
      );
289
290
      this.startDate = defaultTimeRange.start;
      this.endDate = defaultTimeRange.end;
291
    },
292

293
294
    generateLink(group, title, yLabel) {
      const dashboard = this.currentDashboard || this.firstDashboard.path;
295
      const params = pickBy({ 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
    toggleRearrangingPanels() {
      this.isRearrangingPanels = !this.isRearrangingPanels;
    },
304
305
306
    setFormValidity(isValid) {
      this.formIsValid = isValid;
    },
307
    debouncedEnvironmentsSearch: debounce(function environmentsSearchOnInput(searchTerm) {
308
309
      this.setEnvironmentsSearchTerm(searchTerm);
    }, 500),
310
311
312
    submitCustomMetricsForm() {
      this.$refs.customMetricsForm.submit();
    },
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
    /**
     * Return a single empty state for a group.
     *
     * If all states are the same a single state is returned to be displayed
     * Except if the state is OK, in which case the group is displayed.
     *
     * @param {String} groupKey - Identifier for group
     * @returns {String} state code from `metricStates`
     */
    groupSingleEmptyState(groupKey) {
      const states = this.getMetricStates(groupKey);
      if (states.length === 1 && states[0] !== metricStates.OK) {
        return states[0];
      }
      return null;
    },
    /**
     * A group should be not collapsed if any metric is loaded (OK)
     *
     * @param {String} groupKey - Identifier for group
     * @returns {Boolean} If the group should be collapsed
     */
    collapseGroup(groupKey) {
      // Collapse group if no data is available
      return !this.getMetricStates(groupKey).includes(metricStates.OK);
    },
339
    getAddMetricTrackingOptions,
340
341
342
343
344
345
346

    selectDashboard(dashboard) {
      const params = {
        dashboard: dashboard.path,
      };
      redirectTo(mergeUrlParams(params, window.location.href));
    },
Mike Greiling's avatar
Mike Greiling committed
347
  },
348
349
350
351
  addMetric: {
    title: s__('Metrics|Add metric'),
    modalId: 'add-metric',
  },
Mike Greiling's avatar
Mike Greiling committed
352
};
353
</script>
354

355
<template>
356
  <div class="prometheus-graphs">
357
358
359
360
361
    <div
      v-if="showHeader"
      ref="prometheusGraphsHeader"
      class="prometheus-graphs-header gl-p-3 pb-0 border-bottom bg-gray-light"
    >
362
      <div class="row">
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
        <gl-form-group
          :label="__('Dashboard')"
          label-size="sm"
          label-for="monitor-dashboards-dropdown"
          class="col-sm-12 col-md-6 col-lg-2"
        >
          <dashboards-dropdown
            id="monitor-dashboards-dropdown"
            class="mb-0 d-flex"
            toggle-class="dropdown-menu-toggle"
            :default-branch="defaultBranch"
            :selected-dashboard="selectedDashboard"
            @selectDashboard="selectDashboard($event)"
          />
        </gl-form-group>
378

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
        <gl-form-group
          :label="s__('Metrics|Environment')"
          label-size="sm"
          label-for="monitor-environments-dropdown"
          class="col-sm-6 col-md-6 col-lg-2"
        >
          <gl-dropdown
            id="monitor-environments-dropdown"
            ref="monitorEnvironmentsDropdown"
            data-qa-selector="environments_dropdown"
            class="mb-0 d-flex"
            toggle-class="dropdown-menu-toggle"
            menu-class="monitor-environment-dropdown-menu"
            :text="currentEnvironmentName"
            :disabled="filteredEnvironments.length === 0"
394
          >
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
            <div class="d-flex flex-column overflow-hidden">
              <gl-search-box-by-type
                v-if="shouldRenderSearchableEnvironmentsDropdown"
                ref="monitorEnvironmentsDropdownSearch"
                class="m-2"
                @input="debouncedEnvironmentsSearch"
              />
              <div class="flex-fill overflow-auto">
                <gl-dropdown-item
                  v-for="environment in filteredEnvironments"
                  :key="environment.id"
                  :active="environment.name === currentEnvironmentName"
                  active-class="is-active"
                  :href="environment.metrics_path"
                  >{{ environment.name }}</gl-dropdown-item
410
411
                >
              </div>
412
413
414
415
416
417
418
419
420
421
422
              <div
                v-if="shouldRenderSearchableEnvironmentsDropdown"
                v-show="filteredEnvironments.length === 0"
                ref="monitorEnvironmentsDropdownMsg"
                class="text-secondary no-matches-message"
              >
                {{ s__('No matching results') }}
              </div>
            </div>
          </gl-dropdown>
        </gl-form-group>
423

424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        <gl-form-group
          :label="s__('Metrics|Show last')"
          label-size="sm"
          label-for="monitor-time-window-dropdown"
          class="col-sm-6 col-md-6 col-lg-4"
        >
          <date-time-picker
            ref="dateTimePicker"
            :start="startDate"
            :end="endDate"
            :time-windows="datePickerTimeWindows"
            @apply="onDateTimePickerApply"
            @invalid="onDateTimePickerInvalid"
          />
        </gl-form-group>
439
440

        <gl-form-group
441
          v-if="hasHeaderButtons"
442
          label-for="prometheus-graphs-dropdown-buttons"
443
          class="dropdown-buttons col-md d-md-flex col-lg d-lg-flex align-items-end"
444
        >
445
          <div id="prometheus-graphs-dropdown-buttons">
446
447
448
449
450
451
            <gl-button
              v-if="showRearrangePanelsBtn"
              :pressed="isRearrangingPanels"
              variant="default"
              class="mr-2 mt-1 js-rearrange-button"
              @click="toggleRearrangingPanels"
452
              >{{ __('Arrange charts') }}</gl-button
453
            >
454
455
            <gl-button
              v-if="addingMetricsAvailable"
456
              ref="addMetricBtn"
457
              v-gl-modal="$options.addMetric.modalId"
458
              variant="outline-success"
459
              class="mr-2 mt-1"
460
              >{{ $options.addMetric.title }}</gl-button
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
            >
            <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
478
479
                  ref="submitCustomMetricsFormBtn"
                  v-track-event="getAddMetricTrackingOptions()"
480
481
482
                  :disabled="!formIsValid"
                  variant="success"
                  @click="submitCustomMetricsForm"
483
                  >{{ __('Save changes') }}</gl-button
484
485
486
487
                >
              </div>
            </gl-modal>

488
489
490
491
            <gl-button
              v-if="selectedDashboard.can_edit"
              class="mt-1 js-edit-link"
              :href="selectedDashboard.project_blob_path"
492
              >{{ __('Edit dashboard') }}</gl-button
493
494
            >

495
496
497
498
499
500
501
502
503
504
505
506
507
            <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>
508
      </div>
Jose's avatar
Jose committed
509
    </div>
510

511
512
    <div v-if="!showEmptyState">
      <graph-group
513
        v-for="(groupData, index) in dashboard.panel_groups"
Tristan Read's avatar
Tristan Read committed
514
        :key="`${groupData.group}.${groupData.priority}`"
515
516
        :name="groupData.group"
        :show-panels="showPanels"
517
        :collapse-group="collapseGroup(groupData.key)"
518
      >
519
        <div v-if="!groupSingleEmptyState(groupData.key)">
520
521
522
523
524
525
          <vue-draggable
            :value="groupData.panels"
            group="metrics-dashboard"
            :component-data="{ attrs: { class: 'row mx-0 w-100' } }"
            :disabled="!isRearrangingPanels"
            @input="updatePanels(groupData.key, $event)"
526
          >
527
528
529
530
531
532
533
534
535
536
537
538
            <div
              v-for="(graphData, graphIndex) in groupData.panels"
              :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="removePanel(groupData.key, groupData.panels, graphIndex)"
                >
539
540
541
                  <a class="mx-2 p-2 draggable-remove-link" :aria-label="__('Remove')">
                    <icon name="close" />
                  </a>
542
                </div>
543

544
545
546
547
548
549
550
551
552
553
                <panel-type
                  :clipboard-text="
                    generateLink(groupData.group, graphData.title, graphData.y_label)
                  "
                  :graph-data="graphData"
                  :alerts-endpoint="alertsEndpoint"
                  :prometheus-alerts-available="prometheusAlertsAvailable"
                  :index="`${index}-${graphIndex}`"
                />
              </div>
554
            </div>
555
556
557
          </vue-draggable>
        </div>
        <div v-else class="py-5 col col-sm-10 col-md-8 col-lg-7 col-xl-6">
558
          <group-empty-state
559
560
561
            ref="empty-group"
            :documentation-path="documentationPath"
            :settings-path="settingsPath"
562
563
            :selected-state="groupSingleEmptyState(groupData.key)"
            :svg-path="emptyNoDataSmallSvgPath"
564
565
          />
        </div>
566
567
568
569
570
571
572
573
574
575
576
      </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"
577
      :empty-no-data-small-svg-path="emptyNoDataSmallSvgPath"
578
      :empty-unable-to-connect-svg-path="emptyUnableToConnectSvgPath"
579
      :compact="smallEmptyState"
580
    />
581
582
  </div>
</template>