summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/clusters_list/components/clusters.vue
blob: f8fb58cdca2d5ccdb2acda704e9ce9658406541f (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
<script>
import { mapState, mapActions } from 'vuex';
import {
  GlDeprecatedBadge as GlBadge,
  GlLink,
  GlLoadingIcon,
  GlPagination,
  GlDeprecatedSkeletonLoading as GlSkeletonLoading,
  GlSprintf,
  GlTable,
} from '@gitlab/ui';
import AncestorNotice from './ancestor_notice.vue';
import NodeErrorHelpText from './node_error_help_text.vue';
import tooltip from '~/vue_shared/directives/tooltip';
import { CLUSTER_TYPES, STATUSES } from '../constants';
import { __, sprintf } from '~/locale';

export default {
  nodeMemoryText: __('%{totalMemory} (%{freeSpacePercentage}%{percentSymbol} free)'),
  nodeCpuText: __('%{totalCpu} (%{freeSpacePercentage}%{percentSymbol} free)'),
  components: {
    AncestorNotice,
    GlBadge,
    GlLink,
    GlLoadingIcon,
    GlPagination,
    GlSkeletonLoading,
    GlSprintf,
    GlTable,
    NodeErrorHelpText,
  },
  directives: {
    tooltip,
  },
  computed: {
    ...mapState([
      'clusters',
      'clustersPerPage',
      'loadingClusters',
      'loadingNodes',
      'page',
      'providers',
      'totalCulsters',
    ]),
    contentAlignClasses() {
      return 'gl-display-flex gl-align-items-center gl-justify-content-end gl-justify-content-md-start';
    },
    currentPage: {
      get() {
        return this.page;
      },
      set(newVal) {
        this.setPage(newVal);
        this.fetchClusters();
      },
    },
    fields() {
      return [
        {
          key: 'name',
          label: __('Kubernetes cluster'),
        },
        {
          key: 'environment_scope',
          label: __('Environment scope'),
        },
        {
          key: 'node_size',
          label: __('Nodes'),
        },
        {
          key: 'total_cpu',
          label: __('Total cores (CPUs)'),
        },
        {
          key: 'total_memory',
          label: __('Total memory (GB)'),
        },
        {
          key: 'cluster_type',
          label: __('Cluster level'),
          formatter: value => CLUSTER_TYPES[value],
        },
      ];
    },
    hasClusters() {
      return this.clustersPerPage > 0;
    },
  },
  mounted() {
    this.fetchClusters();
  },
  methods: {
    ...mapActions(['fetchClusters', 'reportSentryError', 'setPage']),
    k8sQuantityToGb(quantity) {
      if (!quantity) {
        return 0;
      } else if (quantity.endsWith(__('Ki'))) {
        return parseInt(quantity.substr(0, quantity.length - 2), 10) * 0.000001024;
      } else if (quantity.endsWith(__('Mi'))) {
        return parseInt(quantity.substr(0, quantity.length - 2), 10) * 0.001048576;
      }

      // We are trying to track quantity types coming from Kubernetes.
      // Sentry will notify us if we are missing types.
      throw new Error(`UnknownK8sMemoryQuantity:${quantity}`);
    },
    k8sQuantityToCpu(quantity) {
      if (!quantity) {
        return 0;
      } else if (quantity.endsWith('m')) {
        return parseInt(quantity.substr(0, quantity.length - 1), 10) / 1000.0;
      } else if (quantity.endsWith('n')) {
        return parseInt(quantity.substr(0, quantity.length - 1), 10) / 1000000000.0;
      }

      // We are trying to track quantity types coming from Kubernetes.
      // Sentry will notify us if we are missing types.
      throw new Error(`UnknownK8sCpuQuantity:${quantity}`);
    },
    selectedProvider(provider) {
      return this.providers[provider] || this.providers.default;
    },
    statusTitle(status) {
      const iconTitle = STATUSES[status] || STATUSES.default;
      return sprintf(__('Status: %{title}'), { title: iconTitle.title }, false);
    },
    totalMemoryAndUsage(nodes) {
      try {
        // For EKS node.usage will not be present unless the user manually
        // install the metrics server
        if (nodes && nodes[0].usage) {
          let totalAllocatableMemory = 0;
          let totalUsedMemory = 0;

          nodes.reduce((total, node) => {
            const allocatableMemoryQuantity = node.status.allocatable.memory;
            const allocatableMemoryGb = this.k8sQuantityToGb(allocatableMemoryQuantity);
            totalAllocatableMemory += allocatableMemoryGb;

            const usedMemoryQuantity = node.usage.memory;
            const usedMemoryGb = this.k8sQuantityToGb(usedMemoryQuantity);
            totalUsedMemory += usedMemoryGb;

            return null;
          }, 0);

          const freeSpacePercentage = (1 - totalUsedMemory / totalAllocatableMemory) * 100;

          return {
            totalMemory: totalAllocatableMemory.toFixed(2),
            freeSpacePercentage: Math.round(freeSpacePercentage),
          };
        }
      } catch (error) {
        this.reportSentryError({ error, tag: 'totalMemoryAndUsageError' });
      }

      return { totalMemory: null, freeSpacePercentage: null };
    },
    totalCpuAndUsage(nodes) {
      try {
        // For EKS node.usage will not be present unless the user manually
        // install the metrics server
        if (nodes && nodes[0].usage) {
          let totalAllocatableCpu = 0;
          let totalUsedCpu = 0;

          nodes.reduce((total, node) => {
            const allocatableCpuQuantity = node.status.allocatable.cpu;
            const allocatableCpu = this.k8sQuantityToCpu(allocatableCpuQuantity);
            totalAllocatableCpu += allocatableCpu;

            const usedCpuQuantity = node.usage.cpu;
            const usedCpuGb = this.k8sQuantityToCpu(usedCpuQuantity);
            totalUsedCpu += usedCpuGb;

            return null;
          }, 0);

          const freeSpacePercentage = (1 - totalUsedCpu / totalAllocatableCpu) * 100;

          return {
            totalCpu: totalAllocatableCpu.toFixed(2),
            freeSpacePercentage: Math.round(freeSpacePercentage),
          };
        }
      } catch (error) {
        this.reportSentryError({ error, tag: 'totalCpuAndUsageError' });
      }

      return { totalCpu: null, freeSpacePercentage: null };
    },
  },
};
</script>

<template>
  <gl-loading-icon v-if="loadingClusters" size="md" class="gl-mt-3" />

  <section v-else>
    <ancestor-notice />

    <gl-table
      :items="clusters"
      :fields="fields"
      stacked="md"
      class="qa-clusters-table"
      data-testid="cluster_list_table"
    >
      <template #cell(name)="{ item }">
        <div :class="[contentAlignClasses, 'js-status']">
          <img
            :src="selectedProvider(item.provider_type).path"
            :alt="selectedProvider(item.provider_type).text"
            class="gl-w-6 gl-h-6 gl-display-flex gl-align-items-center"
          />

          <gl-link
            data-qa-selector="cluster"
            :data-qa-cluster-name="item.name"
            :href="item.path"
            class="gl-px-3"
          >
            {{ item.name }}
          </gl-link>

          <gl-loading-icon
            v-if="item.status === 'deleting' || item.status === 'creating'"
            v-tooltip
            :title="statusTitle(item.status)"
            size="sm"
          />
        </div>
      </template>

      <template #cell(node_size)="{ item }">
        <span v-if="item.nodes">{{ item.nodes.length }}</span>

        <gl-skeleton-loading v-else-if="loadingNodes" :lines="1" :class="contentAlignClasses" />

        <NodeErrorHelpText
          v-else-if="item.kubernetes_errors"
          :class="contentAlignClasses"
          :error-type="item.kubernetes_errors.connection_error"
          :popover-id="`nodeSizeError${item.id}`"
        />
      </template>

      <template #cell(total_cpu)="{ item }">
        <span v-if="item.nodes">
          <gl-sprintf :message="$options.nodeCpuText">
            <template #totalCpu>{{ totalCpuAndUsage(item.nodes).totalCpu }}</template>
            <template #freeSpacePercentage>{{
              totalCpuAndUsage(item.nodes).freeSpacePercentage
            }}</template>
            <template #percentSymbol
              >%</template
            >
          </gl-sprintf>
        </span>

        <gl-skeleton-loading v-else-if="loadingNodes" :lines="1" :class="contentAlignClasses" />

        <NodeErrorHelpText
          v-else-if="item.kubernetes_errors"
          :class="contentAlignClasses"
          :error-type="item.kubernetes_errors.node_connection_error"
          :popover-id="`nodeCpuError${item.id}`"
        />
      </template>

      <template #cell(total_memory)="{ item }">
        <span v-if="item.nodes">
          <gl-sprintf :message="$options.nodeMemoryText">
            <template #totalMemory>{{ totalMemoryAndUsage(item.nodes).totalMemory }}</template>
            <template #freeSpacePercentage>{{
              totalMemoryAndUsage(item.nodes).freeSpacePercentage
            }}</template>
            <template #percentSymbol
              >%</template
            >
          </gl-sprintf>
        </span>

        <gl-skeleton-loading v-else-if="loadingNodes" :lines="1" :class="contentAlignClasses" />

        <NodeErrorHelpText
          v-else-if="item.kubernetes_errors"
          :class="contentAlignClasses"
          :error-type="item.kubernetes_errors.metrics_connection_error"
          :popover-id="`nodeMemoryError${item.id}`"
        />
      </template>

      <template #cell(cluster_type)="{value}">
        <gl-badge variant="light">
          {{ value }}
        </gl-badge>
      </template>
    </gl-table>

    <gl-pagination
      v-if="hasClusters"
      v-model="currentPage"
      :per-page="clustersPerPage"
      :total-items="totalCulsters"
      :prev-text="__('Prev')"
      :next-text="__('Next')"
      align="center"
    />
  </section>
</template>