forked from redhat-developer/gitops-console-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplicationList.tsx
More file actions
562 lines (536 loc) · 18 KB
/
ApplicationList.tsx
File metadata and controls
562 lines (536 loc) · 18 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
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import TechPreviewBadge from 'src/components/import/badges/TechPreviewBadge';
import { ApplicationSetKind } from '@gitops/models/ApplicationSetModel';
import {
Action,
K8sResourceCommon,
ListPageBody,
ListPageCreate,
ListPageFilter,
ListPageHeader,
ResourceLink,
RowFilter,
useK8sWatchResource,
useListPageFilter,
} from '@openshift-console/dynamic-plugin-sdk';
import { ErrorState } from '@patternfly/react-component-groups';
import { EmptyState, EmptyStateBody, Flex, FlexItem, Spinner, Title } from '@patternfly/react-core';
import { DataViewTh, DataViewTr } from '@patternfly/react-data-view/dist/esm/DataViewTable';
import { CubesIcon } from '@patternfly/react-icons';
import { Tbody, Td, ThProps, Tr } from '@patternfly/react-table';
import { useApplicationActionsProvider } from '../..//hooks/useApplicationActionsProvider';
import RevisionFragment from '../..//Revision/Revision';
import HealthStatusFragment from '../..//Statuses/HealthStatus';
import { HealthStatus, SyncStatus } from '../..//utils/constants';
import {
ApplicationKind,
ApplicationModel,
ApplicationSource,
} from '../../models/ApplicationModel';
import { AppProjectKind } from '../../models/AppProjectModel';
import { OperationState } from '../../Statuses/OperationState';
import SyncStatusFragment from '../../Statuses/SyncStatus';
import ActionsDropdown from '../../utils/components/ActionDropDown/ActionDropDown';
import { isApplicationRefreshing } from '../../utils/gitops';
import { modelToGroupVersionKind, modelToRef } from '../../utils/utils';
import { ApplicationSetGraphView } from '../appset/graph/ApplicationSetGraphView';
import {
ShowOperandsInAllNamespacesRadioGroup,
useShowOperandsInAllNamespaces,
} from './AllNamespaces';
import { GitOpsDataViewTable, useGitOpsDataViewSort } from './DataView';
interface ApplicationProps {
namespace: string;
// Here to support plugging in view in Projects (i.e. show list of apps that belong to project)
// Needs the console API to support defining your own static filter though since neither a label
// or a field-selector is available to select just the project apps based on k8s watch api.
project?: AppProjectKind;
appset?: K8sResourceCommon | ApplicationSetKind;
hideNameLabelFilters?: boolean;
showTitle?: boolean;
}
function filterApp(project: AppProjectKind, appset: K8sResourceCommon) {
return function (app: ApplicationKind) {
if (project != undefined) {
return app.spec.project == project.metadata.name;
} else if (appset != undefined) {
if (app.metadata.ownerReferences == undefined) return false;
let matched = false;
app.metadata.ownerReferences.forEach((owner) => {
matched = owner.kind == appset.kind && owner.name == appset.metadata.name;
if (matched) return;
});
return matched;
}
return true;
};
}
const ApplicationList: React.FC<ApplicationProps> = ({
namespace,
project,
appset,
hideNameLabelFilters,
showTitle,
}) => {
const [showOperandsInAllNamespaces] = useShowOperandsInAllNamespaces();
const listAllNamespaces =
location.pathname?.includes('openshift-gitops-operator') && showOperandsInAllNamespaces;
if (listAllNamespaces) {
namespace = null;
}
const [applications, loaded, loadError] = useK8sWatchResource<K8sResourceCommon[]>({
isList: true,
groupVersionKind: {
group: 'argoproj.io',
kind: 'Application',
version: 'v1alpha1',
},
namespaced: !listAllNamespaces,
namespace,
});
const { t } = useTranslation('plugin__gitops-plugin');
const columnSortConfig = React.useMemo(
() =>
[
'name',
...(!listAllNamespaces || !namespace ? ['namespace'] : []),
'sync-status',
'health-status',
'revision',
'project',
'actions',
].map((key) => ({ key })),
[listAllNamespaces, namespace],
);
const { searchParams, sortBy, direction, getSortParams } =
useGitOpsDataViewSort(columnSortConfig);
// Get search query from URL parameters
const searchQuery = searchParams.get('q') || '';
const columnsDV = useColumnsDV(namespace, getSortParams);
const sortedApplications = React.useMemo(() => {
return sortData(applications, sortBy, direction);
}, [applications, sortBy, direction]);
// Filter applications by project or appset FIRST - before PatternFly filters
// This ensures PF filters work on the correct dataset (owned apps only)
const ownedApps = React.useMemo(
() => sortedApplications.filter(filterApp(project, appset)),
[sortedApplications, project, appset],
);
// TODO: use alternate filter since it is deprecated. See DataTableView potentially
// PatternFly filters work on owned apps only (the dataset that will be displayed)
const filters = getFilters(t);
const [data, filteredData, onFilterChange] = useListPageFilter(ownedApps, filters);
// Filter by search query if present (after other filters)
const filteredBySearch = React.useMemo(() => {
if (!searchQuery) return filteredData;
return filteredData.filter((app) => {
const labels = app.metadata?.labels || {};
// Check if any label matches the search query
return Object.entries(labels).some(([key, value]) => {
const labelSelector = `${key}=${value}`;
return labelSelector.includes(searchQuery) || key.includes(searchQuery);
});
});
}, [filteredData, searchQuery]);
const rows = useApplicationRowsDV(filteredBySearch, namespace);
// Check if there are applications owned by this ApplicationSet initially (before filters/search)
const hasOwnedApplications = ownedApps.length > 0;
const empty = (
<Tbody>
<Tr key="loading" ouiaId="table-tr-loading">
<Td colSpan={columnsDV.length}>
<EmptyState
headingLevel="h4"
icon={CubesIcon}
titleText={
searchQuery ? t('No matching Argo CD Applications') : t('No Argo CD Applications')
}
>
<EmptyStateBody>
{(() => {
if (searchQuery) {
return (
<>
{t('No Argo CD Applications match the label filter')}{' '}
<strong>"{searchQuery}"</strong>.
<br />
{t(
'Try removing the filter or selecting a different label to see more applications.',
)}
</>
);
}
return namespace
? t('There are no Argo CD Applications in this project.')
: t('There are no Argo CD Applications in all projects.');
})()}
</EmptyStateBody>
</EmptyState>
</Td>
</Tr>
</Tbody>
);
const error = loadError && (
<Tbody>
<Tr key="loading" ouiaId={'table-tr-loading'}>
<Td colSpan={columnsDV.length}>
<ErrorState
titleText={t('Unable to load data')}
bodyText={t(
'There was an error retrieving applications. Check your connection and reload the page.',
)}
/>
</Td>
</Tr>
</Tbody>
);
return (
<div>
{showTitle == undefined && (project == undefined || appset == undefined) && (
<ListPageHeader
title={t('plugin__gitops-plugin~Applications')}
badge={
location.pathname?.includes('openshift-gitops-operator') ? null : (
<TechPreviewBadge
tooltipContent={t(
'This list page is under tech preview, but not necessarily the resources it represents',
)}
/>
)
}
helpText={
location.pathname?.includes('openshift-gitops-operator') ? (
<ShowOperandsInAllNamespacesRadioGroup />
) : null
}
hideFavoriteButton={false}
>
<ListPageCreate groupVersionKind={modelToRef(ApplicationModel)}>
Create Application
</ListPageCreate>
</ListPageHeader>
)}
<ListPageBody>
{/* Show an AppSet specific title if showTitle is undefined. We don't want a duplicate title from above */}
{appset && (
<Flex flex={{ default: 'flexDefault' }}>
{/* {showTitle == undefined && ( */}
<Title headingLevel="h2" className="co-section-heading">
{t('ApplicationSet Applications')}
</Title>
{/* )} */}
<FlexItem fullWidth={{ default: 'fullWidth' }}>
{t(
"The graph and table views show the ApplicationSet's applications. Use the filter below the graph to filter applications based on their health and sync status.",
)}
</FlexItem>
<FlexItem
fullWidth={{ default: 'fullWidth' }}
style={{
width: '95%',
height: '1000px',
border: '1px solid gray',
margin: '30px 30px',
}}
>
<ApplicationSetGraphView
applicationSet={appset as ApplicationSetKind}
applications={filteredData}
/>
</FlexItem>
</Flex>
)}
{!hideNameLabelFilters && hasOwnedApplications && (
<ListPageFilter
data={data}
loaded={loaded}
rowFilters={filters}
onFilterChange={onFilterChange}
nameFilterPlaceholder={t('plugin__gitops-plugin~Search by name...')}
/>
)}
<GitOpsDataViewTable
columns={columnsDV}
rows={rows}
isEmpty={filteredBySearch.length === 0}
emptyState={empty}
errorState={error || undefined}
isError={!!loadError}
/>
</ListPageBody>
</div>
);
};
export const sortData = (
data: ApplicationKind[],
sortBy: string | undefined,
direction: 'asc' | 'desc' | undefined,
) => {
if (!(sortBy && direction)) return data;
return [...data].sort((a, b) => {
let aValue: any, bValue: any;
switch (sortBy) {
case 'name':
aValue = a.metadata?.name || '';
bValue = b.metadata?.name || '';
break;
case 'namespace':
aValue = a.metadata?.namespace || '';
bValue = b.metadata?.namespace || '';
break;
case 'sync-status':
aValue = a.status?.sync?.status || '';
bValue = b.status?.sync?.status || '';
break;
case 'health-status':
aValue = a.status?.health?.status || '';
bValue = b.status?.health?.status || '';
break;
case 'revision':
aValue = a.status?.sync?.revision || '';
bValue = b.status?.sync?.revision || '';
break;
case 'project':
aValue = a.spec?.project || '';
bValue = b.spec?.project || '';
break;
default:
return 0;
}
if (direction === 'asc') {
// eslint-disable-next-line no-nested-ternary
return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
} else {
// eslint-disable-next-line no-nested-ternary
return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
}
});
};
const ApplicationActionsCell: React.FC<{ app: ApplicationKind }> = ({ app }) => {
const actionList: [actions: Action[]] = useApplicationActionsProvider(app);
return (
<div style={{ textAlign: 'right' }}>
<ActionsDropdown
actions={actionList ? actionList[0] : []}
id="gitops-application-actions"
isKebabToggle={true}
/>
</div>
);
};
const useApplicationRowsDV = (applicationsList, namespace): DataViewTr[] => {
const rows: DataViewTr[] = [];
applicationsList.forEach((app, index) => {
let sources: ApplicationSource[];
let revisions: string[] = [];
if (app.spec?.source) {
sources = [app.spec?.source];
revisions = [app.status?.sync?.revision];
} else if (app.spec?.sources) {
sources = app.spec.sources || [];
revisions = app.status?.sync?.revisions || [];
} else {
//Should never fall here since there always has to be a source or sources
sources = [];
revisions = [];
}
rows.push([
{
cell: (
<div>
<ResourceLink
groupVersionKind={modelToGroupVersionKind(ApplicationModel)}
name={app.metadata.name}
namespace={app.metadata.namespace}
inline={true}
>
<span className="pf-u-pl-sm">
{isApplicationRefreshing(app) && <Spinner size="sm" />}
</span>
</ResourceLink>
</div>
),
id: app.metadata?.name,
dataLabel: 'Name',
},
...(!namespace
? [
{
cell: <ResourceLink kind="Namespace" name={app.metadata.namespace} />,
id: app.metadata.namespace,
dataLabel: 'Namespace',
},
]
: []),
{
id: app.status?.sync?.status,
cell: (
<div className="pf-m-width-40">
<Flex>
<FlexItem>
<SyncStatusFragment status={app.status?.sync?.status || SyncStatus.UNKNOWN} />
</FlexItem>
<FlexItem>
<OperationState app={app} quiet={true} />
</FlexItem>
</Flex>
</div>
),
},
{
id: app.status?.health?.status,
cell: <HealthStatusFragment status={app.status?.health?.status || HealthStatus.UNKNOWN} />,
},
{
id: app?.status?.sync?.revision,
cell: (
<>
{sources[0]?.targetRevision ? sources[0].targetRevision : 'HEAD'}
{!(app.status?.sourceType == 'Helm' && sources[0].chart) && (
<RevisionFragment
revision={revisions[0] || ''}
repoURL={sources[0]?.repoURL || ''}
helm={app.status?.sourceType == 'Helm' && sources[0].chart ? true : false}
revisionExtra={revisions.length > 1 && ' and ' + (revisions.length - 1) + ' more'}
/>
)}
</>
),
},
{
id: app.spec?.project,
cell: app.spec?.project && (
<ResourceLink
groupVersionKind={{ group: 'argoproj.io', version: 'v1alpha1', kind: 'AppProject' }}
name={app.spec.project}
/>
),
},
{
id: 'actions-' + index,
cell: <ApplicationActionsCell app={app} />,
props: { style: { paddingTop: 8, paddingRight: 0, paddingLeft: 0, width: 10 } },
},
]);
});
return rows;
};
const useColumnsDV = (
namespace: string,
getSortParams: (columnIndex: number) => ThProps['sort'],
): DataViewTh[] => {
const i: number = namespace ? 0 : 1;
const { t } = useTranslation('plugin__gitops-plugin');
const columns: DataViewTh[] = [
{
cell: t('Name'),
props: {
'aria-label': 'name',
className: 'pf-m-width-25',
sort: getSortParams(0),
},
},
...(!namespace
? [
{
cell: t('Namespace'),
props: {
'aria-label': 'namespace',
className: 'pf-m-width-15',
sort: getSortParams(1),
},
},
]
: []),
{
cell: t('Sync Status'),
props: {
'aria-label': 'sync status',
className: 'pf-m-width-15',
sort: getSortParams(1 + i),
},
},
{
cell: t('Health Status'),
props: {
'aria-label': 'health status',
className: 'pf-m-width-15',
sort: getSortParams(2 + i),
},
},
{
cell: t('Revision'),
props: {
'aria-label': 'revision',
className: 'pf-m-width-12',
sort: getSortParams(3 + i),
},
},
{
cell: t('App Project'),
props: {
'aria-label': 'project',
className: 'pf-m-width-20',
sort: getSortParams(4 + i),
},
},
{
cell: '',
props: { 'aria-label': 'actions' },
},
];
return columns;
};
const FilterUnknownStatus: string = 'Sync.' + SyncStatus.UNKNOWN;
const getFilters = (t: (key: string) => string): RowFilter[] => [
{
filterGroupName: t('Sync Status'),
type: 'app-sync',
reducer: (application) =>
application.status?.sync?.status == SyncStatus.UNKNOWN ||
application.status?.sync?.status == undefined
? FilterUnknownStatus
: application.status?.sync?.status,
filter: (input, application) => {
if (input.selected?.length && application?.status?.sync?.status) {
return (
input.selected.includes(application.status?.sync?.status) ||
(input.selected.includes(FilterUnknownStatus) &&
application.status?.sync?.status == SyncStatus.UNKNOWN)
);
} else if (application.status?.sync?.status == undefined) {
return true;
} else if (!application?.status?.sync?.status) {
return false;
}
return true;
},
items: [
{ id: SyncStatus.SYNCED, title: SyncStatus.SYNCED },
{ id: SyncStatus.OUT_OF_SYNC, title: SyncStatus.OUT_OF_SYNC },
{ id: FilterUnknownStatus, title: SyncStatus.UNKNOWN },
],
},
{
filterGroupName: t('Health Status'),
type: 'app-health',
reducer: (application) => application.status?.health?.status,
filter: (input, application) => {
if (input.selected?.length && application?.status?.health?.status) {
return input.selected.includes(application.status?.health?.status);
} else {
return true;
}
},
items: [
{ id: HealthStatus.UNKNOWN, title: HealthStatus.UNKNOWN },
{ id: HealthStatus.PROGRESSING, title: HealthStatus.PROGRESSING },
{ id: HealthStatus.SUSPENDED, title: HealthStatus.SUSPENDED },
{ id: HealthStatus.HEALTHY, title: HealthStatus.HEALTHY },
{ id: HealthStatus.DEGRADED, title: HealthStatus.DEGRADED },
{ id: HealthStatus.MISSING, title: HealthStatus.MISSING },
],
},
];
export default ApplicationList;