-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Expand file tree
/
Copy pathutils.tsx
More file actions
2083 lines (1901 loc) · 80.5 KB
/
utils.tsx
File metadata and controls
2083 lines (1901 loc) · 80.5 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 {models, DataLoader, FormField, MenuItem, NotificationType, Tooltip, HelpIcon} from 'argo-ui';
import {ActionButton} from 'argo-ui/v2';
import * as classNames from 'classnames';
import * as React from 'react';
import * as ReactForm from 'react-form';
import {FormApi, Text} from 'react-form';
import * as moment from 'moment';
import {BehaviorSubject, combineLatest, concat, from, fromEvent, Observable, Observer, Subscription} from 'rxjs';
import {debounceTime, map} from 'rxjs/operators';
import {AppContext, Context, ContextApis} from '../../shared/context';
import {isValidURL} from '../../shared/utils';
import {ResourceTreeNode} from './application-resource-tree/application-resource-tree';
import {CheckboxField, COLORS, ErrorNotification, Revision} from '../../shared/components';
import * as appModels from '../../shared/models';
import {services} from '../../shared/services';
import {ApplicationSource} from '../../shared/models';
require('./utils.scss');
export interface NodeId {
kind: string;
namespace: string;
name: string;
group: string;
createdAt?: models.Time;
}
type ActionMenuItem = MenuItem & {disabled?: boolean; tooltip?: string};
export function nodeKey(node: NodeId) {
return [node.group, node.kind, node.namespace, node.name].join('/');
}
// Convert ResourceStatus to ResourceNode for orphaned resources
export function resourceStatusToResourceNode(res: appModels.ResourceStatus): appModels.ResourceNode {
return {
kind: res.kind,
name: res.name,
namespace: res.namespace,
group: res.group,
version: res.version,
uid: `${res.group}/${res.kind}/${res.namespace}/${res.name}`,
resourceVersion: '',
createdAt: res.createdAt,
parentRefs: [],
info: []
};
}
export function createdOrNodeKey(node: NodeId) {
return node?.createdAt || nodeKey(node);
}
export function isSameNode(first: NodeId, second: NodeId) {
return nodeKey(first) === nodeKey(second);
}
export function helpTip(text: string) {
return (
<Tooltip content={text}>
<span style={{fontSize: 'smaller'}}>
{' '}
<i className='fas fa-info-circle' />
</span>
</Tooltip>
);
}
//CLassic Solid circle-notch icon
//<!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
//this will replace all <i> fa-spin </i> icons as they are currently misbehaving with no fix available.
export const SpinningIcon = ({color, qeId}: {color: string; qeId: string}) => {
return (
<svg className='icon spin' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512' style={{color}} qe-id={qeId}>
<path
fill={color}
d='M222.7 32.1c5 16.9-4.6 34.8-21.5 39.8C121.8 95.6 64 169.1 64 256c0 106 86 192 192 192s192-86 192-192c0-86.9-57.8-160.4-137.1-184.1c-16.9-5-26.6-22.9-21.5-39.8s22.9-26.6 39.8-21.5C434.9 42.1 512 140 512 256c0 141.4-114.6 256-256 256S0 397.4 0 256C0 140 77.1 42.1 182.9 10.6c16.9-5 34.8 4.6 39.8 21.5z'
/>
</svg>
);
};
export async function deleteApplication(appName: string, appNamespace: string, apis: ContextApis, application?: appModels.Application): Promise<boolean> {
let confirmed = false;
// Use common child application detection logic if application object is provided
const isChildApp = application ? isChildApplication(application) : false;
const dialogTitle = isChildApp ? 'Delete child application' : 'Delete application';
const appType = isChildApp ? 'child Application' : 'Application';
const confirmLabel = isChildApp ? 'child application' : 'application';
// Check if this is being called from resource tree context
const isFromResourceTree = application !== undefined;
const propagationPolicies: {name: string; message: string}[] = [
{
name: 'Foreground',
message: `Cascade delete the application's resources using foreground propagation policy`
},
{
name: 'Background',
message: `Cascade delete the application's resources using background propagation policy`
},
{
name: 'Non-cascading',
message: `Only delete the application, but do not cascade delete its resources`
}
];
await apis.popup.prompt(
dialogTitle,
api => (
<div>
<p>
Are you sure you want to delete the <strong>{appType}</strong> <kbd>{appName}</kbd>?
</p>
{isFromResourceTree && (
<p>
<strong>
<i className='fa fa-warning delete-dialog-icon warning' /> Note:
</strong>{' '}
You are about to delete an Application from the resource tree. This uses the same deletion behavior as the Applications list page.
</p>
)}
<p>
Deleting the application in <kbd>foreground</kbd> or <kbd>background</kbd> mode will delete all the application's managed resources, which can be{' '}
<strong>dangerous</strong>. Be sure you understand the effects of deleting this resource before continuing. Consider asking someone to review the change first.
</p>
<div className='argo-form-row'>
<FormField
label={`Please type '${appName}' to confirm the deletion of the ${confirmLabel}`}
formApi={api}
field='applicationName'
qeId='name-field-delete-confirmation'
component={Text}
/>
</div>
<p>Select propagation policy for application deletion</p>
<div className='propagation-policy-list'>
{propagationPolicies.map(policy => {
return (
<FormField
formApi={api}
key={policy.name}
field='propagationPolicy'
component={PropagationPolicyOption}
componentProps={{
policy: policy.name,
message: policy.message
}}
/>
);
})}
</div>
</div>
),
{
validate: vals => ({
applicationName: vals.applicationName !== appName && 'Enter the application name to confirm the deletion'
}),
submit: async (vals, _, close) => {
try {
await services.applications.delete(appName, appNamespace, vals.propagationPolicy);
confirmed = true;
close();
} catch (e) {
apis.notifications.show({
content: <ErrorNotification title='Unable to delete application' e={e} />,
type: NotificationType.Error
});
}
}
},
{name: 'argo-icon-warning', color: 'failed'},
'red',
{propagationPolicy: 'foreground'}
);
return confirmed;
}
export async function confirmSyncingAppOfApps(apps: appModels.Application[], apis: ContextApis, form: FormApi): Promise<boolean> {
let confirmed = false;
const appNames: string[] = apps.map(app => app.metadata.name);
const appNameList = appNames.join(', ');
await apis.popup.prompt(
'Warning: Synchronize App of Multiple Apps using replace?',
api => (
<div>
<p>
Are you sure you want to sync the application '{appNameList}' which contain(s) multiple apps with 'replace' option? This action will delete and recreate all
apps linked to '{appNameList}'.
</p>
<div className='argo-form-row'>
<FormField
label={`Please type '${appNameList}' to confirm the Syncing of the resource`}
formApi={api}
field='applicationName'
qeId='name-field-delete-confirmation'
component={Text}
/>
</div>
</div>
),
{
validate: vals => ({
applicationName: vals.applicationName !== appNameList && 'Enter the application name(s) to confirm syncing'
}),
submit: async (_vals, _, close) => {
try {
await form.submitForm(null);
confirmed = true;
close();
} catch (e) {
apis.notifications.show({
content: <ErrorNotification title='Unable to sync application' e={e} />,
type: NotificationType.Error
});
}
}
},
{name: 'argo-icon-warning', color: 'warning'},
'yellow'
);
return confirmed;
}
const PropagationPolicyOption = ReactForm.FormField((props: {fieldApi: ReactForm.FieldApi; policy: string; message: string}) => {
const {
fieldApi: {setValue}
} = props;
return (
<div className='propagation-policy-option'>
<input
className='radio-button'
key={props.policy}
type='radio'
name='propagation-policy'
value={props.policy}
id={props.policy}
defaultChecked={props.policy === 'Foreground'}
onChange={() => setValue(props.policy.toLowerCase())}
/>
<label htmlFor={props.policy}>
{props.policy} {helpTip(props.message)}
</label>
</div>
);
});
export const OperationPhaseIcon = ({app, isButton}: {app: appModels.Application; isButton?: boolean}) => {
const operationState = getAppOperationState(app);
if (operationState === undefined) {
return null;
}
let className = '';
let color = '';
switch (operationState.phase) {
case appModels.OperationPhases.Succeeded:
className = `fa fa-check-circle${isButton ? ' status-button' : ''}`;
color = COLORS.operation.success;
break;
case appModels.OperationPhases.Error:
className = `fa fa-times-circle${isButton ? ' status-button' : ''}`;
color = COLORS.operation.error;
break;
case appModels.OperationPhases.Failed:
className = `fa fa-times-circle${isButton ? ' status-button' : ''}`;
color = COLORS.operation.failed;
break;
default:
className = 'fa fa-circle-notch fa-spin';
color = COLORS.operation.running;
break;
}
return className.includes('fa-spin') ? (
<SpinningIcon color={color} qeId='utils-operations-status-title' />
) : (
<i title={getOperationStateTitle(app)} qe-id='utils-operations-status-title' className={className} style={{color}} />
);
};
export const HydrateOperationPhaseIcon = ({operationState, isButton}: {operationState?: appModels.HydrateOperation; isButton?: boolean}) => {
if (operationState === undefined) {
return null;
}
let className = '';
let color = '';
switch (operationState.phase) {
case appModels.HydrateOperationPhases.Hydrated:
className = `fa fa-check-circle${isButton ? ' status-button' : ''}`;
color = COLORS.operation.success;
break;
case appModels.HydrateOperationPhases.Failed:
className = `fa fa-times-circle${isButton ? ' status-button' : ''}`;
color = COLORS.operation.failed;
break;
default:
className = 'fa fa-circle-notch fa-spin';
color = COLORS.operation.running;
break;
}
return className.includes('fa-spin') ? (
<SpinningIcon color={color} qeId='utils-operations-status-title' />
) : (
<i title={operationState.phase} qe-id='utils-operations-status-title' className={className} style={{color}} />
);
};
export const ComparisonStatusIcon = ({
status,
resource,
label,
noSpin,
isButton
}: {
status: appModels.SyncStatusCode;
resource?: {requiresPruning?: boolean};
label?: boolean;
noSpin?: boolean;
isButton?: boolean;
}) => {
let className = 'fas fa-question-circle';
let color = COLORS.sync.unknown;
let title: string = 'Unknown';
switch (status) {
case appModels.SyncStatuses.Synced:
className = `fa fa-check-circle${isButton ? ' status-button' : ''}`;
color = COLORS.sync.synced;
title = 'Synced';
break;
case appModels.SyncStatuses.OutOfSync:
// eslint-disable-next-line no-case-declarations
const requiresPruning = resource && resource.requiresPruning;
className = requiresPruning ? `fa fa-trash${isButton ? ' status-button' : ''}` : `fa fa-arrow-alt-circle-up${isButton ? ' status-button' : ''}`;
title = 'OutOfSync';
if (requiresPruning) {
title = `${title} (This resource is not present in the application's source. It will be deleted from Kubernetes if the prune option is enabled during sync.)`;
}
color = COLORS.sync.out_of_sync;
break;
case appModels.SyncStatuses.Unknown:
className = `fa fa-circle-notch ${noSpin ? '' : 'fa-spin'}${isButton ? ' status-button' : ''}`;
break;
}
return className.includes('fa-spin') ? (
<SpinningIcon color={color} qeId='utils-sync-status-title' />
) : (
<React.Fragment>
<i qe-id='utils-sync-status-title' title={title} className={className} style={{color}} /> {label && title}
</React.Fragment>
);
};
export function showDeploy(resource: string, revision: string, apis: ContextApis) {
apis.navigation.goto('.', {deploy: resource, revision}, {replace: true});
}
export function findChildPod(node: appModels.ResourceNode, tree: appModels.ApplicationTree): appModels.ResourceNode {
const key = nodeKey(node);
const allNodes = tree.nodes.concat(tree.orphanedNodes || []);
const nodeByKey = new Map<string, appModels.ResourceNode>();
allNodes.forEach(item => nodeByKey.set(nodeKey(item), item));
const pods = tree.nodes.concat(tree.orphanedNodes || []).filter(item => item.kind === 'Pod');
return pods.find(pod => {
const items: Array<appModels.ResourceNode> = [pod];
while (items.length > 0) {
const next = items.pop();
const parentKeys = (next.parentRefs || []).map(nodeKey);
if (parentKeys.includes(key)) {
return true;
}
parentKeys.forEach(item => {
const parent = nodeByKey.get(item);
if (parent) {
items.push(parent);
}
});
}
return false;
});
}
export function findChildResources(node: appModels.ResourceNode, tree: appModels.ApplicationTree): appModels.ResourceNode[] {
const key = nodeKey(node);
const children: appModels.ResourceNode[] = [];
tree.nodes.forEach(item => {
(item.parentRefs || []).forEach(parent => {
if (key === nodeKey(parent)) {
children.push(item);
}
});
});
return children;
}
const deletePodAction = async (ctx: ContextApis, pod: appModels.ResourceNode, app: appModels.AbstractApplication) => {
ctx.popup.prompt(
'Delete pod',
() => (
<div>
<p>
Are you sure you want to delete <strong>Pod</strong> <kbd>{pod.name}</kbd>?
<span style={{display: 'block', marginBottom: '10px'}} />
Deleting resources can be <strong>dangerous</strong>. Be sure you understand the effects of deleting this resource before continuing. Consider asking someone to
review the change first.
</p>
<div className='argo-form-row' style={{paddingLeft: '30px'}}>
<CheckboxField id='force-delete-checkbox' field='force' />
<label htmlFor='force-delete-checkbox'>Force delete</label>
<HelpIcon title='If checked, Argo will ignore any configured grace period and delete the resource immediately' />
</div>
</div>
),
{
submit: async (vals, _, close) => {
try {
await services.applications.deleteResource(app.metadata.name, app.metadata.namespace, pod, !!vals.force, false);
close();
} catch (e) {
ctx.notifications.show({
content: <ErrorNotification title='Unable to delete resource' e={e} />,
type: NotificationType.Error
});
}
}
}
);
};
export const deleteSourceAction = (app: appModels.Application, source: appModels.ApplicationSource, appContext: AppContext) => {
appContext.apis.popup.prompt(
'Delete source',
() => (
<div>
<p>
Are you sure you want to delete the source with URL: <kbd>{source.repoURL}</kbd>
{source.path ? (
<>
{' '}
and path: <kbd>{source.path}</kbd>?
</>
) : (
<>?</>
)}
</p>
</div>
),
{
submit: async (vals, _, close) => {
try {
const i = app.spec.sources.indexOf(source);
app.spec.sources.splice(i, 1);
await services.applications.update(app);
close();
} catch (e) {
appContext.apis.notifications.show({
content: <ErrorNotification title='Unable to delete source' e={e} />,
type: NotificationType.Error
});
}
}
},
{name: 'argo-icon-warning', color: 'warning'},
'yellow'
);
};
// Detect if a resource is an Application
const isApplicationResource = (resource: ResourceTreeNode): boolean => {
return resource.kind === 'Application' && resource.group === 'argoproj.io';
};
// Detect if an application is a child application
const isChildApplication = (application: appModels.Application): boolean => {
const partOfLabel = application.metadata.labels?.['app.kubernetes.io/part-of'];
return partOfLabel && partOfLabel.trim() !== '';
};
export const deletePopup = async (
ctx: ContextApis,
resource: ResourceTreeNode,
application: appModels.AbstractApplication,
isManaged: boolean,
childResources: appModels.ResourceNode[],
appChanged?: BehaviorSubject<appModels.AbstractApplication>
) => {
// Detect if this is an Application resource
const isApplication = isApplicationResource(resource);
const hasApplicationContext = isApp(application);
// Check if we're in a parent-child context (used for both Application and non-Application resources)
const isInParentContext = hasApplicationContext ? isChildApplication(application) : false;
// For Application resources, use the deleteApplication function with resource tree context
if (isApplication) {
return deleteApplication(resource.name, resource.namespace || '', ctx, hasApplicationContext ? application : undefined);
}
const deleteOptions = {
option: 'foreground'
};
function handleStateChange(option: string) {
deleteOptions.option = option;
}
if (resource.kind === 'Pod' && !isManaged) {
return deletePodAction(ctx, resource, application);
}
// Determine dialog title and add custom messaging
const dialogTitle = 'Delete resource';
let customMessage: React.ReactNode = null;
if (isInParentContext) {
customMessage = (
<div>
<p>
<strong>
<i className='fa fa-exclamation-triangle delete-dialog-icon info' /> Note:
</strong>{' '}
You are about to delete a resource from a parent application's resource tree.
</p>
</div>
);
}
return ctx.popup.prompt(
dialogTitle,
api => (
<div>
<p>
Are you sure you want to delete <strong>{resource.kind}</strong> <kbd>{resource.name}</kbd>?
</p>
{customMessage}
<p>
Deleting resources can be <strong>dangerous</strong>. Be sure you understand the effects of deleting this resource before continuing. Consider asking someone to
review the change first.
</p>
{(childResources || []).length > 0 ? (
<React.Fragment>
<p>Dependent resources:</p>
<ul>
{childResources.slice(0, 4).map((child, i) => (
<li key={i}>
<kbd>{[child.kind, child.name].join('/')}</kbd>
</li>
))}
{childResources.length === 5 ? (
<li key='4'>
<kbd>{[childResources[4].kind, childResources[4].name].join('/')}</kbd>
</li>
) : (
''
)}
{childResources.length > 5 ? <li key='N'>and {childResources.slice(4).length} more.</li> : ''}
</ul>
</React.Fragment>
) : (
''
)}
{isManaged ? (
<div className='argo-form-row'>
<FormField label={`Please type '${resource.name}' to confirm the deletion of the resource`} formApi={api} field='resourceName' component={Text} />
</div>
) : (
''
)}
<div className='argo-form-row'>
<input
type='radio'
name='deleteOptions'
value='foreground'
onChange={() => handleStateChange('foreground')}
defaultChecked={true}
style={{marginRight: '5px'}}
id='foreground-delete-radio'
/>
<label htmlFor='foreground-delete-radio' style={{paddingRight: '30px'}}>
Foreground Delete {helpTip('Deletes the resource and dependent resources using the cascading policy in the foreground')}
</label>
<input type='radio' name='deleteOptions' value='force' onChange={() => handleStateChange('force')} style={{marginRight: '5px'}} id='force-delete-radio' />
<label htmlFor='force-delete-radio' style={{paddingRight: '30px'}}>
Background Delete {helpTip('Performs a forceful "background cascading deletion" of the resource and its dependent resources')}
</label>
<input type='radio' name='deleteOptions' value='orphan' onChange={() => handleStateChange('orphan')} style={{marginRight: '5px'}} id='cascade-delete-radio' />
<label htmlFor='cascade-delete-radio'>Non-cascading (Orphan) Delete {helpTip('Deletes the resource and orphans the dependent resources')}</label>
</div>
</div>
),
{
validate: vals =>
isManaged && {
resourceName: vals.resourceName !== resource.name && 'Enter the resource name to confirm the deletion'
},
submit: async (vals, _, close) => {
const force = deleteOptions.option === 'force';
const orphan = deleteOptions.option === 'orphan';
try {
await services.applications.deleteResource(application.metadata.name, application.metadata.namespace, resource, !!force, !!orphan);
if (appChanged) {
const objectListKind = isApp(application) ? 'application' : 'applicationset';
appChanged.next(await services.applications.get(application.metadata.name, application.metadata.namespace, objectListKind));
}
close();
} catch (e) {
ctx.notifications.show({
content: <ErrorNotification title='Unable to delete resource' e={e} />,
type: NotificationType.Error
});
}
}
},
{name: 'argo-icon-warning', color: 'warning'},
'yellow'
);
};
export async function getResourceActionsMenuItems(resource: ResourceTreeNode, metadata: models.ObjectMeta, apis: ContextApis): Promise<ActionMenuItem[]> {
// Don't call API for missing resources
if (!resource.uid) {
return [];
}
return services.applications
.getResourceActions(metadata.name, metadata.namespace, resource)
.then(actions => {
return actions.map(action => ({
title: action.displayName ?? action.name,
disabled: !!action.disabled,
iconClassName: action.iconClass,
action: async () => {
const confirmed = false;
const title = action.params ? `Enter input parameters for action: ${action.name}` : `Perform ${action.name} action?`;
await apis.popup.prompt(
title,
api => (
<div>
{!action.params && (
<div className='argo-form-row'>
<div> Are you sure you want to perform {action.name} action?</div>
</div>
)}
{action.params &&
action.params.map((param, index) => (
<div className='argo-form-row' key={index}>
<FormField label={param.name} field={param.name} formApi={api} component={Text} />
</div>
))}
</div>
),
{
submit: async (vals, _, close) => {
try {
const resourceActionParameters = action.params
? action.params.map(param => ({
name: param.name,
value: vals[param.name] || param.default,
type: param.type,
default: param.default
}))
: [];
await services.applications.runResourceAction(metadata.name, metadata.namespace, resource, action.name, resourceActionParameters);
close();
} catch (e) {
apis.notifications.show({
content: <ErrorNotification title='Unable to execute resource action' e={e} />,
type: NotificationType.Error
});
}
}
},
null,
null,
action.params
? action.params.reduce((acc, res) => {
acc[res.name] = res.default;
return acc;
}, {} as any)
: {}
);
return confirmed;
}
}));
})
.catch(() => [] as ActionMenuItem[]);
}
function getActionItems(
resource: ResourceTreeNode,
application: appModels.AbstractApplication,
tree: appModels.AbstractApplicationTree,
apis: ContextApis,
appChanged: BehaviorSubject<appModels.AbstractApplication>,
isQuickStart: boolean
): Observable<ActionMenuItem[]> {
function isTopLevelResource(res: ResourceTreeNode, app: appModels.AbstractApplication): boolean {
const uniqRes = `/${res.namespace}/${res.group}/${res.kind}/${res.name}`;
return (
app.status?.resources?.some((resStatus: appModels.ResourceStatus) => `/${resStatus.namespace}/${resStatus.group}/${resStatus.kind}/${resStatus.name}` === uniqRes) ||
false
);
}
const isPod = resource.kind === 'Pod';
const isManaged = isTopLevelResource(resource, application);
const childResources = isApp(application) ? findChildResources(resource, tree as appModels.ApplicationTree) : [];
const items: MenuItem[] = [
...((isManaged && [
{
title: 'Sync',
iconClassName: 'fa fa-fw fa-sync',
action: () => showDeploy(nodeKey(resource), null, apis)
}
]) ||
[]),
{
title: 'Delete',
iconClassName: 'fa fa-fw fa-times-circle',
action: async () => {
return deletePopup(apis, resource, application, isManaged, childResources, appChanged);
}
}
];
if (!isQuickStart) {
items.unshift({
title: 'Details',
iconClassName: 'fa fa-fw fa-info-circle',
action: () => apis.navigation.goto('.', {node: nodeKey(resource)})
});
}
const logsAction = isApp(application)
? services.accounts
.canI('logs', 'get', application.spec.project + '/' + application.metadata.name)
.then(async allowed => {
if (allowed && (isPod || findChildPod(resource, tree as appModels.ApplicationTree))) {
return [
{
title: 'Logs',
iconClassName: 'fa fa-fw fa-align-left',
action: () => apis.navigation.goto('.', {node: nodeKey(resource), tab: 'logs'}, {replace: true})
} as MenuItem
];
}
return [] as MenuItem[];
})
.catch(() => [] as MenuItem[])
: Promise.resolve([] as MenuItem[]);
if (isQuickStart) {
return combineLatest(
from([items]), // this resolves immediately
concat([[] as MenuItem[]], logsAction) // this resolves at first to [] and then whatever the API returns
).pipe(map(res => ([] as MenuItem[]).concat(...res)));
}
const execAction = isApp(application)
? services.authService
.settings()
.then(async settings => {
const execAllowed = settings.execEnabled && (await services.accounts.canI('exec', 'create', application.spec.project + '/' + application.metadata.name));
if (isPod && execAllowed) {
return [
{
title: 'Exec',
iconClassName: 'fa fa-fw fa-terminal',
action: async () => apis.navigation.goto('.', {node: nodeKey(resource), tab: 'exec'}, {replace: true})
} as MenuItem
];
}
return [] as MenuItem[];
})
.catch(() => [] as MenuItem[])
: Promise.resolve([] as MenuItem[]);
const resourceActions = getResourceActionsMenuItems(resource, application.metadata, apis);
const links = !resource.uid
? Promise.resolve([])
: services.applications
.getResourceLinks(application.metadata.name, application.metadata.namespace, resource)
.then(data => {
return (data.items || []).map(
link =>
({
title: link.title,
iconClassName: `fa fa-fw ${link.iconClass ? link.iconClass : 'fa-external-link'}`,
action: () => window.open(link.url, '_blank'),
tooltip: link.description
}) as MenuItem
);
})
.catch(() => [] as MenuItem[]);
return combineLatest(
from([items]), // this resolves immediately
concat([[] as MenuItem[]], logsAction), // this resolves at first to [] and then whatever the API returns
concat([[] as MenuItem[]], resourceActions), // this resolves at first to [] and then whatever the API returns
concat([[] as MenuItem[]], execAction), // this resolves at first to [] and then whatever the API returns
concat([[] as MenuItem[]], links) // this resolves at first to [] and then whatever the API returns
).pipe(map(res => ([] as MenuItem[]).concat(...res)));
}
export function renderResourceMenu(
resource: ResourceTreeNode,
application: appModels.AbstractApplication,
tree: appModels.AbstractApplicationTree,
apis: ContextApis,
appChanged: BehaviorSubject<appModels.AbstractApplication>,
getApplicationActionMenu: () => any
): React.ReactNode {
let menuItems: Observable<ActionMenuItem[]>;
if (isAppNode(resource) && resource.name === application.metadata.name) {
menuItems = from([getApplicationActionMenu()]);
} else {
menuItems = getActionItems(resource, application, tree, apis, appChanged, false);
}
return (
<DataLoader load={() => menuItems}>
{items => (
<ul>
{items.map((item, i) => (
<li
className={classNames('application-details__action-menu', {disabled: item.disabled})}
tabIndex={item.disabled ? undefined : 0}
key={i}
onClick={e => {
e.stopPropagation();
if (!item.disabled) {
item.action();
document.body.click();
}
}}
onKeyDown={e => {
if (e.keyCode === 13 || e.key === 'Enter') {
e.stopPropagation();
setTimeout(() => {
item.action();
document.body.click();
});
}
}}>
{item.tooltip ? (
<Tooltip content={item.tooltip || ''}>
<div>
{item.iconClassName && <i className={item.iconClassName} />} {item.title}
</div>
</Tooltip>
) : (
<>
{item.iconClassName && <i className={item.iconClassName} />} {item.title}
</>
)}
</li>
))}
</ul>
)}
</DataLoader>
);
}
export function renderResourceActionMenu(menuItems: ActionMenuItem[]): React.ReactNode {
return (
<ul>
{menuItems.map((item, i) => (
<li
className={classNames('application-details__action-menu', {disabled: item.disabled})}
key={i}
onClick={e => {
e.stopPropagation();
if (!item.disabled) {
item.action();
document.body.click();
}
}}>
{item.iconClassName && <i className={item.iconClassName} />} {item.title}
</li>
))}
</ul>
);
}
interface ResourceButtonsProps {
resource: ResourceTreeNode;
application: appModels.AbstractApplication;
tree: appModels.AbstractApplicationTree;
apis: ContextApis;
appChanged: BehaviorSubject<appModels.AbstractApplication>;
}
interface ResourceButtonsInput {
resource: ResourceTreeNode;
application: appModels.AbstractApplication;
tree: appModels.AbstractApplicationTree;
apisId: number;
appChangedId: number;
}
const objectIds = new WeakMap<object, number>();
let nextObjectId = 1;
function getObjectId(value: object) {
let id = objectIds.get(value);
if (id === undefined) {
id = nextObjectId++;
objectIds.set(value, id);
}
return id;
}
// Keep quickstart action loading stable across unrelated PodView rerenders.
const ResourceButtons = React.memo(({resource, application, tree, apis, appChanged}: ResourceButtonsProps) => {
const input = React.useMemo(
() => ({
resource,
application,
tree,
apisId: getObjectId(apis),
appChangedId: getObjectId(appChanged)
}),
[resource, application, tree, apis, appChanged]
);
return (
<DataLoader input={input} load={(value: ResourceButtonsInput) => getActionItems(value.resource, value.application, value.tree, apis, appChanged, true)}>
{items => (
<div className='pod-view__node__quick-start-actions'>
{items.map((item, i) => (
<ActionButton
disabled={item.disabled}
key={i}
action={(e: React.MouseEvent) => {
e.stopPropagation();
if (!item.disabled) {
item.action();
document.body.click();
}
}}
icon={item.iconClassName}
tooltip={item.title.toString().charAt(0).toUpperCase() + item.title.toString().slice(1)}
/>
))}
</div>
)}
</DataLoader>
);
});
ResourceButtons.displayName = 'ResourceButtons';
export function renderResourceButtons(
resource: ResourceTreeNode,
application: appModels.AbstractApplication,
tree: appModels.AbstractApplicationTree,
apis: ContextApis,
appChanged: BehaviorSubject<appModels.AbstractApplication>
): React.ReactNode {
return <ResourceButtons resource={resource} application={application} tree={tree} apis={apis} appChanged={appChanged} />;
}
export function syncStatusMessage(app: appModels.Application) {
const source = getAppDefaultSource(app);
const revision = getAppDefaultSyncRevision(app);
const rev = app.status.sync.revision || (source ? source.targetRevision || 'HEAD' : 'Unknown');
let message = source ? source?.targetRevision || 'HEAD' : 'Unknown';
if (revision && source) {
if (source.chart) {
message += ' (' + revision + ')';
} else if (revision.length >= 7 && !revision.startsWith(source.targetRevision)) {
if (source.repoURL.startsWith('oci://')) {
// Show "sha256: " plus the first 7 actual characters of the digest.
if (revision.startsWith('sha256:')) {
message += ' (' + revision.substring(0, 14) + ')';
} else {
message += ' (' + revision.substring(0, 7) + ')';
}
} else {
message += ' (' + revision.substring(0, 7) + ')';
}
}
}
switch (app.status.sync.status) {
case appModels.SyncStatuses.Synced:
return (
<span>
to{' '}
<Revision repoUrl={source.repoURL} revision={rev}>
{message}