@skyhook-io/radar-app 1.20.3 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/package.json +10 -9
  2. package/src/App.tsx +54 -10
  3. package/src/api/client.audit-gating.test.tsx +105 -5
  4. package/src/api/client.auditBadgesSync.test.tsx +118 -0
  5. package/src/api/client.capabilitiesPoll.test.ts +61 -0
  6. package/src/api/client.ts +129 -5
  7. package/src/api/namespaceScopeRetry.test.ts +14 -0
  8. package/src/api/radarFeatures.ts +7 -0
  9. package/src/api/substrateHealth.ts +134 -0
  10. package/src/api/velero.test.ts +60 -0
  11. package/src/api/velero.ts +201 -0
  12. package/src/api/vulnerabilities.ts +255 -0
  13. package/src/components/NamespaceSwitcher.tsx +3 -1
  14. package/src/components/audit/AuditView.tsx +4 -0
  15. package/src/components/audit/ChecksViewTabs.test.tsx +33 -5
  16. package/src/components/audit/ChecksViewTabs.tsx +11 -1
  17. package/src/components/audit/UpgradeReadinessView.test.ts +35 -1
  18. package/src/components/audit/UpgradeReadinessView.tsx +60 -2
  19. package/src/components/audit/VulnerabilitiesView.tsx +907 -0
  20. package/src/components/cnpg/CNPGClusterTabs.tsx +3 -1
  21. package/src/components/cnpg/CNPGDrawerTrail.tsx +5 -26
  22. package/src/components/cnpg/CNPGInvestigationAction.test.tsx +27 -6
  23. package/src/components/cnpg/CNPGView.tsx +43 -117
  24. package/src/components/cnpg/CNPGWorkspace.compatibility.test.tsx +30 -0
  25. package/src/components/cnpg/host.tsx +2 -2
  26. package/src/components/cnpg/routes.ts +3 -1
  27. package/src/components/cnpg/shared.tsx +5 -53
  28. package/src/components/cnpg/useCNPGNavigate.ts +1 -21
  29. package/src/components/cnpg/useCNPGSidebarWorkspace.ts +16 -13
  30. package/src/components/community.tsx +42 -0
  31. package/src/components/diagnose/diagnoseEvidenceTypes.ts +2 -0
  32. package/src/components/diagnose/investigationMetrics.test.ts +20 -0
  33. package/src/components/diagnose/investigationMetrics.ts +2 -1
  34. package/src/components/dock/BottomDock.tsx +1 -0
  35. package/src/components/dock/LogsTab.tsx +3 -0
  36. package/src/components/gitops/GitOpsView.tsx +1 -1
  37. package/src/components/helm/HelmDrawerFrame.tsx +1 -1
  38. package/src/components/helm/HelmView.tsx +20 -16
  39. package/src/components/helm/OwnedResources.tsx +4 -3
  40. package/src/components/home/ClusterHealthCard.tsx +3 -1
  41. package/src/components/home/HomeAgentBlock.tsx +3 -0
  42. package/src/components/home/HomeView.tsx +7 -0
  43. package/src/components/home/MCPSetupDialog.test.tsx +19 -12
  44. package/src/components/home/MCPSetupDialog.tsx +4 -2
  45. package/src/components/home/mcpToolCatalog.ts +15 -2
  46. package/src/components/home/useVulnerabilitiesRow.test.ts +26 -0
  47. package/src/components/home/useVulnerabilitiesRow.ts +50 -0
  48. package/src/components/logs/LogsViewer.tsx +3 -1
  49. package/src/components/logs/MultiPodLogsTab.test.tsx +24 -4
  50. package/src/components/logs/MultiPodLogsTab.tsx +9 -5
  51. package/src/components/nav/PrimaryNavRail.test.tsx +17 -0
  52. package/src/components/nav/PrimaryNavRail.tsx +174 -29
  53. package/src/components/resource/PrometheusChartsGrid.tsx +5 -1
  54. package/src/components/resource/SubstrateHealthCharts.test.tsx +143 -0
  55. package/src/components/resource/SubstrateHealthCharts.tsx +254 -0
  56. package/src/components/resource/SubstrateVerdictLine.test.tsx +131 -0
  57. package/src/components/resource/SubstrateVerdictLine.tsx +180 -0
  58. package/src/components/resources/ResourcesView.tsx +12 -6
  59. package/src/components/resources/renderers/UpgradePlanRenderer.test.tsx +20 -0
  60. package/src/components/resources/renderers/UpgradePlanRenderer.tsx +22 -0
  61. package/src/components/resources/renderers/VeleroBackupRenderer.tsx +16 -36
  62. package/src/components/resources/renderers/VeleroRestoreRenderer.tsx +6 -19
  63. package/src/components/resources/renderers/WorkloadRenderer.tsx +8 -0
  64. package/src/components/rightsizing/RightsizingScanView.tsx +3 -2
  65. package/src/components/shared/LargeClusterNamespacePicker.test.tsx +27 -0
  66. package/src/components/shared/LargeClusterNamespacePicker.tsx +8 -2
  67. package/src/components/timeline/TimelineView.tsx +3 -1
  68. package/src/components/traffic/TrafficConnectionsTable.test.tsx +94 -0
  69. package/src/components/traffic/TrafficConnectionsTable.tsx +21 -5
  70. package/src/components/traffic/TrafficData.test.tsx +37 -0
  71. package/src/components/traffic/TrafficData.tsx +27 -0
  72. package/src/components/traffic/TrafficFlowList.tsx +9 -7
  73. package/src/components/traffic/TrafficGraph.layoutEngine.test.tsx +193 -0
  74. package/src/components/traffic/TrafficGraph.test.tsx +269 -0
  75. package/src/components/traffic/TrafficGraph.tsx +135 -64
  76. package/src/components/traffic/TrafficGraphUnavailable.tsx +57 -0
  77. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +211 -0
  78. package/src/components/traffic/TrafficView.tsx +46 -129
  79. package/src/components/traffic/trafficFilters.test.ts +172 -1
  80. package/src/components/traffic/trafficFilters.ts +139 -0
  81. package/src/components/ui/DiagnosticsOverlay.tsx +14 -1
  82. package/src/components/ui/UpdateNotification.manual.test.tsx +5 -2
  83. package/src/components/ui/UpdateNotification.test.tsx +31 -2
  84. package/src/components/ui/UpdateNotification.tsx +34 -17
  85. package/src/components/ui/command-items.ts +24 -1
  86. package/src/components/velero/VeleroBackupNow.test.tsx +165 -0
  87. package/src/components/velero/VeleroBackupNow.tsx +143 -0
  88. package/src/components/velero/VeleroDeleteBackup.test.tsx +364 -0
  89. package/src/components/velero/VeleroDeleteBackup.tsx +306 -0
  90. package/src/components/velero/VeleroDetailPage.tsx +148 -0
  91. package/src/components/velero/VeleroKindLists.test.tsx +48 -0
  92. package/src/components/velero/VeleroKindLists.tsx +43 -0
  93. package/src/components/velero/VeleroLocations.expand.test.tsx +27 -0
  94. package/src/components/velero/VeleroLocations.test.tsx +86 -0
  95. package/src/components/velero/VeleroLocations.tsx +240 -0
  96. package/src/components/velero/VeleroOverview.test.tsx +311 -0
  97. package/src/components/velero/VeleroOverview.tsx +485 -0
  98. package/src/components/velero/VeleroPages.test.tsx +516 -0
  99. package/src/components/velero/VeleroPages.tsx +1056 -0
  100. package/src/components/velero/VeleroRunLists.tsx +309 -0
  101. package/src/components/velero/VeleroRunMessagesHost.test.tsx +25 -0
  102. package/src/components/velero/VeleroRunMessagesHost.tsx +54 -0
  103. package/src/components/velero/VeleroScheduleStatusBadge.test.tsx +28 -0
  104. package/src/components/velero/VeleroScheduleStatusBadge.tsx +21 -0
  105. package/src/components/velero/VeleroSchedules.tsx +255 -0
  106. package/src/components/velero/VeleroView.tsx +59 -0
  107. package/src/components/velero/VeleroWorkspace.gate.test.tsx +97 -0
  108. package/src/components/velero/attention.test.ts +178 -0
  109. package/src/components/velero/attention.ts +281 -0
  110. package/src/components/velero/backupDelete.test.tsx +91 -0
  111. package/src/components/velero/backupDelete.tsx +182 -0
  112. package/src/components/velero/coverage.test.ts +87 -0
  113. package/src/components/velero/coverage.ts +150 -0
  114. package/src/components/velero/host.tsx +86 -0
  115. package/src/components/velero/routes.ts +78 -0
  116. package/src/components/velero/runs.tsx +121 -0
  117. package/src/components/velero/shared.test.ts +84 -0
  118. package/src/components/velero/shared.tsx +423 -0
  119. package/src/components/velero/useVeleroSidebarWorkspace.test.tsx +28 -0
  120. package/src/components/velero/useVeleroSidebarWorkspace.ts +71 -0
  121. package/src/components/velero/velero.fixtures.ts +61 -0
  122. package/src/components/velero/workspaceRoute.ts +21 -0
  123. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +167 -0
  124. package/src/components/vulnerabilities/parts.test.ts +72 -0
  125. package/src/components/vulnerabilities/parts.tsx +291 -0
  126. package/src/components/workload/WorkloadView.tsx +64 -27
  127. package/src/components/workspace/DrawerTrailBack.tsx +32 -0
  128. package/src/components/workspace/WorkspaceFrame.tsx +71 -0
  129. package/src/components/workspace/coverage.ts +61 -0
  130. package/src/components/workspace/layout.test.tsx +29 -1
  131. package/src/components/workspace/layout.tsx +15 -5
  132. package/src/components/workspace/sidebar.ts +9 -0
  133. package/src/components/workspace/useWorkspaceDrawer.ts +63 -0
  134. package/src/components/workspace/useWorkspaceNavigate.ts +21 -0
  135. package/src/desktop/AboutDialog.test.ts +12 -0
  136. package/src/desktop/AboutDialog.tsx +151 -0
  137. package/src/desktop/WindowsTitleBar.tsx +359 -0
  138. package/src/desktop/titleBar.test.ts +61 -0
  139. package/src/desktop/titleBar.ts +45 -0
  140. package/src/index.css +19 -0
  141. package/src/integrations/resourceHost.ts +5 -1
  142. package/src/integrations/resourceHosts.test.tsx +14 -2
  143. package/src/integrations/resourceHosts.tsx +22 -6
  144. package/src/integrations/workspaceRoute.ts +1 -1
  145. package/src/integrations/workspaceRoutes.test.ts +11 -0
  146. package/src/integrations/workspaceRoutes.ts +3 -1
  147. package/src/integrations/workspaceScreens.tsx +2 -0
  148. package/src/main.tsx +8 -0
  149. package/src/utils/desktop-zoom.test.ts +53 -0
  150. package/src/utils/desktop-zoom.ts +30 -0
  151. package/src/utils/staleAssetPrompt.test.tsx +76 -0
  152. package/src/utils/staleAssetPrompt.tsx +32 -0
@@ -0,0 +1,150 @@
1
+ import type { VeleroScheduleReading } from '@skyhook-io/k8s-ui'
2
+
3
+ /** Kubernetes' own namespaces (kube-system, kube-public, kube-node-lease and add-ons' kube-*), which backups usually leave out on purpose. */
4
+ const isKubernetesNamespace = (ns: string) => ns.startsWith('kube-')
5
+
6
+ type GlobToken = { t: 'lit'; c: string } | { t: 'any' } | { t: 'star' } | { t: 'class'; chars: string; range?: [string, string] }
7
+
8
+ /**
9
+ * The longest pattern Velero accepts: with its wildcards read as letters it
10
+ * must be a namespace name, at most 63 characters.
11
+ */
12
+ const VELERO_PATTERN_MAX = 63
13
+
14
+ // Characters Velero refuses in a namespace pattern (wildcard.ValidateNamespaceName
15
+ // and the namespace-name check), so a schedule using them is rejected and backs
16
+ // up nothing.
17
+ const VELERO_PATTERN_REFUSED = /[|(){},!\\]/
18
+
19
+ function parseGlob(pattern: string): GlobToken[] | null {
20
+ const out: GlobToken[] = []
21
+ for (let i = 0; i < pattern.length; i++) {
22
+ const c = pattern[i]
23
+ if (c === '*') out.push({ t: 'star' })
24
+ else if (c === '?') out.push({ t: 'any' })
25
+ else if (c === '[') {
26
+ const end = pattern.indexOf(']', i + 1)
27
+ if (end <= i + 1) return null
28
+ const body = pattern.slice(i + 1, end)
29
+ if (body.length === 3 && body[1] === '-') {
30
+ if (body[0] > body[2]) return null
31
+ out.push({ t: 'class', chars: '', range: [body[0], body[2]] })
32
+ } else out.push({ t: 'class', chars: body })
33
+ i = end
34
+ } else out.push({ t: 'lit', c })
35
+ }
36
+ return out
37
+ }
38
+
39
+ function tokenMatches(tok: GlobToken, ch: string): boolean {
40
+ if (tok.t === 'any') return true
41
+ if (tok.t === 'lit') return tok.c === ch
42
+ if (tok.t !== 'class') return false
43
+ return tok.range ? ch >= tok.range[0] && ch <= tok.range[1] : tok.chars.includes(ch)
44
+ }
45
+
46
+ // On a mismatch it resumes after the last star, never revisiting earlier
47
+ // ones: at most pattern × name steps, both at most 63 characters.
48
+ function matchTokens(tokens: GlobToken[], name: string): boolean {
49
+ let p = 0
50
+ let n = 0
51
+ let starP = -1
52
+ let starN = 0
53
+ while (n < name.length) {
54
+ const tok = tokens[p]
55
+ if (tok?.t === 'star') {
56
+ starP = p++
57
+ starN = n
58
+ } else if (tok && tokenMatches(tok, name[n])) {
59
+ p++
60
+ n++
61
+ } else if (starP >= 0) {
62
+ p = starP + 1
63
+ n = ++starN
64
+ } else return false
65
+ }
66
+ while (tokens[p]?.t === 'star') p++
67
+ return p === tokens.length
68
+ }
69
+
70
+ /**
71
+ * A namespace pattern as Velero matches it: `*` any run, `?` one character,
72
+ * and a class, where `[a-z]` is a range only when it is exactly one;
73
+ * otherwise every character between the brackets is listed as written, so
74
+ * `[ab-d]` is a, b, - and d. A pattern Velero refuses (longer than a
75
+ * namespace name, braces, `!`, an empty or descending class) matches only
76
+ * itself. Patterns come from the cluster, so matching never goes through a
77
+ * backtracking regular expression.
78
+ */
79
+ export function veleroGlobMatch(pattern: string, name: string): boolean {
80
+ if (!/[*?[]/.test(pattern)) return pattern === name
81
+ const tokens = pattern.length <= VELERO_PATTERN_MAX && !VELERO_PATTERN_REFUSED.test(pattern) ? parseGlob(pattern) : null
82
+ return tokens ? matchTokens(tokens, name) : pattern === name
83
+ }
84
+
85
+ // Velero v1.18.2 wildcard.validateBracePatterns: every [ closes, with something
86
+ // between, and no ] stands alone.
87
+ function bracketsValid(pattern: string): boolean {
88
+ for (let i = 0; i < pattern.length; i++) {
89
+ if (pattern[i] === '[') {
90
+ const end = pattern.indexOf(']', i + 1)
91
+ if (end < 0 || end === i + 1) return false
92
+ i = end
93
+ } else if (pattern[i] === ']') return false
94
+ }
95
+ return true
96
+ }
97
+
98
+ // Velero v1.18.2 collections.validateNamespaceName: "" is allowed (Velero's "no
99
+ // namespace"); wildcard.ValidateNamespaceName refuses |()!{}, and consecutive
100
+ // asterisks; then each of * ? [ ] read as a letter must leave a namespace name.
101
+ function validNamespacePattern(pattern: string): boolean {
102
+ if (pattern === '') return true
103
+ if (/[|()!{},]/.test(pattern) || pattern.includes('**') || !bracketsValid(pattern)) return false
104
+ const asName = pattern.replace(/[*?[\]]/g, 'x')
105
+ return asName.length <= VELERO_PATTERN_MAX && /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(asName)
106
+ }
107
+
108
+ /**
109
+ * Why Velero refuses a schedule's namespace selection
110
+ * (ValidateNamespaceIncludesExcludes), or undefined when it accepts it. Velero
111
+ * then rejects the schedule, which backs up nothing.
112
+ */
113
+ export function veleroSelectionProblem(s: Pick<VeleroScheduleReading, 'includedNamespaces' | 'excludedNamespaces'>): string | undefined {
114
+ // Velero reads both lists as sets, so a repeated entry is one entry.
115
+ const inc = [...new Set(s.includedNamespaces)].sort()
116
+ const exc = [...new Set(s.excludedNamespaces)].sort()
117
+ if (inc.includes('*') && inc.length > 1) return 'it includes “*” beside other namespaces'
118
+ if (exc.includes('*')) return 'it excludes “*”'
119
+ const both = exc.find((ns) => inc.includes(ns))
120
+ if (both !== undefined) return `it both includes and excludes ${both}`
121
+ const bad = [...inc, ...exc].find((p) => !validNamespacePattern(p))
122
+ if (bad !== undefined) return `${bad} is not a namespace name or pattern Velero accepts`
123
+ return undefined
124
+ }
125
+
126
+ /** Whether a schedule's template selects the namespace, as Velero reads the selection: exclusions win, and a selection Velero refuses selects nothing. */
127
+ export function scheduleIncludes(s: Pick<VeleroScheduleReading, 'includedNamespaces' | 'excludedNamespaces'>, namespace: string): boolean {
128
+ if (veleroSelectionProblem(s)) return false
129
+ if (s.excludedNamespaces.some((p) => veleroGlobMatch(p, namespace))) return false
130
+ return s.includedNamespaces.length === 0 || s.includedNamespaces.includes('*') || s.includedNamespaces.some((p) => veleroGlobMatch(p, namespace))
131
+ }
132
+
133
+ /**
134
+ * The namespaces no schedule selects, leaving out Kubernetes' own and the
135
+ * namespaces Velero is installed in. A schedule counts whatever its state:
136
+ * this answers what is declared, and a paused or failing schedule is said
137
+ * elsewhere on the Overview.
138
+ */
139
+ export function namespacesNoScheduleIncludes(
140
+ namespaces: string[],
141
+ schedules: VeleroScheduleReading[],
142
+ installations: string[],
143
+ ): { uncovered: string[]; leftOut: number } {
144
+ const own = new Set(installations)
145
+ const listed = namespaces.filter((ns) => !isKubernetesNamespace(ns) && !own.has(ns))
146
+ return {
147
+ uncovered: listed.filter((ns) => !schedules.some((s) => scheduleIncludes(s, ns))).sort(),
148
+ leftOut: namespaces.length - listed.length,
149
+ }
150
+ }
@@ -0,0 +1,86 @@
1
+ import type { DetailSlots, HostResource, ResourceHost } from '../../integrations/resourceHost'
2
+ import type { SelectedResource } from '../../types'
3
+ import { DrawerTrailBack } from '../workspace/DrawerTrailBack'
4
+ import { VeleroBSLRenderer } from '../resources/renderers/VeleroBSLRenderer'
5
+ import { VeleroBackupRenderer } from '../resources/renderers/VeleroBackupRenderer'
6
+ import { VeleroRestoreRenderer } from '../resources/renderers/VeleroRestoreRenderer'
7
+ import { VELERO_DETAIL_KINDS, VELERO_GROUP as VELERO_GROUP_NAME, VELERO_BACKUP_KIND, VELERO_LOCATION_KIND, VELERO_RESTORE_KIND, VELERO_SCHEDULE_KIND, veleroDetailKindFor, veleroDetailPath, veleroKindListMode, VELERO_NAMESPACE_FILTER_TOOLTIP } from './routes'
8
+ import { renderVeleroSummary } from './VeleroPages'
9
+ import { VeleroBackupsKindList, VeleroLocationsKindList, VeleroRestoresKindList, VeleroSchedulesKindList } from './VeleroKindLists'
10
+ import { VeleroDeleteBackup } from './VeleroDeleteBackup'
11
+ import { VeleroBackupNow } from './VeleroBackupNow'
12
+ import { VeleroScheduleStatusBadge } from './VeleroScheduleStatusBadge'
13
+ import { VeleroRunIssueMessages } from './VeleroRunMessagesHost'
14
+ import { kindToPluralWithGroup } from '../../utils/navigation'
15
+ import { isApiGroup } from '@skyhook-io/k8s-ui'
16
+
17
+ const KIND_BY_PLURAL: Record<string, string> = {
18
+ backups: 'Backup',
19
+ restores: 'Restore',
20
+ schedules: 'Schedule',
21
+ backupstoragelocations: 'BackupStorageLocation',
22
+ backuprepositories: 'BackupRepository',
23
+ volumesnapshotlocations: 'VolumeSnapshotLocation',
24
+ }
25
+
26
+ function VeleroDrawerTrailBack({ resource }: { resource: SelectedResource }) {
27
+ return <DrawerTrailBack resource={resource} pathPrefix="/velero" kindLabel={(plural) => KIND_BY_PLURAL[plural]} />
28
+ }
29
+
30
+ function detailKind(resource: HostResource): string | null {
31
+ return veleroDetailKindFor(kindToPluralWithGroup(resource.kind, resource.group ?? ''), resource.group)
32
+ }
33
+
34
+ export const veleroResourceHost: ResourceHost = {
35
+ id: 'velero',
36
+ feature: 'veleroWorkspace',
37
+ renderers: { VeleroBSLRenderer, VeleroBackupRenderer, VeleroRestoreRenderer },
38
+ drawerNavigation: {
39
+ ownsPath: (pathname) => pathname === '/velero' || pathname.startsWith('/velero/'),
40
+ Component: VeleroDrawerTrailBack,
41
+ },
42
+ resources: Object.keys(VELERO_DETAIL_KINDS).map((name) => ({ name, group: VELERO_GROUP_NAME })),
43
+ // Each of these kinds has a page of its own (/velero/<plural>/<ns>/<name>):
44
+ // "Open full view" and links to the generic detail land there.
45
+ expandedPath: (resource, context, tab) => {
46
+ const plural = detailKind(resource)
47
+ return plural ? veleroDetailPath({ plural, namespace: resource.namespace, name: resource.name }, context, tab) : null
48
+ },
49
+ detailRedirect: (resource, search) => {
50
+ const plural = detailKind(resource)
51
+ if (!plural) return null
52
+ const params = new URLSearchParams(search)
53
+ params.delete('apiGroup')
54
+ const base = veleroDetailPath({ plural, namespace: resource.namespace, name: resource.name })
55
+ const qs = params.toString()
56
+ return qs ? `${base}?${qs}` : base
57
+ },
58
+ detailOwnership: ['summary', 'destination'],
59
+ // The composed Overview, on the page and in the drawer (the renderer is
60
+ // Spec & status); a backup's Delete backup; and a schedule's header: its
61
+ // reading as the status chip, and Back up now in the action row with every
62
+ // resource's actions.
63
+ detailSlots: (resource): DetailSlots => {
64
+ const summary: DetailSlots = { renderSummary: (props) => renderVeleroSummary(props) }
65
+ if (detailKind(resource) === VELERO_BACKUP_KIND.name) return {
66
+ ...summary,
67
+ renderHeaderActions: ({ resource: data }) => isApiGroup(data?.apiVersion, VELERO_GROUP_NAME) ? <VeleroDeleteBackup backup={data} /> : null,
68
+ }
69
+ if (kindToPluralWithGroup(resource.kind, resource.group ?? VELERO_GROUP_NAME) !== VELERO_SCHEDULE_KIND.name) return summary
70
+ return {
71
+ ...summary,
72
+ renderStatusBadge: (data: any) => <VeleroScheduleStatusBadge resource={data} />,
73
+ renderHeaderActions: ({ resource: data, onNavigate }) =>
74
+ isApiGroup(data?.apiVersion, VELERO_GROUP_NAME) ? <VeleroBackupNow schedule={data} onNavigate={onNavigate} /> : null,
75
+ }
76
+ },
77
+ // A failed run's messages are what is wrong with it.
78
+ issueDetail: (props) => <VeleroRunIssueMessages {...props} />,
79
+ // Radar's own tables are these kinds' lists, so none has a second entry in the sidebar.
80
+ kindLists: [
81
+ { kind: VELERO_SCHEDULE_KIND, title: 'Velero schedules', mode: veleroKindListMode, namespaceFilterTooltip: VELERO_NAMESPACE_FILTER_TOOLTIP, Component: VeleroSchedulesKindList },
82
+ { kind: VELERO_LOCATION_KIND, title: 'Velero storage locations', mode: veleroKindListMode, namespaceFilterTooltip: VELERO_NAMESPACE_FILTER_TOOLTIP, Component: VeleroLocationsKindList },
83
+ { kind: VELERO_BACKUP_KIND, title: 'Velero backups', mode: veleroKindListMode, namespaceFilterTooltip: VELERO_NAMESPACE_FILTER_TOOLTIP, Component: VeleroBackupsKindList },
84
+ { kind: VELERO_RESTORE_KIND, title: 'Velero restores', mode: veleroKindListMode, namespaceFilterTooltip: VELERO_NAMESPACE_FILTER_TOOLTIP, Component: VeleroRestoresKindList },
85
+ ],
86
+ }
@@ -0,0 +1,78 @@
1
+ import type { RadarFeatureSupport } from '../../api/radarFeatures'
2
+
3
+ export const VELERO_GROUP = 'velero.io'
4
+
5
+ /** The one Velero view; Radar's Schedule, storage-location, Backup and Restore tables are those kinds' lists. */
6
+ export const VELERO_OVERVIEW = { label: 'Overview', title: 'Velero overview', path: '/velero' }
7
+
8
+ /** The namespace picker's tooltip on every Velero screen: Velero keeps its objects in its own namespace, so the filter would empty the views. */
9
+ export const VELERO_NAMESPACE_FILTER_TOOLTIP = 'Velero is shown for every installation you can read — the namespace filter doesn’t apply here.'
10
+
11
+ export const VELERO_SCHEDULES_PATH = '/resources/schedules?apiGroup=velero.io'
12
+ export const VELERO_LOCATIONS_PATH = '/resources/backupstoragelocations?apiGroup=velero.io'
13
+
14
+ export const VELERO_SCHEDULE_KIND = { name: 'schedules', kind: 'Schedule', group: VELERO_GROUP }
15
+ export const VELERO_LOCATION_KIND = { name: 'backupstoragelocations', kind: 'BackupStorageLocation', group: VELERO_GROUP }
16
+ export const VELERO_BACKUP_KIND = { name: 'backups', kind: 'Backup', group: VELERO_GROUP }
17
+ export const VELERO_RESTORE_KIND = { name: 'restores', kind: 'Restore', group: VELERO_GROUP }
18
+
19
+ /**
20
+ * A Velero Backup's kind. Its generic Delete removes only the object: the
21
+ * backup stays in storage and Velero recreates the object from it.
22
+ */
23
+ export function isVeleroBackupKind(plural: string | undefined, group: string | undefined): boolean {
24
+ return veleroDetailKindFor(plural ?? '', group) === VELERO_BACKUP_KIND.name
25
+ }
26
+
27
+ /**
28
+ * What a Velero kind's Resources route shows when Radar has a richer list for
29
+ * it (Schedule, BackupStorageLocation, Backup, Restore): that list when this
30
+ * Radar serves the Velero views; a loader while capabilities load for the
31
+ * first time, so the generic table never flashes before it; otherwise the
32
+ * generic table.
33
+ */
34
+ export function veleroKindListMode(support: RadarFeatureSupport, capabilitiesPending: boolean): 'view' | 'wait' | 'table' {
35
+ if (support === 'supported') return 'view'
36
+ return support === 'unknown' && capabilitiesPending ? 'wait' : 'table'
37
+ }
38
+
39
+ /** The Velero kinds with a page of their own, and the kind list each one's crumb returns to. */
40
+ export const VELERO_DETAIL_KINDS: Record<string, { kind: string; label: string; listPath: string }> = {
41
+ backups: { kind: 'Backup', label: 'Backups', listPath: '/resources/backups?apiGroup=velero.io' },
42
+ restores: { kind: 'Restore', label: 'Restores', listPath: '/resources/restores?apiGroup=velero.io' },
43
+ schedules: { kind: 'Schedule', label: 'Schedules', listPath: VELERO_SCHEDULES_PATH },
44
+ backupstoragelocations: { kind: 'BackupStorageLocation', label: 'Storage locations', listPath: VELERO_LOCATIONS_PATH },
45
+ }
46
+
47
+ export interface VeleroDetailTarget {
48
+ plural: string
49
+ namespace: string
50
+ name: string
51
+ }
52
+
53
+ export function veleroDetailKindFor(plural: string, group: string | undefined): string | null {
54
+ const p = plural.toLowerCase()
55
+ return group === VELERO_GROUP && VELERO_DETAIL_KINDS[p] ? p : null
56
+ }
57
+
58
+ /** `/velero` is the Overview; `/velero/<plural>/<namespace>/<name>` an object's page. */
59
+ export function parseVeleroRoute(pathname: string): { detail?: VeleroDetailTarget } {
60
+ const seg = pathname.replace(/^\/+/, '').split('/').map((s) => {
61
+ try {
62
+ return decodeURIComponent(s)
63
+ } catch {
64
+ return s
65
+ }
66
+ })
67
+ if (seg[0] !== 'velero' || !VELERO_DETAIL_KINDS[seg[1] ?? ''] || !seg[2] || !seg[3]) return {}
68
+ return { detail: { plural: seg[1], namespace: seg[2], name: seg[3] } }
69
+ }
70
+
71
+ /** An object's page; `ctx` pins the Kubernetes context it belongs to. */
72
+ export function veleroDetailPath(target: VeleroDetailTarget, ctx?: string, tab?: string): string {
73
+ const params = new URLSearchParams()
74
+ if (ctx) params.set('ctx', ctx)
75
+ if (tab) params.set('tab', tab)
76
+ const qs = params.toString()
77
+ return `/velero/${target.plural}/${encodeURIComponent(target.namespace)}/${encodeURIComponent(target.name)}${qs ? `?${qs}` : ''}`
78
+ }
@@ -0,0 +1,121 @@
1
+ import { useState, type ReactNode } from 'react'
2
+ import { Tooltip, formatDuration, formatRelativeAgeTime, getBackupStatus, getRestoreStatus, toneTextClass, veleroLocalTime, veleroMomentText, veleroPlainReason, VELERO_FAILED_PHASES } from '@skyhook-io/k8s-ui'
3
+ import type { VeleroRunRow, VeleroRunsResponse } from '../../api/velero'
4
+ import { WholeNames } from './shared'
5
+ import { Notice } from '../workspace/layout'
6
+ import { INCOMPLETE_COVERAGE_STATES, coverageEmpty, coverageLabel } from '../workspace/coverage'
7
+
8
+ // How a Velero run (a Backup or Restore) reads in the lists and on the pages.
9
+
10
+ export function expired(expiration: string | undefined): boolean {
11
+ return !!expiration && new Date(expiration).getTime() < Date.now()
12
+ }
13
+
14
+ export function durationText(start?: string, end?: string): string | undefined {
15
+ if (!start || !end) return undefined
16
+ return formatDuration(Math.max(0, Date.parse(end) - Date.parse(start)), true)
17
+ }
18
+
19
+ export function Outcome({ badge }: { badge: { text: string; color: string } }) {
20
+ return <span className={`badge whitespace-nowrap ${badge.color}`}>{badge.text}</span>
21
+ }
22
+
23
+ export function RunOutcome({ kind, phase }: { kind: 'Backup' | 'Restore'; phase?: string }) {
24
+ const resource = { status: { phase } }
25
+ return <Outcome badge={kind === 'Backup' ? getBackupStatus(resource) : getRestoreStatus(resource)} />
26
+ }
27
+
28
+ export const FAILED = VELERO_FAILED_PHASES
29
+ // Velero refused the run or it failed outright; the rest of FAILED partly failed.
30
+ const FAILED_OUTRIGHT = new Set(['Failed', 'FailedValidation'])
31
+
32
+ /** Why a run failed, under its outcome: Radar's plain reading when it has one, Velero's text on hover. */
33
+ export function RunReason({ run }: { run: Pick<VeleroRunRow, 'phase' | 'reason'> }) {
34
+ if (!run.reason || !FAILED.has(run.phase ?? '')) return null
35
+ const plain = veleroPlainReason(run.reason)
36
+ return (
37
+ <Tooltip content={run.reason}>
38
+ <div className={`mt-0.5 line-clamp-2 min-w-0 break-words text-xs ${toneTextClass(FAILED_OUTRIGHT.has(run.phase ?? '') ? 'unhealthy' : 'degraded')}`}><WholeNames text={plain ?? run.reason} /></div>
39
+ </Tooltip>
40
+ )
41
+ }
42
+
43
+ export function When({ iso, fallback }: { iso?: string; fallback: string }) {
44
+ if (!iso) return <span className="text-theme-text-tertiary">{fallback}</span>
45
+ return (
46
+ <Tooltip content={veleroLocalTime(iso)}>
47
+ <span>{formatRelativeAgeTime(iso)}</span>
48
+ </Tooltip>
49
+ )
50
+ }
51
+
52
+ /** When a backup's retention ends. */
53
+ export function Expires({ iso }: { iso?: string }) {
54
+ if (!iso) return <span className="text-theme-text-tertiary">—</span>
55
+ if (expired(iso)) {
56
+ return (
57
+ <Tooltip content={`${veleroLocalTime(iso)} · eligible for garbage collection`}>
58
+ <span className="text-theme-text-tertiary">expired</span>
59
+ </Tooltip>
60
+ )
61
+ }
62
+ return (
63
+ <Tooltip content={veleroLocalTime(iso)}>
64
+ <span>{veleroMomentText(iso)}</span>
65
+ </Tooltip>
66
+ )
67
+ }
68
+
69
+ /** "0 · 2": errors and warnings, each coloured only when there are some. */
70
+ export function RunCounts({ errors, warnings }: { errors: number; warnings: number }) {
71
+ return (
72
+ <span className="tabular-nums">
73
+ <span className={errors > 0 ? toneTextClass('unhealthy') : 'text-theme-text-tertiary'}>{errors}</span>
74
+ <span className="text-theme-text-tertiary"> · </span>
75
+ <span className={warnings > 0 ? toneTextClass('degraded') : 'text-theme-text-tertiary'}>{warnings}</span>
76
+ </span>
77
+ )
78
+ }
79
+
80
+ /** All runs, newest first, or only the failed ones. Opens on all, so a run in progress is in view. */
81
+ export function useRunView<R extends VeleroRunRow>(rows: R[]) {
82
+ const failed = rows.filter((r) => FAILED.has(r.phase ?? ''))
83
+ const [view, setView] = useState<'all' | 'failed'>('all')
84
+ return { failed, view, setView, shown: view === 'failed' ? failed : rows }
85
+ }
86
+
87
+ /** A count over what was read: exact only when the read covered everything. */
88
+ export function boundedCount(n: number, query: { data?: VeleroRunsResponse }): string {
89
+ const partial = !query.data || INCOMPLETE_COVERAGE_STATES.has(query.data.coverage.state) || query.data.truncated
90
+ return partial && n > 0 ? `≥${n}` : String(n)
91
+ }
92
+
93
+ /** The All and Failed segments; the failed count is red when there are any. */
94
+ export function runViewOptions(failed: number, all: number, query: { data?: VeleroRunsResponse }) {
95
+ const failedCount = boundedCount(failed, query)
96
+ return [
97
+ { id: 'all' as const, label: 'All', count: boundedCount(all, query) },
98
+ { id: 'failed' as const, label: 'Failed', count: failed > 0 ? <span className={toneTextClass('unhealthy')}>{failedCount}</span> : failedCount },
99
+ ]
100
+ }
101
+
102
+ /** Why a run list is empty, or that what was read holds no match. */
103
+ export function runsEmpty(query: { data?: VeleroRunsResponse; isPending: boolean; error: unknown }, noun: string, filtered: string): string {
104
+ if (query.isPending) return `Loading ${noun}…`
105
+ if (!query.data) return `${noun[0].toUpperCase()}${noun.slice(1)} could not be read: ${(query.error as Error | null)?.message ?? 'unknown error'}`
106
+ const cov = query.data.coverage
107
+ if (INCOMPLETE_COVERAGE_STATES.has(cov.state)) return `${filtered} in what Radar could read (${coverageLabel(cov)}).`
108
+ if (query.data.runs.length === 0) return coverageEmpty(cov, noun)
109
+ // Only the newest were sent, so an older match may exist.
110
+ return query.data.truncated ? `${filtered} in the newest ${query.data.runs.length.toLocaleString('en-US')}.` : `${filtered}.`
111
+ }
112
+
113
+ /** A read that failed or is partial, said above the rows it leaves. */
114
+ export function RunsReadNotice({ query, noun }: { query: { data?: VeleroRunsResponse; error: unknown }; noun: string }) {
115
+ const notes: ReactNode[] = []
116
+ if (query.error && query.data) notes.push(`The last refresh of ${noun} failed (${(query.error as Error).message}); what is shown is from before it.`)
117
+ if (query.data && INCOMPLETE_COVERAGE_STATES.has(query.data.coverage.state)) notes.push(`Some ${noun} were not read: ${coverageLabel(query.data.coverage)}. Counts are lower bounds.`)
118
+ if (query.data?.truncated) notes.push(`Only the newest ${query.data.runs.length} of ${query.data.total} ${noun} are listed.`)
119
+ if (notes.length === 0) return null
120
+ return <Notice>{notes.map((n, i) => <div key={i}>{n}</div>)}</Notice>
121
+ }
@@ -0,0 +1,84 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { restoredIntoText, selectionText } from './shared'
3
+
4
+ // Specs as Velero 1.18 leaves them after processing: it writes these
5
+ // exclusions into every Backup and Restore itself.
6
+ const processedBackup = {
7
+ includedNamespaces: ['*'],
8
+ excludedClusterScopedResources: ['volumesnapshotcontents.snapshot.storage.k8s.io'],
9
+ excludedNamespaceScopedResources: ['volumesnapshots.snapshot.storage.k8s.io'],
10
+ storageLocation: 'default',
11
+ ttl: '720h0m0s',
12
+ }
13
+ const processedBackupOldFilters = {
14
+ includedNamespaces: ['demo'],
15
+ excludedResources: ['volumesnapshots.snapshot.storage.k8s.io', 'volumesnapshotcontents.snapshot.storage.k8s.io'],
16
+ }
17
+ const processedRestore = {
18
+ backupName: 'nightly-1',
19
+ includedNamespaces: ['*'],
20
+ excludedResources: [
21
+ 'nodes',
22
+ 'events',
23
+ 'events.events.k8s.io',
24
+ 'backups.velero.io',
25
+ 'restores.velero.io',
26
+ 'resticrepositories.velero.io',
27
+ 'csinodes.storage.k8s.io',
28
+ 'volumeattachments.storage.k8s.io',
29
+ 'backuprepositories.velero.io',
30
+ ],
31
+ }
32
+
33
+ describe('a Velero selection', () => {
34
+ it('is not narrowed by the exclusions Velero adds itself', () => {
35
+ expect(selectionText(processedBackup, 'All namespaces')).toEqual({ text: 'All namespaces', narrowed: false })
36
+ expect(selectionText(processedBackupOldFilters, 'All namespaces')).toEqual({ text: 'demo', narrowed: false })
37
+ expect(selectionText(processedRestore, '', 'restore').narrowed).toBe(false)
38
+ expect(selectionText({ includedResources: ['*'] }, '').narrowed).toBe(false)
39
+ })
40
+
41
+ it('is narrowed by a filter the user added beside them', () => {
42
+ expect(selectionText({ ...processedBackup, excludedNamespaceScopedResources: [...processedBackup.excludedNamespaceScopedResources, 'secrets'] }, '').narrowed).toBe(true)
43
+ expect(selectionText({ ...processedBackup, includedClusterScopedResources: ['persistentvolumes'] }, '').narrowed).toBe(true)
44
+ expect(selectionText({ ...processedRestore, excludedResources: [...processedRestore.excludedResources, 'secrets'] }, '', 'restore').narrowed).toBe(true)
45
+ expect(selectionText({ ...processedRestore, labelSelector: { matchLabels: { app: 'x' } } }, '', 'restore').narrowed).toBe(true)
46
+ })
47
+
48
+ it('is narrowed by a wildcard exclusion, which drops a whole scope', () => {
49
+ expect(selectionText({ ...processedBackup, excludedNamespaceScopedResources: ['*'] }, '').narrowed).toBe(true)
50
+ expect(selectionText({ ...processedBackup, excludedClusterScopedResources: ['*'] }, '').narrowed).toBe(true)
51
+ expect(selectionText({ excludedResources: ['*'] }, '').narrowed).toBe(true)
52
+ // In an include list it means everything.
53
+ expect(selectionText({ ...processedBackup, includedNamespaceScopedResources: ['*'], includedClusterScopedResources: ['*'] }, '').narrowed).toBe(false)
54
+ })
55
+
56
+ it('only marks label selection as narrowed when its selectors restrict the objects', () => {
57
+ const byApp = { matchLabels: { app: 'api' } }
58
+ const byTier = { matchExpressions: [{ key: 'tier', operator: 'Exists' }] }
59
+ expect(selectionText({ orLabelSelectors: [byApp, byTier] }, 'All namespaces').narrowed).toBe(true)
60
+ expect(selectionText({ orLabelSelectors: [byApp, {}] }, 'All namespaces').narrowed).toBe(false)
61
+ expect(selectionText({ labelSelector: {} }, 'All namespaces').narrowed).toBe(false)
62
+ })
63
+
64
+ it('counts a restore exclusion on a backup, where Velero does not add it', () => {
65
+ expect(selectionText({ excludedResources: ['nodes'] }, '').narrowed).toBe(true)
66
+ })
67
+ })
68
+
69
+ describe('where a restore puts things', () => {
70
+ it('names every included namespace, with the mapped one’s destination', () => {
71
+ expect(restoredIntoText({ includedNamespaces: ['demo', 'shop'], namespaceMapping: { demo: 'demo-copy' } })).toBe('demo → demo-copy, shop')
72
+ })
73
+
74
+ it('reads all namespaces with a mapping as every namespace, with that mapping', () => {
75
+ expect(restoredIntoText({ includedNamespaces: ['*'], namespaceMapping: { demo: 'demo-copy' } })).toBe('Every namespace in the backup, with demo → demo-copy')
76
+ expect(restoredIntoText({ includedNamespaces: [], excludedNamespaces: [] })).toBe('Every namespace in the backup')
77
+ })
78
+
79
+ it('drops the mapping of an excluded namespace, which Velero restores nothing from', () => {
80
+ expect(restoredIntoText({ includedNamespaces: [], excludedNamespaces: ['demo'], namespaceMapping: { demo: 'demo-copy', shop: 'shop-copy' } })).toBe(
81
+ 'Every namespace in the backup, with shop → shop-copy, except demo',
82
+ )
83
+ })
84
+ })