Skip to content

Commit 2e72c18

Browse files
fix(dashboard): distinguish unknown upload state from a negative answer
Second review round on the VMDisk upload panel. An errored CDIConfig read rendered as "this cluster publishes no upload proxy URL". With retry disabled and Refresh refetching only the DataVolume, a single failed cdiconfigs GET pinned that false claim until a full page reload. Gate the warning on the read having succeeded, add a distinct branch for the errored case, and make Refresh refetch both reads. The panel also never auto-advanced: the DataVolume query had no refetchInterval, the parent's poll is on a different query key, and the panel never unmounts, so a disk reaching UploadReady kept showing "preparing". Poll every 5s while the stage is preparing, and only for a disk this panel actually renders — the other vm-disk sources render nothing, so polling for them is pure load. Finally, the virtctl command was offered on a failed disk, which the module's own invariant says is wrong: `failed` covers PVC-bind failures where no upload server was ever created, and CDI does not recreate the pod for a DataVolume that already failed. Withhold the command and tell the user to recreate the disk instead; the failure reason still renders. Also rewords the cdiconfigs RBAC comment, which asserted a system:authenticated binding this repo does not provide. Signed-off-by: Myasnikov Daniil <[email protected]>
1 parent 04bd52f commit 2e72c18

2 files changed

Lines changed: 180 additions & 13 deletions

File tree

‎packages/system/dashboard/images/console/apps/console/src/routes/detail/DiskUploadPanel.test.tsx‎

Lines changed: 134 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { describe, it, expect, vi, afterEach } from "vitest"
2-
import { screen, waitFor, cleanup, fireEvent } from "@testing-library/react"
2+
import { act, screen, waitFor, cleanup, fireEvent } from "@testing-library/react"
33
import { K8sClient } from "@cozystack/k8s-client"
44
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
55
import { DiskUploadPanel } from "./DiskUploadPanel.tsx"
6+
import type { DataVolume } from "../../lib/vm-disk-upload.ts"
67
import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types"
78

89
const ad: ApplicationDefinition = {
@@ -20,6 +21,25 @@ const ad: ApplicationDefinition = {
2021
},
2122
}
2223

24+
/**
25+
* The same application without an explicit `release.prefix`. `releasePrefix`
26+
* then falls back to `<singular>-`, and the panel has to name the DataVolume
27+
* the same way the chart does.
28+
*/
29+
const adWithoutPrefix: ApplicationDefinition = {
30+
apiVersion: "cozystack.io/v1alpha1",
31+
kind: "ApplicationDefinition",
32+
metadata: { name: "vm-disk" },
33+
spec: {
34+
application: {
35+
kind: "VMDisk",
36+
plural: "vmdisks",
37+
singular: "vmdisk",
38+
openAPISchema: "{}",
39+
},
40+
},
41+
}
42+
2343
const instance: ApplicationInstance = {
2444
apiVersion: "apps.cozystack.io/v1alpha1",
2545
kind: "VMDisk",
@@ -29,17 +49,24 @@ const instance: ApplicationInstance = {
2949
interface ClusterFixture {
3050
source?: Record<string, unknown>
3151
phase?: string
52+
/** Successive DataVolume phases, one per GET; the last one repeats. */
53+
phases?: string[]
54+
conditions?: NonNullable<DataVolume["status"]>["conditions"]
3255
dvError?: Error
3356
uploadProxyURL?: string
57+
cdiConfigError?: Error
3458
canUpload?: boolean
3559
ssarError?: Error
3660
}
3761

3862
function makeClient(fixture: ClusterFixture) {
3963
const client = new K8sClient()
64+
const phases = fixture.phases ?? [fixture.phase ?? "UploadReady"]
65+
let dvReads = 0
4066
vi.spyOn(client, "get").mockImplementation(
4167
async (_g: string, _v: string, plural: string, name: string) => {
4268
if (plural === "cdiconfigs") {
69+
if (fixture.cdiConfigError) throw fixture.cdiConfigError
4370
return {
4471
apiVersion: "cdi.kubevirt.io/v1beta1",
4572
kind: "CDIConfig",
@@ -50,12 +77,13 @@ function makeClient(fixture: ClusterFixture) {
5077
}
5178
}
5279
if (fixture.dvError) throw fixture.dvError
80+
const phase = phases[Math.min(dvReads++, phases.length - 1)]
5381
return {
5482
apiVersion: "cdi.kubevirt.io/v1beta1",
5583
kind: "DataVolume",
5684
metadata: { name, namespace: "tenant-root" },
5785
spec: { source: fixture.source ?? { upload: {} } },
58-
status: { phase: fixture.phase ?? "UploadReady" },
86+
status: { phase, conditions: fixture.conditions },
5987
}
6088
},
6189
)
@@ -72,8 +100,15 @@ function makeClient(fixture: ClusterFixture) {
72100
return client
73101
}
74102

103+
/** How many times the panel has read the DataVolume through this client. */
104+
function dvReads(client: K8sClient): number {
105+
const get = client.get as unknown as { mock: { calls: unknown[][] } }
106+
return get.mock.calls.filter((c) => c[2] === "datavolumes").length
107+
}
108+
75109
afterEach(() => {
76110
cleanup()
111+
vi.useRealTimers()
77112
vi.restoreAllMocks()
78113
// jsdom exposes no clipboard; drop the one the copy test installs.
79114
Reflect.deleteProperty(navigator, "clipboard")
@@ -94,6 +129,39 @@ describe("DiskUploadPanel visibility", () => {
94129
)
95130
})
96131

132+
it("names the DataVolume from the singular when the definition sets no prefix", async () => {
133+
const client = makeClient({})
134+
renderWithK8sProvider(
135+
<DiskUploadPanel ad={adWithoutPrefix} instance={instance} />,
136+
{ client },
137+
)
138+
await waitFor(() =>
139+
expect(client.get).toHaveBeenCalledWith(
140+
"cdi.kubevirt.io",
141+
"v1beta1",
142+
"datavolumes",
143+
"vmdisk-demo",
144+
"tenant-root",
145+
),
146+
)
147+
})
148+
149+
it("reads CDIConfig cluster-scoped, not from the instance namespace", async () => {
150+
const client = makeClient({})
151+
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
152+
// CDIConfig is a cluster-scoped singleton; a namespace here builds
153+
// /namespaces/tenant-root/cdiconfigs/config, which is a 404.
154+
await waitFor(() =>
155+
expect(client.get).toHaveBeenCalledWith(
156+
"cdi.kubevirt.io",
157+
"v1beta1",
158+
"cdiconfigs",
159+
"config",
160+
undefined,
161+
),
162+
)
163+
})
164+
97165
it("renders nothing for a disk with a non-upload source", async () => {
98166
const client = makeClient({ source: { http: { url: "https://example.org/i.qcow2" } } })
99167
const { container } = renderWithK8sProvider(
@@ -104,6 +172,18 @@ describe("DiskUploadPanel visibility", () => {
104172
expect(container).toBeEmptyDOMElement()
105173
})
106174

175+
it("does not poll a disk whose panel renders nothing", async () => {
176+
vi.useFakeTimers({ shouldAdvanceTime: true })
177+
const client = makeClient({
178+
source: { http: { url: "https://example.org/i.qcow2" } },
179+
phase: "Pending",
180+
})
181+
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
182+
await waitFor(() => expect(dvReads(client)).toBe(1))
183+
await act(() => vi.advanceTimersByTimeAsync(15_000))
184+
expect(dvReads(client)).toBe(1)
185+
})
186+
107187
it("renders nothing when the DataVolume cannot be read", async () => {
108188
const client = makeClient({ dvError: new Error("forbidden") })
109189
const { container } = renderWithK8sProvider(
@@ -126,6 +206,24 @@ describe("DiskUploadPanel states", () => {
126206
expect(screen.queryByText(/publishes no upload proxy URL/)).not.toBeInTheDocument()
127207
})
128208

209+
it("renders the whole awaiting-upload panel, not just the badge", async () => {
210+
const client = makeClient({ uploadProxyURL: "https://cdi-uploadproxy.example.org" })
211+
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
212+
expect(
213+
await screen.findByRole("heading", { name: "Image upload" }),
214+
).toBeInTheDocument()
215+
expect(
216+
screen.getByText("This disk was created from an uploaded image."),
217+
).toBeInTheDocument()
218+
expect(await screen.findByText("Waiting for an image")).toBeInTheDocument()
219+
expect(screen.getByText("UploadReady")).toBeInTheDocument()
220+
// The panel exists to say the upload cannot happen in the browser; the
221+
// command alone does not say that.
222+
const guidance = screen.getByText(/the browser cannot reach the CDI/)
223+
expect(guidance.textContent).toContain("--image-path")
224+
expect(screen.getByRole("button", { name: "Copy command" })).toBeInTheDocument()
225+
})
226+
129227
it("flags the placeholder when the cluster published no proxy URL", async () => {
130228
const client = makeClient({})
131229
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
@@ -140,25 +238,56 @@ describe("DiskUploadPanel states", () => {
140238
expect(cmd.textContent).toContain("cdi-uploadproxy.<your-cozystack-domain>")
141239
})
142240

241+
it("does not report an unreadable CDIConfig as a cluster with no proxy URL", async () => {
242+
const client = makeClient({ cdiConfigError: new Error("forbidden") })
243+
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
244+
expect(await screen.findByText(/could not be read/)).toBeInTheDocument()
245+
expect(screen.queryByText(/publishes no upload proxy URL/)).not.toBeInTheDocument()
246+
})
247+
143248
it("withholds the command before the upload target exists", async () => {
144249
const client = makeClient({ phase: "Pending" })
145250
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
146251
expect(await screen.findByText("Preparing upload target")).toBeInTheDocument()
147252
expect(screen.queryByText(/virtctl image-upload/)).not.toBeInTheDocument()
148253
})
149254

255+
it("advances from Pending to UploadReady without a manual refresh", async () => {
256+
vi.useFakeTimers({ shouldAdvanceTime: true })
257+
const client = makeClient({ phases: ["Pending", "UploadReady"] })
258+
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
259+
expect(await screen.findByText("Preparing upload target")).toBeInTheDocument()
260+
expect(screen.queryByText(/virtctl image-upload/)).not.toBeInTheDocument()
261+
await act(() => vi.advanceTimersByTimeAsync(5_000))
262+
expect(await screen.findByText("Waiting for an image")).toBeInTheDocument()
263+
expect(await screen.findByText(/virtctl image-upload/)).toBeInTheDocument()
264+
// ...and the poll stops there: UploadReady is where CDI waits for the
265+
// user, so polling on would be load with nothing to observe.
266+
const reads = dvReads(client)
267+
await act(() => vi.advanceTimersByTimeAsync(15_000))
268+
expect(dvReads(client)).toBe(reads)
269+
})
270+
150271
it("withholds the command once the image is written", async () => {
151272
const client = makeClient({ phase: "Succeeded" })
152273
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
153274
expect(await screen.findByText("Image uploaded")).toBeInTheDocument()
154275
expect(screen.queryByText(/virtctl image-upload/)).not.toBeInTheDocument()
155276
})
156277

157-
it("offers the command again after a failed upload", async () => {
158-
const client = makeClient({ phase: "Failed" })
278+
it("withholds the command after a failure and says to recreate the disk", async () => {
279+
// A Failed DataVolume has no upload server to talk to — CDI never
280+
// recreates one — and the phase covers bind failures where none existed.
281+
const client = makeClient({
282+
phase: "Failed",
283+
conditions: [{ type: "Bound", status: "False", message: "no capacity" }],
284+
})
159285
renderWithK8sProvider(<DiskUploadPanel ad={ad} instance={instance} />, { client })
160286
expect(await screen.findByText("Upload failed")).toBeInTheDocument()
161-
expect(await screen.findByText(/virtctl image-upload/)).toBeInTheDocument()
287+
expect(screen.queryByText(/virtctl image-upload/)).not.toBeInTheDocument()
288+
expect(screen.getByText(/Recreate the disk/)).toBeInTheDocument()
289+
// The reason CDI gave must survive: it is the only clue the user gets.
290+
expect(screen.getByText("no capacity")).toBeInTheDocument()
162291
})
163292
})
164293

‎packages/system/dashboard/images/console/apps/console/src/routes/detail/DiskUploadPanel.tsx‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,28 @@ export function DiskUploadPanel({
9797
name: dvName,
9898
namespace: ns,
9999
},
100-
{ enabled: !!ns && !!instance.metadata.name, retry: false },
100+
{
101+
enabled: !!ns && !!instance.metadata.name,
102+
retry: false,
103+
// CDI walks the disk to UploadReady on its own and this panel never
104+
// unmounts, so without a poll the user sits on "preparing" until they
105+
// happen to press Refresh. Matches the detail page's instance poll.
106+
// Gated on the source too: the panel renders nothing for the other
107+
// vm-disk sources, and polling for a hidden panel is pure load.
108+
refetchInterval: (query) => {
109+
const dv = query.state.data
110+
return isUploadSource(dv) && uploadState(dv).stage === "preparing"
111+
? 5000
112+
: false
113+
},
114+
},
101115
)
102116

103-
// CDI binds a config-reader role to system:authenticated, so every logged-in
104-
// user can read the proxy URL the platform published (empty unless the
105-
// kubevirt-cdi chart was given uploadProxyURL).
117+
// The proxy URL lives on the cluster-scoped CDIConfig singleton, and whether
118+
// a tenant may read it is up to what upstream CDI binds — this repo grants no
119+
// role of its own for it. So a failed read means "unknown", never "the
120+
// cluster published none". The field is empty anyway unless the kubevirt-cdi
121+
// chart was given uploadProxyURL.
106122
const cdiConfig = useK8sGet<CDIConfig>(
107123
{
108124
apiGroup: CDI_GROUP,
@@ -132,7 +148,10 @@ export function DiskUploadPanel({
132148
namespace: ns,
133149
uploadProxyURL: proxyURL,
134150
})
135-
const showCommand = state.stage === "awaiting-upload" || state.stage === "failed"
151+
// Only at awaiting-upload: `failed` covers PVC-bind failures where no upload
152+
// server was ever created, and CDI does not recreate one for a DataVolume
153+
// that already failed — the disk has to be recreated instead.
154+
const showCommand = state.stage === "awaiting-upload"
136155

137156
return (
138157
<div className="px-6 pt-6">
@@ -143,8 +162,11 @@ export function DiskUploadPanel({
143162
<Button
144163
variant="outline"
145164
size="sm"
146-
onClick={() => void dvQuery.refetch()}
147-
disabled={dvQuery.isFetching}
165+
onClick={() => {
166+
void dvQuery.refetch()
167+
void cdiConfig.refetch()
168+
}}
169+
disabled={dvQuery.isFetching || cdiConfig.isFetching}
148170
>
149171
<RefreshCw className="size-3.5" /> Refresh
150172
</Button>
@@ -176,6 +198,13 @@ export function DiskUploadPanel({
176198
</p>
177199
)}
178200

201+
{state.stage === "failed" && (
202+
<p className="mt-3 text-sm text-slate-600">
203+
CDI does not retry a failed upload target. Recreate the disk to try
204+
again.
205+
</p>
206+
)}
207+
179208
{state.message && (
180209
<p className="mt-3 text-sm text-red-700">{state.message}</p>
181210
)}
@@ -188,13 +217,22 @@ export function DiskUploadPanel({
188217
at your local image and run:
189218
</p>
190219
<CopyableCommand command={command} />
191-
{!proxyURL && (
220+
{!proxyURL && cdiConfig.isSuccess && (
192221
<p className="text-xs text-slate-500">
193222
This cluster publishes no upload proxy URL, so the address above is a
194223
placeholder. Ask your platform administrator for the{" "}
195224
<span className="font-mono">cdi-uploadproxy</span> hostname.
196225
</p>
197226
)}
227+
{/* An errored CDIConfig read is not an answer either way. */}
228+
{!proxyURL && cdiConfig.isError && (
229+
<p className="text-xs text-slate-500">
230+
The upload proxy URL could not be read from{" "}
231+
<span className="font-mono">CDIConfig</span>, so the address above is
232+
a placeholder. Refresh, or ask your platform administrator for the{" "}
233+
<span className="font-mono">cdi-uploadproxy</span> hostname.
234+
</p>
235+
)}
198236
{/* An errored SSAR surfaces as allowed=false, which is not a denial. */}
199237
{!canUpload.isLoading && !canUpload.error && !canUpload.allowed && (
200238
<p className="rounded-md border border-amber-200 bg-amber-50 p-3 text-xs text-amber-800">

0 commit comments

Comments
 (0)