forked from rancher/dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1335 lines (1061 loc) · 40.9 KB
/
index.js
File metadata and controls
1335 lines (1061 loc) · 40.9 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
471
472
473
474
475
476
477
478
479
480
481
482
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BACK_TO } from '@shell/config/local-storage';
import { setBrand, setVendor } from '@shell/config/private-label';
import { NAME as EXPLORER } from '@shell/config/product/explorer';
import {
LOGGED_OUT, IS_SSO, IS_SLO, TIMED_OUT, UPGRADED, _FLAGGED, IS_SESSION_IDLE
} from '@shell/config/query-params';
import { SETTING } from '@shell/config/settings';
import {
COUNT,
DEFAULT_WORKSPACE,
FLEET,
MANAGEMENT,
NAMESPACE, NORMAN,
UI, VIRTUAL_HARVESTER_PROVIDER, HCI
} from '@shell/config/types';
import { BY_TYPE } from '@shell/plugins/dashboard-store/classify';
import Steve from '@shell/plugins/steve';
import { STEVE_MODEL_TYPES } from '@shell/plugins/steve/getters';
import { CLUSTER as CLUSTER_PREF, LAST_NAMESPACE, NAMESPACE_FILTERS, WORKSPACE } from '@shell/store/prefs';
import { BOTH, CLUSTER_LEVEL, NAMESPACED } from '@shell/store/type-map';
import { filterBy, findBy } from '@shell/utils/array';
import { ApiError, ClusterNotFoundError } from '@shell/utils/error';
import { gcActions, gcGetters } from '@shell/utils/gc/gc-root-store';
import {
NAMESPACE_FILTER_ALL_ORPHANS as ALL_ORPHANS,
NAMESPACE_FILTER_ALL_SYSTEM as ALL_SYSTEM,
NAMESPACE_FILTER_ALL_USER as ALL_USER,
NAMESPACE_FILTER_NAMESPACED_NO as NAMESPACED_NO,
NAMESPACE_FILTER_NAMESPACED_PREFIX as NAMESPACED_PREFIX,
NAMESPACE_FILTER_NAMESPACED_YES as NAMESPACED_YES,
splitNamespaceFilterKey,
NAMESPACE_FILTER_NS_FULL_PREFIX,
} from '@shell/utils/namespace-filter';
import { allHash, allHashSettled } from '@shell/utils/promise';
import { sortBy } from '@shell/utils/sort';
import { addParam } from '@shell/utils/url';
import semver from 'semver';
import { STORE, BLANK_CLUSTER } from '@shell/store/store-types';
import { getReleaseNotesURL } from '@shell/utils/version';
import { getVersionData } from '@shell/config/version';
import { markRaw } from 'vue';
import paginationUtils from '@shell/utils/pagination-utils';
import { addReleaseNotesNotification } from '@shell/utils/release-notes';
import sideNavService from '@shell/components/nav/TopLevelMenu.helper';
import { fetchAndProcessDynamicContent } from '@shell/utils/dynamic-content';
// Disables strict mode for all store instances to prevent warning about changing state outside of mutations
// because it's more efficient to do that sometimes.
export const strict = false;
export const plugins = [
Steve({
namespace: STORE.MANAGEMENT,
baseUrl: '/v1',
modelBaseClass: BY_TYPE,
supportsStream: false, // true, -- Disabled due to report that it's sometimes much slower in Chrome
}),
Steve({
namespace: STORE.CLUSTER,
baseUrl: '', // URL is dynamically set for the selected cluster
supportsStream: false, // true, -- Disabled due to report that it's sometimes much slower in Chrome
supportsGc: true, // Enable garbage collection for this store only
}),
Steve({
namespace: STORE.RANCHER,
baseUrl: '/v3',
supportsStream: false, // The norman API doesn't support streaming
modelBaseClass: STEVE_MODEL_TYPES.NORMAN,
}),
];
/**
* Get all the namespaces categories
* @returns Record<string, true>
*/
const getActiveNamespacesCategories = (getters, namespaces, filters) => {
// Split namespaces by category
const includeAll = getters.isAllNamespaces;
const includeSystem = filters.includes(ALL_SYSTEM);
const includeUser = filters.includes(ALL_USER);
const includeOrphans = filters.includes(ALL_ORPHANS);
// Categories to pull in all the user, system, or orphaned namespaces
const hasCategory = includeAll || includeOrphans || includeSystem || includeUser;
return hasCategory ? Object.values(namespaces).reduce((acc, ns) => {
if (
includeAll ||
(includeOrphans && !ns.projectId) ||
(includeUser && !ns.isSystem) ||
(includeSystem && ns.isSystem)
) {
acc[ns.id] = true;
}
return acc;
}, {}) : {};
};
/**
* Get handpicked namespaces from the filters
* @returns Record<string, true>
*/
const getActiveSingleNamespaces = (getters, filters) => {
const activeNamespaces = {};
// Individual cases for stacked project and/or namespace filters
if ( !getters.isAllNamespaces ) {
const clusterId = getters['currentCluster']?.id;
for ( const filter of filters ) {
const [type, id] = filter.split('://', 2);
if ( !type ) {
continue;
}
if ( type === 'ns' ) {
activeNamespaces[id] = true;
} else if (type === 'project') {
// Set all the namespaces contained in the project
const project = getters['management/byId'](MANAGEMENT.PROJECT, `${ clusterId }/${ id }`);
if ( project ) {
for ( const projectNamespace of project.namespaces ) {
activeNamespaces[projectNamespace.id] = true;
}
}
}
}
}
return activeNamespaces;
};
/**
* Get only namespaces for user with roles "Cluster Member" and "View All Projects"
* @returns Record<string, true>
*/
const getReadOnlyActiveNamespaces = (namespaces, activeNamespaces) => {
const readonlyNamespaces = Object
.values(namespaces)
.filter((ns) => !!ns.links.update)
.map(({ id }) => id);
return Object.keys(activeNamespaces)
.filter((ns) => readonlyNamespaces.includes(ns))
.reduce((acc, ns) => ({
...acc,
[ns]: true
}), {});
};
/**
* Collect all the namespaces for the current cluster grouped by category, project or single pick
* @returns Record<string, true>
*/
const getActiveNamespaces = (state, getters, readonly = false) => {
const product = getters['currentProduct'];
if ( !product ) {
return {};
}
// TODO: Add comment with logic for fleet
if ( product.showWorkspaceSwitcher ) {
const fleetOut = { [state.workspace]: true };
updateActiveNamespaceCache(state, fleetOut);
return fleetOut;
}
// Reset cache if no cluster is found or is not in store
const inStore = product?.inStore;
const clusterId = getters['currentCluster']?.id;
if ( !clusterId || !inStore ) {
updateActiveNamespaceCache(state, {});
return {};
}
// Use default "All Namespaces" category if no namespaces is found
const hasNamespaces = Array.isArray(state.allNamespaces) && state.allNamespaces.length > 0;
const allNamespaces = hasNamespaces ? state.allNamespaces : getters[`${ inStore }/all`](NAMESPACE);
const allowedNamespaces = allNamespaces
.filter((ns) => state.prefs.data['all-namespaces'] ? true : !ns.isObscure) // Filter out Rancher system namespaces
.filter((ns) => product.hideSystemResources ? !ns.isSystem : true); // Filter out Fleet system namespaces
// Retrieve all the filters selected by the user
const filters = state.namespaceFilters.filter(
(filters) => !!filters && !`${ filters }`.startsWith(NAMESPACED_PREFIX)
);
const activeNamespaces = {
...getActiveNamespacesCategories(getters, allowedNamespaces, filters),
...getActiveSingleNamespaces(getters, filters),
};
// Create map that can be used to efficiently check if a resource should be displayed
updateActiveNamespaceCache(state, activeNamespaces);
// Exclude namespaces restricted to the user for writing
if (readonly) {
return getReadOnlyActiveNamespaces(allowedNamespaces, activeNamespaces);
}
return activeNamespaces;
};
/**
* Caching side-effect while retrieving namespaces filters
*/
const updateActiveNamespaceCache = (state, activeNamespaceCache) => {
// This is going to run a lot, so keep it optimised
let cacheKey = '';
for (const key in activeNamespaceCache) {
// I thought array.join would be faster than string concatenation, but in places like this where the array must first be constructed it's
// slower.
cacheKey += key + activeNamespaceCache[key];
}
// Only update `activeNamespaceCache` if there have been changes. This reduces a lot of churn
if (state.activeNamespaceCacheKey !== cacheKey) {
state.activeNamespaceCacheKey = cacheKey;
state.activeNamespaceCache = activeNamespaceCache;
}
};
/**
* Are we in the vai enabled world where mgmt clusters are paginated?
*/
const paginateClusters = ({ rootGetters, state }) => {
return paginationUtils.isEnabled({ rootGetters, $extension: state.$extension }, { store: 'management', resource: { id: MANAGEMENT.CLUSTER, context: 'side-bar' } });
};
export const state = () => {
return {
managementReady: false,
clusterReady: false,
isRancher: false,
namespaceFilters: [],
activeNamespaceCache: {}, // Used to efficiently check if a resource should be displayed
activeNamespaceCacheKey: '', // Fingerprint of activeNamespaceCache
allNamespaces: [],
allWorkspaces: [],
clusterId: null,
productId: null,
workspace: null,
error: null,
cameFromError: false,
pageActions: [],
pageActionHandler: null,
serverVersion: null,
systemNamespaces: [],
isSingleProduct: undefined,
isRancherInHarvester: false,
targetRoute: null,
rootProduct: undefined,
$router: markRaw({}),
$route: markRaw({}),
$plugin: markRaw({}),
$extension: markRaw({}),
showWorkspaceSwitcher: true,
localCluster: null,
};
};
export const getters = {
clusterReady(state) {
return state.clusterReady === true;
},
/**
* Cache of the mgmt cluster fetched at start up
*
* We cannot rely on the store to cache this as the store may contain a page without the local cluster
*/
localCluster(state) {
return state.localCluster;
},
isMultiCluster(state, getters) {
const clusterCount = getters['management/all'](COUNT)?.[0]?.counts?.[MANAGEMENT.CLUSTER]?.summary?.count || 0;
const localCluster = getters['localCluster'];
if (clusterCount === 1 && !!localCluster) {
return false;
} else {
return true;
}
},
isRancher(state) {
return state.isRancher === true;
},
clusterId(state) {
return state.clusterId;
},
productId(state, getters) {
return state.productId;
},
workspace(state, getters) {
return state.workspace;
},
pageActions(state) {
return state.pageActions;
},
systemNamespaces(state) {
return state.systemNamespaces;
},
currentCluster(state, getters) {
return getters['management/byId'](MANAGEMENT.CLUSTER, state.clusterId);
},
currentProduct(state, getters) {
const active = getters['type-map/activeProducts'];
let out = findBy(active, 'name', state.productId);
if ( !out ) {
out = findBy(active, 'name', EXPLORER);
}
if ( !out ) {
out = active[0];
}
return out;
},
// Get the root product - this is either the current product or the current product's root (if set)
// Used for navigation and other areas that don't want to re-evaluate when the product changes, but is still within
// a common root product
rootProduct(state) {
return state.rootProduct;
},
getStoreNameByProductId(state) {
const products = state['type-map']?.products;
return (products.find((p) => p.name === state.productId) || {})?.inStore || 'cluster';
},
currentStore(state, getters) {
return (type) => {
const product = getters['currentProduct'];
if (!product) {
return 'cluster';
}
if (type && product.typeStoreMap?.[type]) {
return product.typeStoreMap[type];
}
return product.inStore;
};
},
isExplorer(state, getters) {
const product = getters.rootProduct;
return product?.name === EXPLORER;
},
defaultClusterId(state, getters) {
const all = getters['management/all'](MANAGEMENT.CLUSTER);
const clusters = sortBy(filterBy(all, 'isReady'), 'nameDisplay');
const desired = getters['prefs/get'](CLUSTER_PREF);
if ( clusters.find((x) => x.id === desired) ) {
return desired;
} else if ( clusters.length ) {
return clusters[0].id;
}
return BLANK_CLUSTER;
},
isAllNamespaces(state, getters) {
const product = getters['currentProduct'];
if ( !product ) {
return true;
}
if ( product.showWorkspaceSwitcher ) {
return false;
}
if ( !product.showNamespaceFilter && !getters['isExplorer'] ) {
return true;
}
return state.namespaceFilters.filter((x) => !`${ x }`.startsWith(NAMESPACED_PREFIX)).length === 0;
},
isMultipleNamespaces(state, getters) {
const product = getters['currentProduct'];
if ( !product ) {
return true;
}
if ( product.showWorkspaceSwitcher ) {
return false;
}
if ( getters.isAllNamespaces ) {
return true;
}
const filters = state.namespaceFilters;
if ( filters.length !== 1 ) {
return true;
}
return !filters[0].startsWith(NAMESPACE_FILTER_NS_FULL_PREFIX);
},
/**
* Namespace/Project filter for the current cluster
*/
namespaceFilters(state) {
const filters = state.namespaceFilters.filter((x) => !!x && !`${ x }`.startsWith(NAMESPACED_PREFIX));
return filters;
},
namespaceMode(state, getters) {
const filters = state.namespaceFilters;
const product = getters['currentProduct'];
if ( !product?.showNamespaceFilter ) {
return BOTH;
}
// Explicitly asking
if ( filters.includes(NAMESPACED_YES) ) {
return NAMESPACED;
} else if ( filters.includes(NAMESPACED_NO) ) {
return CLUSTER_LEVEL;
}
const byKind = {};
for ( const filter of filters ) {
const type = filter.split('://', 2)[0];
byKind[type] = (byKind[type] || 0) + 1;
}
if ( byKind['project'] > 0 || byKind['ns'] > 0 ) {
return NAMESPACED;
}
return BOTH;
},
activeNamespaceCache(state) {
// The activeNamespaceCache value is updated by the
// updateNamespaces mutation. We use this map to filter workloads
// as we don't want to recompute the active namespaces
// for each workload in a list.
return state.activeNamespaceCache;
},
activeNamespaceCacheKey(state) {
return state.activeNamespaceCacheKey;
},
activeNamespaceFilters(state) {
return state.namespaceFilters;
},
/**
* All namespaces in the current cluster
*/
allNamespaces(state) {
return state.allNamespaces;
},
namespaces(state, getters) {
// Call this getter if you want to recompute the active namespaces
// by looping over all namespaces in a cluster. Otherwise call activeNamespaceCache,
// which returns the same object but is only recomputed when the updateNamespaces
// mutation is called.
return () => getActiveNamespaces(state, getters);
},
/**
* Return namespaces which the user can refer to create resources
* @returns Record<string, true>
*/
allowedNamespaces(state, getters) {
return () => getActiveNamespaces(state, getters, true);
},
defaultNamespace(state, getters, rootState, rootGetters) {
const product = getters['currentProduct'];
if ( !product ) {
return 'default';
}
const inStore = product.inStore;
const filteredMap = getters['activeNamespaceCache'];
const isAll = getters['isAllNamespaces'];
const all = getters[`${ inStore }/all`](NAMESPACE).map((x) => x.id);
let out;
function isOk() {
if ( !out ) {
return false;
}
return (isAll && all.includes(out) ) ||
(!isAll && filteredMap && filteredMap[out] );
}
out = rootGetters['prefs/get'](LAST_NAMESPACE);
if ( isOk() ) {
return out;
}
out = 'default';
if ( isOk() ) {
return out;
}
if ( !isAll ) {
const keys = Object.keys(filteredMap);
if ( keys.length ) {
return keys[0];
}
}
return all[0];
},
backToRancherGlobalLink(state) {
let link = '/g';
if ( process.env.dev ) {
link = `https://localhost:8000${ link }`;
}
return link;
},
backToRancherLink(state) {
const clusterId = state.clusterId;
let link = '/g';
if ( clusterId ) {
link = `/c/${ escape(clusterId) }`;
}
if ( process.env.dev ) {
link = `https://localhost:8000${ link }`;
}
return link;
},
rancherLink(getters) {
if ( process.env.dev ) {
return `https://localhost:8000/`;
}
return '/';
},
isSingleProduct(state) {
if (state.isSingleProduct !== undefined) {
return state.isSingleProduct;
}
return false;
},
isRancherInHarvester(state) {
return state.isRancherInHarvester;
},
isVirtualCluster(state, getters) {
const cluster = getters['currentCluster'];
return cluster?.status?.provider === VIRTUAL_HARVESTER_PROVIDER;
},
isStandaloneHarvester(state, getters) {
const localCluster = getters['localCluster'];
return getters['isSingleProduct'] && localCluster?.isHarvester && !getters['isRancherInHarvester'];
},
showTopLevelMenu(getters) {
return getters['isRancherInHarvester'] || getters['isMultiCluster'] || !getters['isSingleProduct'];
},
showWorkspaceSwitcher(state, getters) {
const product = getters['currentProduct'];
if (!product) {
return false;
}
return product.showWorkspaceSwitcher && state.showWorkspaceSwitcher;
},
targetRoute(state) {
return state.targetRoute;
},
releaseNotesUrl(state, getters) {
const version = getters['management/byId'](MANAGEMENT.SETTING, SETTING.VERSION_RANCHER)?.value;
const isPrime = getVersionData().RancherPrime === 'true';
return getReleaseNotesURL(isPrime, version);
},
...gcGetters
};
export const mutations = {
pageActionHandler(state, handler) {
if (handler && typeof handler === 'function') {
state.pageActionHandler = handler;
}
},
clearPageActionHandler(state) {
state.pageActionHandler = null;
},
managementChanged(state, { ready, isRancher, localCluster }) {
state.managementReady = ready;
state.isRancher = isRancher;
state.localCluster = localCluster;
},
clusterReady(state, ready) {
state.clusterReady = ready;
},
isRancherInHarvester(state, neu) {
state.isRancherInHarvester = neu;
},
/**
* Updates cluster specific ns settings, including the selected ns cache `activeNamespaceCache`
*/
updateNamespaces(state, { filters, all, getters: optGetters }) {
state.namespaceFilters = filters.filter((x) => !!x);
if ( all ) {
state.allNamespaces = all;
}
// - Create map that can be used to efficiently check if a resource should be displayed.
// - The 'getters' parameter is required to preserve compatibility with older Harvester's versions in embedded mode.
// see https://github.com/rancher/dashboard/issues/10647
getActiveNamespaces(state, optGetters || getters);
},
changeAllNamespaces(state, namespace) {
// `allNamespaces/changeAllNamespaces` allow products to restrict the namespaces shown to the user in the NamespaceFilter and NameNsDescription components.
// You can configure the `notFilterNamespace` parameter for each resource page to define namespaces that do not need to be filtered, and then change `allNamespaces` by calling `changeAllNamespaces`
// eg:
// const notFilterNamespaces = this.$store.getters[`type-map/optionsFor`](resource).notFilterNamespace || [];
// const allNamespaces = this.$store.getters[`${ this.currentProduct.inStore }/filterNamespace`](notFilterNamespaces);
state.allNamespaces = namespace;
},
pageActions(state, pageActions) {
state.pageActions = pageActions;
},
updateWorkspace(state, { value, all, getters }) {
if ( all ) {
state.allWorkspaces = all;
if ( findBy(all, 'id', value) ) {
// The value is a valid option, good
} else if ( findBy(all, 'id', DEFAULT_WORKSPACE) ) {
// How about the default
value = DEFAULT_WORKSPACE;
} else if ( all.length ) {
value = all[0].id;
}
}
state.workspace = value;
getActiveNamespaces(state, getters);
},
clusterId(state, neu) {
state.clusterId = neu;
},
setProduct(state, value) {
state.productId = value;
// Update rootProduct ONLY if the root product has changed as a result of the product change
const newProduct = this.getters['type-map/productByName'](value);
let newRootProduct = newProduct;
if (newProduct?.rootProduct) {
newRootProduct = this.getters['type-map/productByName'](newProduct.rootProduct) || newProduct;
}
if (newRootProduct?.name !== state.rootProduct?.name) {
state.rootProduct = newRootProduct;
}
},
setError(state, { error: obj, locationError }) {
// We don't want to clobber one error with another, doing so can hide the original cause of an error
if (obj && state.error) {
return;
}
const err = new ApiError(obj);
console.log('Loading error', err); // eslint-disable-line no-console
console.log('(actual error)', obj); // eslint-disable-line no-console
// Location of error, with description and stack trace
console.log('Loading error location', locationError); // eslint-disable-line no-console
console.log('Loading original error', obj); // eslint-disable-line no-console
state.error = err;
state.cameFromError = true;
},
cameFromError(state) {
state.cameFromError = true;
},
setServerVersion(state, version) {
state.serverVersion = version;
},
setSystemNamespaces(state, namespaces) {
state.systemNamespaces = namespaces;
},
setIsSingleProduct(state, isSingleProduct) {
state.isSingleProduct = isSingleProduct;
},
targetRoute(state, route) {
state.targetRoute = route;
},
setRouter(state, router) {
state.$router = markRaw(router || {});
},
setRoute(state, route) {
state.$route = markRaw(route || {});
},
setPlugin(state, pluginDefinition) {
state.$extension = markRaw(pluginDefinition || {});
state.$plugin = markRaw(pluginDefinition || {});
},
showWorkspaceSwitcher(state, value) {
state.showWorkspaceSwitcher = value;
},
};
export const actions = {
handlePageAction({ state }, action) {
if (state.pageActionHandler) {
state.pageActionHandler(action);
}
},
async loadManagement({
getters, state, commit, dispatch, rootGetters
}) {
if ( state.managementReady) {
// Do nothing, it's already loaded
return;
}
console.log('Loading management...'); // eslint-disable-line no-console
try {
await dispatch('rancher/findAll', { type: NORMAN.PRINCIPAL, opt: { url: 'principals' } });
} catch (e) {
// Maybe not Rancher
}
let res = await allHashSettled({
mgmtSubscribe: dispatch('management/subscribe'),
mgmtSchemas: dispatch('management/loadSchemas', true),
rancherSchemas: dispatch('rancher/loadSchemas', true),
});
// Note - why aren't we watching anything fetched in the `promises` object?
// To watch we need feature flags to know that the vai cache is enabled.
// So to work around this we won't watch anything initially... and then watch once we have feature flags
// The alternative is simpler (fetch features up front) but would add another blocking request in
const promises = {
// Features checks on its own if they are available
[MANAGEMENT.FEATURE]: dispatch('features/loadServer'),
};
const toWatch = [
MANAGEMENT.FEATURE,
];
const isRancher = res.rancherSchemas.status === 'fulfilled' && !!getters['management/schemaFor'](MANAGEMENT.PROJECT);
if ( isRancher ) {
promises['prefs'] = dispatch('prefs/loadServer');
promises['rancherSubscribe'] = dispatch('rancher/subscribe');
}
if ( getters['management/schemaFor'](COUNT) ) {
promises[COUNT] = dispatch('management/findAll', { type: COUNT, opt: { watch: false } });
toWatch.push(COUNT);
}
if ( getters['management/canList'](MANAGEMENT.SETTING) ) {
promises[MANAGEMENT.SETTING] = dispatch('management/findAll', { type: MANAGEMENT.SETTING, opt: { watch: false } });
toWatch.push(MANAGEMENT.SETTING);
}
if ( getters['management/schemaFor'](NAMESPACE) ) {
promises[NAMESPACE] = dispatch('management/findAll', { type: NAMESPACE, opt: { watch: false } });
toWatch.push(NAMESPACE);
}
const fleetSchema = getters['management/schemaFor'](FLEET.WORKSPACE);
if (fleetSchema?.links?.collection) {
promises[FLEET.WORKSPACE] = dispatch('management/findAll', { type: FLEET.WORKSPACE, opt: { watch: false } });
toWatch.push(FLEET.WORKSPACE);
}
res = await allHash(promises);
let localCluster = null;
if (!res[MANAGEMENT.SETTING] || !paginateClusters({ rootGetters, state })) {
// This introduces a synchronous request, however we need settings to determine if SSP is enabled
await dispatch('management/findAll', { type: MANAGEMENT.CLUSTER, opt: { watch: false } });
toWatch.push(MANAGEMENT.CLUSTER);
localCluster = getters['management/byId'](MANAGEMENT.CLUSTER, 'local');
} else {
try {
localCluster = await dispatch('management/find', {
type: MANAGEMENT.CLUSTER, id: 'local', opt: { watch: false }
});
} catch (e) { // we don't care about errors, specifically 404s
}
}
// See comment above. Now that we have feature flags we can watch resources
toWatch.forEach((type) => {
dispatch('management/watch', { type });
});
// If the local cluster is a Harvester cluster and 'rancher-manager-support' is true, it means that the embedded Rancher is being used.
if (localCluster?.isHarvester) {
const harvesterSetting = await dispatch('cluster/findAll', { type: HCI.SETTING, opt: { url: `/v1/harvester/${ HCI.SETTING }s` } });
const rancherManagerSupport = harvesterSetting.find((setting) => setting.id === 'rancher-manager-support');
const isRancherInHarvester = (rancherManagerSupport?.value || rancherManagerSupport?.default) === 'true';
commit('isRancherInHarvester', isRancherInHarvester);
if (getters['isSingleProduct']) {
console.log('Detect standalone harvester, subscribe Rancher socket'); // eslint-disable-line no-console
await dispatch('rancher/subscribe');
}
}
const pl = res[MANAGEMENT.SETTING]?.find((x) => x.id === 'ui-pl')?.value;
const brand = res[MANAGEMENT.SETTING]?.find((x) => x.id === SETTING.BRAND)?.value;
const systemNamespaces = res[MANAGEMENT.SETTING]?.find((x) => x.id === SETTING.SYSTEM_NAMESPACES);
if ( pl ) {
setVendor(pl);
}
if (brand) {
setBrand(brand);
}
// Add the notification for the release notes
if (isRancher) {
await addReleaseNotesNotification(dispatch, getters);
fetchAndProcessDynamicContent(dispatch, getters, this.$axios);
}
if (systemNamespaces) {
const namespace = (systemNamespaces.value || systemNamespaces.default)?.split(',');
commit('setSystemNamespaces', namespace);
}
commit('managementChanged', {
ready: true,
isRancher,
localCluster
});
if ( res[FLEET.WORKSPACE] ) {
commit('updateWorkspace', {
value: getters['prefs/get'](WORKSPACE),
all: res[FLEET.WORKSPACE],
getters
});
}
const isMultiCluster = getters['isMultiCluster'];
console.log(`Done loading management; isRancher=${ isRancher }; isMultiCluster=${ isMultiCluster }`); // eslint-disable-line no-console
},
// Note:
// - state.clusterId is the old cluster id (or undefined)
// - id is the new cluster id (or undefined)
async loadCluster({
state, commit, dispatch, getters, rootGetters
}, {
id, product, oldProduct, oldPkg, newPkg, targetRoute
}) {
commit('targetRoute', targetRoute);
const sameCluster = state.clusterId && state.clusterId === id;
const samePackage = oldPkg?.name === newPkg?.name;
const sameProduct = oldProduct === product;
const isMultiCluster = getters['isMultiCluster'];
const productConfig = state['type-map']?.products?.find((p) => p.name === product);
const oldProductConfig = state['type-map']?.products?.find((p) => p.name === oldProduct);
// Are we in the same cluster and package or product or root product?
if (sameCluster && (samePackage || sameProduct || (productConfig?.rootProduct === oldProductConfig?.rootProduct))) {
// Do nothing, we're already connected/connecting to this cluster
return;
}
const oldPkgClusterStore = oldPkg?.stores.find(
(s) => getters[`${ s.storeName }/isClusterStore`]
)?.storeName;
const newPkgClusterStore = newPkg?.stores.find(
(s) => getters[`${ s.storeName }/isClusterStore`]
)?.storeName;
// Forget the cluster if we had a cluster and we have a new cluster OR if the store changed between the old and new products OR if the pkg store changed
// Package stores are only there for UI Extensions that have their own stores (normal case is this is undefined)
const forgetCurrentCluster = ((state.clusterId && id) ||
(productConfig?.inStore && productConfig.inStore !== oldProductConfig?.inStore)) ||
(oldPkgClusterStore !== newPkgClusterStore);
// Should we leave/forget the current cluster? Only if we're going from an existing cluster to a new cluster, or the package has changed
// (latter catches cases like nav from explorer cluster A to epinio cluster A)
// AND if the product not scoped to the explorer - a case for products that only exist within the explorer (i.e. Kubewarden)
if ( forgetCurrentCluster ) {
// Clear the old cluster state out if switching to a new one.
// If there is not an id then stay connected to the old one behind the scenes,
// so that the nav and header stay the same when going to things like prefs
commit('clusterReady', false);
commit('clusterId', undefined);
await dispatch('cluster/unsubscribe');
commit('cluster/reset');
await dispatch('management/watch', {
type: MANAGEMENT.PROJECT,
namespace: state.clusterId,
stop: true
});
commit('management/forgetType', MANAGEMENT.PROJECT);
commit('catalog/reset');
if (oldPkgClusterStore) {
// Mirror actions on the 'cluster' store for our specific pkg `cluster` store
await dispatch(`${ oldPkgClusterStore }/unsubscribe`);
await commit(`${ oldPkgClusterStore }/reset`);
}
}