-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathimage-upload.tsx
More file actions
833 lines (748 loc) · 28.9 KB
/
image-upload.tsx
File metadata and controls
833 lines (748 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright Oxide Computer Company
*/
import { skipToken, useQuery } from '@tanstack/react-query'
import cn from 'classnames'
import { filesize } from 'filesize'
import pMap from 'p-map'
import pRetry from 'p-retry'
import { useRef, useState } from 'react'
import { useForm } from 'react-hook-form'
import { useNavigate } from 'react-router'
import {
api,
q,
queryClient,
useApiMutation,
type ApiError,
type BlockSize,
type Disk,
type Snapshot,
} from '@oxide/api'
import {
Error12Icon,
OpenLink12Icon,
Success12Icon,
Unauthorized12Icon,
} from '@oxide/design-system/icons/react'
import { DescriptionField } from '~/components/form/fields/DescriptionField'
import { FileField } from '~/components/form/fields/FileField'
import { NameField } from '~/components/form/fields/NameField'
import { RadioField } from '~/components/form/fields/RadioField'
import { TextField } from '~/components/form/fields/TextField'
import { SideModalForm } from '~/components/form/SideModalForm'
import { titleCrumb } from '~/hooks/use-crumbs'
import { useProjectSelector } from '~/hooks/use-params'
import { Message } from '~/ui/lib/Message'
import { Modal } from '~/ui/lib/Modal'
import { SideModalFormDocs } from '~/ui/lib/ModalLinks'
import { Progress } from '~/ui/lib/Progress'
import { Spinner } from '~/ui/lib/Spinner'
import { anySignal } from '~/util/abort'
import { readBlobAsBase64 } from '~/util/file'
import { invariant } from '~/util/invariant'
import { docLinks, links } from '~/util/links'
import { pb } from '~/util/path-builder'
import { isAllZeros } from '~/util/str'
import { GiB, KiB } from '~/util/units'
/** Format file size with two decimal points */
const fsize = (bytes: number) => filesize(bytes, { base: 2, pad: true })
type FormValues = {
imageName: string
imageDescription: string
os: string
version: string
blockSize: BlockSize
imageFile: File | null
}
const defaultValues: FormValues = {
imageName: '',
imageDescription: '',
os: '',
version: '',
blockSize: 512,
imageFile: null,
}
// subset of the mutation state we care about
type MutationState = {
isPending: boolean
isSuccess: boolean
isError: boolean
}
const initSyntheticState: MutationState = {
isPending: false,
isSuccess: false,
isError: false,
}
type StepProps = {
children?: React.ReactNode
state: MutationState
label: string
duration?: number
className?: string
}
function Step({ children, state, label, className }: StepProps) {
/* eslint-disable react/jsx-key */
const [status, icon] = state.isSuccess
? ['complete', <Success12Icon className="text-accent" />]
: state.isPending
? ['running', <Spinner />]
: state.isError
? ['error', <Error12Icon className="text-error" />]
: ['ready', <Unauthorized12Icon className="text-disabled" />]
/* eslint-enable react/jsx-key */
return (
// data-status used only for e2e testing
<div
className={cn('upload-step flex gap-2 px-4 py-3', className)}
data-testid={`upload-step: ${label}`}
data-status={status}
>
{/* padding on icon to align it with text since everything is aligned to top */}
<div className="pt-px">{icon}</div>
<div className={cn('w-full space-y-2', state.isError ? 'text-error' : 'text-raise')}>
<div>{label}</div>
{children}
</div>
</div>
)
}
const randInt = () => Math.floor(Math.random() * 100000000)
function getTmpDiskName(imageName: string) {
if (process.env.NODE_ENV === 'development') {
// this is only here for testing purposes. because we normally generate a
// random tmp disk name, we have to not do that if we want to pass special
// values to MSW to get it to do error things for us. If we pass special
// values as the image name, use the same value as the disk name and we'll
// do the right thing in
const specialNames = new Set([
'disk-create-500',
'import-start-500',
'import-stop-500',
'disk-finalize-500',
])
if (specialNames.has(imageName)) return imageName
}
return `tmp-for-image-${randInt()}`
}
// TODO: do we need to distinguish between abort due to manual cancel and abort
// due to error?
const ABORT_ERROR = new Error('Upload canceled')
/**
* Crucible currently enforces a limit of 512 KiB. See [crucible
* source](https://github.com/oxidecomputer/crucible/blob/c574ff1232/pantry/src/pantry.rs#L239-L253).
*/
const CHUNK_SIZE_BYTES = 512 * KiB
// States
//
// - Form
// - Clean or filled
// - Error
// - Checking that image name isn't taken (back to form if taken)
// - Upload in progress
// - Happy path
// - Create disk
// - Import start
// - Uploading
// - Import stop
// - Finalize disk + create snapshot
// - Create image from snapshot
// - Cleanup
// - Error
// - Show error, click here to try again
// - If we failed after upload complete, maybe try again from there?
// - Otherwise, restart everything
// - If image name got taken in the meantime, give chance to rename?
//
// Part of the problem is that I'm relying on RQ for the state of the upload
// steps, but there's slippage with what I actually want that to represent
// TODO: make sure cleanup, cancelEverything, and resetMainFlow are called in
// the right places
export const handle = titleCrumb('Upload image')
/**
* Upload an image. Opens a second modal to show upload progress.
*/
export default function ImageCreate() {
const navigate = useNavigate()
const { project } = useProjectSelector()
// The state in this component is very complex because we are doing a bunch of
// requests in order, all of which can fail, plus the whole thing can be
// aborted. We have the usual form state, plus an additional validation step
// where we check the API to make sure the name is not taken. Then, while we
// are submitting, we rely on the RQ mutations themselves, plus a synthetic
// mutation state representing the many calls of the bulk upload step.
const [formError, setFormError] = useState<ApiError | null>(null)
const [modalOpen, setModalOpen] = useState(false)
const [modalError, setModalError] = useState<string | null>(null)
// progress bar, 0-100
const [uploadProgress, setUploadProgress] = useState(0)
const backToImages = () => navigate(pb.projectImages({ project }))
// done as ref (global var) to avoid init in onSubmit and passing it around
const abortController = useRef<AbortController | null>(null)
// done with everything, ready to close the modal
const [allDone, setAllDone] = useState(false)
const createDisk = useApiMutation(api.diskCreate)
const startImport = useApiMutation(api.diskBulkWriteImportStart)
// gcTime: 0 prevents the mutation cache from holding onto all the chunks for
// 5 minutes. It can be a ton of memory. To be honest, I don't even understand
// why the mutation cache exists. It's not like the query cache, which dedupes
// identical queries made around the same time.
// https://tanstack.com/query/v5/docs/reference/MutationCache
const uploadChunk = useApiMutation(api.diskBulkWriteImport, { gcTime: 0 })
// synthetic state for upload step because it consists of multiple requests
const [syntheticUploadState, setSyntheticUploadState] =
useState<MutationState>(initSyntheticState)
const stopImport = useApiMutation(api.diskBulkWriteImportStop)
const finalizeDisk = useApiMutation(api.diskFinalizeImport)
const createImage = useApiMutation(api.imageCreate)
const deleteDisk = useApiMutation(api.diskDelete)
const deleteSnapshot = useApiMutation(api.snapshotDelete)
// TODO: Distinguish cleanup mutations being called after successful run vs.
// due to error. In the former case, they have their own steps to highlight as
// successful. In the latter, we do not want to highlight the steps.
const mainFlowMutations = [
createDisk,
startImport,
uploadChunk,
stopImport,
finalizeDisk,
createImage,
deleteDisk,
deleteSnapshot,
]
// separate so we can distinguish between cleanup due to error vs. cleanup after success
const stopImportCleanup = useApiMutation(api.diskBulkWriteImportStop)
const finalizeDiskCleanup = useApiMutation(api.diskFinalizeImport)
// in production these invalidations are unlikely to matter, but they help a
// lot in the tests when we check the disk list after canceling to make sure
// the temp resources got deleted
const deleteDiskCleanup = useApiMutation(api.diskDelete, {
onSuccess() {
queryClient.invalidateEndpoint('diskList')
},
})
const deleteSnapshotCleanup = useApiMutation(api.snapshotDelete, {
onSuccess() {
queryClient.invalidateEndpoint('snapshotList')
},
})
const cleanupMutations = [
stopImportCleanup,
finalizeDiskCleanup,
deleteDiskCleanup,
deleteSnapshotCleanup,
]
const allMutations = [...mainFlowMutations, syntheticUploadState, ...cleanupMutations]
// we don't want to be able to click submit while anything is running
const formLoading = allMutations.some((m) => m.isPending)
// the created snapshot and disk. presence used in cleanup to decide whether we need to
// attempt to delete them
const snapshot = useRef<Snapshot | null>(null)
const disk = useRef<Disk | null>(null)
function closeModal() {
if (allDone) {
backToImages()
return
}
// if we're still going, need to confirm cancellation. if we have an error,
// everything is already stopped
if (modalError || confirm('Are you sure? Closing the modal will cancel the upload.')) {
// Note we don't run cleanup() here -- cancelEverything triggers an
// abort, which gets caught by the try/catch in the onSubmit on the upload
// form, which does the cleanup. We used to call cleanup here and used
// error-prone state logic to avoid it running twice.
//
// Because we are working with a closed-over copy of allDone, there is
// a possibility that the upload finishes while the user is looking at
// the confirm modal, in which case cancelEverything simply won't do
// anything. The finally{} in onSubmit clears out the abortController so
// cancelEverything() is a noop.
cancelEverything()
resetMainFlow()
setModalOpen(false)
}
}
// Aborting works for steps other than file upload despite the
// signal not being used directly in the former because we call
// `abortController.throwIfAborted()` after each step. We could technically
// plumb through the signal to the requests themselves, but they complete so
// quickly it's probably not necessary.
function cancelEverything() {
abortController.current?.abort(ABORT_ERROR)
}
function resetMainFlow() {
setModalError(null)
setUploadProgress(0)
mainFlowMutations.forEach((m) => m.reset())
setSyntheticUploadState(initSyntheticState)
}
/** If a snapshot or disk was created, clean it up*/
async function cleanup() {
if (snapshot.current) {
await deleteSnapshotCleanup.mutateAsync({ path: { snapshot: snapshot.current.id } })
snapshot.current = null
}
if (disk.current) {
// we won't be able to delete the disk unless it's out of import mode
const path = { disk: disk.current.id }
const freshDisk = await queryClient.fetchQuery(q(api.diskView, { path }))
const diskState = freshDisk.state.state
if (diskState === 'importing_from_bulk_writes') {
await stopImportCleanup.mutateAsync({ path })
await finalizeDiskCleanup.mutateAsync({ path, body: {} })
}
if (diskState === 'import_ready') {
// TODO: if this fails, there's no way to delete the disk. tell user?
await finalizeDiskCleanup.mutateAsync({ path, body: {} })
}
await deleteDiskCleanup.mutateAsync({ path: { disk: disk.current.id } })
disk.current = null
}
}
async function onSubmit({
imageName,
imageDescription,
imageFile,
blockSize,
os,
version,
}: FormValues) {
invariant(imageFile, 'imageFile must exist') // shouldn't be possible to fail bc file is a required field
// this is done up here instead of next to the upload step because after
// upload is canceled, a few outstanding bulk writes will complete, setting
// uploadProgress to non-zero values. if we do this reset down there instead
// of up here, cancel and retry will bring up a modal briefly showing the
// previous run's progress, and it resets only when bulk upload starts
resetMainFlow()
setModalOpen(true)
// Create a disk in state import-ready
const diskName = getTmpDiskName(imageName)
disk.current = await createDisk.mutateAsync({
query: { project },
body: {
name: diskName,
description: `temporary disk for importing image ${imageName}`,
diskBackend: {
type: 'distributed',
diskSource: { type: 'importing_blocks', blockSize },
},
size: Math.ceil(imageFile.size / GiB) * GiB,
},
})
// do these between each step to catch cancellations
abortController.current?.signal.throwIfAborted()
// set disk to state importing-via-bulk-write
const path = { disk: disk.current.id }
await startImport.mutateAsync({ path })
abortController.current?.signal.throwIfAborted()
// Post file to the API in chunks of size `maxChunkSize`. Browsers cap
// concurrent fetches at 6 per host. If we ran without a concurrency limit,
// we'd read way more chunks into memory than we're ready to POST, and we'd
// be sitting around waiting for the browser to let the fetches through.
// That sounds bad. So we use pMap to process at most 6 chunks at a time.
setSyntheticUploadState({ isPending: true, isSuccess: false, isError: false })
const nChunks = Math.ceil(imageFile.size / CHUNK_SIZE_BYTES)
// TODO: try to warn user if they try to close the tab while this is going
let chunksProcessed = 0
const postChunk = async (i: number) => {
const offset = i * CHUNK_SIZE_BYTES
const end = Math.min(offset + CHUNK_SIZE_BYTES, imageFile.size)
const base64EncodedData = await readBlobAsBase64(imageFile.slice(offset, end))
// Disk space is all zeros by default, so we can skip any chunks that are
// all zeros. It turns out this happens a lot.
if (!isAllZeros(base64EncodedData)) {
await uploadChunk
.mutateAsync({
path,
body: { offset, base64EncodedData },
// use both the abort signal for the whole upload and a per-request timeout
__signal: anySignal([
AbortSignal.timeout(30000),
abortController.current?.signal,
]),
})
.catch(() => {
// this needs to throw a regular Error or pRetry gets mad
throw Error(`Chunk ${i} (offset ${offset}) failed`)
})
}
chunksProcessed++
setUploadProgress(Math.round((100 * chunksProcessed) / nChunks))
}
// avoid pointless array of size 4000 for a 2gb image
function* genChunks() {
for (let i = 0; i < nChunks; i++) yield i
}
// will throw if aborted or if requests error out
try {
await pMap(
genChunks(),
(i) => pRetry(() => postChunk(i), { retries: 2 }),
// browser can only do 6 fetches at once, so we only read 6 chunks at once
{ concurrency: 6, signal: abortController.current?.signal }
)
} catch (e) {
if (e !== ABORT_ERROR) {
setSyntheticUploadState({ isPending: false, isSuccess: false, isError: true })
}
throw e // rethrow to get the usual the error handling in the wrapper function
}
setSyntheticUploadState({ isPending: false, isSuccess: true, isError: false })
await stopImport.mutateAsync({ path })
abortController.current?.signal.throwIfAborted()
const snapshotName = `tmp-snapshot-${randInt()}`
await finalizeDisk.mutateAsync({ path, body: { snapshotName } })
abortController.current?.signal.throwIfAborted()
// diskFinalizeImport does not return the snapshot, but create image
// requires an ID
snapshot.current = await queryClient.fetchQuery(
q(api.snapshotView, {
path: { snapshot: snapshotName },
query: { project },
})
)
abortController.current?.signal.throwIfAborted()
// TODO: we checked at the beginning that the image name was free, but it
// could be taken during upload. If this fails with object already exists,
// don't delete the snapshot (could still delete the disk). Instead, link
// user to snapshot detail and tell them to go there and create the image
// from it.
await createImage.mutateAsync({
query: { project },
body: {
name: imageName,
description: imageDescription,
os,
version,
source: { type: 'snapshot', id: snapshot.current.id },
},
})
abortController.current?.signal.throwIfAborted()
queryClient.invalidateEndpoint('imageList')
// now delete the snapshot and the disk. don't use cleanup() because that
// uses different mutations
await deleteSnapshot.mutateAsync({ path: { snapshot: snapshot.current.id } })
await deleteDisk.mutateAsync({ path: { disk: disk.current.id } })
setAllDone(true)
}
// Surface file validation as soon as the user picks a file. Block-size
// changes are still validated on submit.
const form = useForm({ defaultValues, mode: 'onChange' })
const file = form.watch('imageFile')
const blockSize = form.watch('blockSize')
const { data: imageValidation } = useQuery({
queryKey: ['validateImage', ...(file ? [file.name, file.size, file.lastModified] : [])],
queryFn: file ? () => validateImage(file) : skipToken,
})
return (
<SideModalForm
form={form}
formType="create"
resourceName="image"
title="Upload image"
onDismiss={backToImages}
onSubmit={async (values) => {
setFormError(null)
// check that image name isn't taken before starting the whole thing
const image = await queryClient
.fetchQuery(
q(
api.imageView,
{ path: { image: values.imageName }, query: { project } },
{
errorsExpected: {
explanation: 'the image name may not exist yet.',
statusCode: 404,
},
}
)
)
.catch((e) => {
// eat a 404 since that's what we want. anything else should still blow up
if (e.statusCode === 404) return null
throw e
})
if (image) {
// TODO: set this error on the field instead of the whole form
// TODO: make setError available here somehow :(
setFormError({
errorCode: 'ObjectAlreadyExists',
message: 'Image name already exists',
})
return
}
// every submit needs its own AbortController because they can't be
// reset
abortController.current = new AbortController()
try {
await onSubmit(values)
} catch (e) {
if (e !== ABORT_ERROR) {
console.error(e)
setModalError('Something went wrong. Please try again.')
// abort anything in flight in case
cancelEverything()
}
// user canceled
await cleanup()
// TODO: if we get here, show failure state in the upload modal
} finally {
// Clear the abort controller. This is aimed at the case where the
// user clicks cancel and then stares at the confirm modal without
// clicking for so long that the upload manages to finish, which means
// there's no longer anything to cancel. If abortController is gone,
// cancelEverything is a noop.
abortController.current = null
}
}}
loading={formLoading}
submitError={formError}
submitLabel={allDone ? 'Done' : 'Upload image'}
>
<NameField name="imageName" label="Name" control={form.control} />
<DescriptionField
name="imageDescription"
label="Description"
control={form.control}
/>
{/* TODO: are OS and Version supposed to be non-empty? I doubt the API cares,
* but it will be pretty for end users if they're empty
*/}
<TextField name="os" label="OS" control={form.control} required />
<TextField name="version" control={form.control} required />
<div className="flex w-full flex-col flex-wrap space-y-4">
<RadioField
name="blockSize"
label="Block size"
units="Bytes"
control={form.control}
parseValue={(val) => parseInt(val, 10) as BlockSize}
items={[
{ label: '512', value: 512 },
{ label: '2048', value: 2048 },
{ label: '4096', value: 4096 },
]}
/>
{imageValidation && <BlockSizeNotice {...imageValidation} blockSize={blockSize} />}
</div>
<div className="flex w-full flex-col flex-wrap space-y-4">
<FileField
id="image-file-input"
name="imageFile"
label="Image file"
required
control={form.control}
// Crucible rejects bulk-write imports whose total size isn't a
// multiple of the block size, so catch it before the long upload.
validate={(f, { blockSize }) => {
if (f && f.size % blockSize !== 0) {
return `File size must be a multiple of the block size (${blockSize} bytes)`
}
}}
/>
{imageValidation && <BootableNotice {...imageValidation} />}
</div>
{file && modalOpen && (
<Modal isOpen onDismiss={closeModal} title="Image upload progress">
<Modal.Body className="p-0!">
<Modal.Section className="p-0!">
<div className="*:border-b-secondary *:border-b last:*:border-b-0">
{modalError && (
<Message
variant="error"
title="Error"
content={modalError}
className="rounded-none! shadow-none!"
/>
)}
<Step state={createDisk} label="Create temporary disk" />
<Step state={startImport} label="Put disk in import mode" />
<Step state={syntheticUploadState} label="Upload image file">
<div className="bg-default border-default rounded-lg border">
<div className="border-b-secondary flex justify-between border-b p-3 pb-2">
<div className="text-sans-md text-raise">{file.name}</div>
{/* cancel and/or pause buttons could go here */}
</div>
<div className="p-3 pt-2">
<div className="text-mono-sm flex justify-between">
<div className="text-default normal-case!">
{fsize((uploadProgress / 100) * file.size)}{' '}
<span className="text-quaternary">/</span> {fsize(file.size)}
</div>
<div className="text-accent">{uploadProgress}%</div>
</div>
<Progress
className="mt-1.5"
aria-label="Upload progress"
value={uploadProgress}
/>
</div>
</div>
</Step>
<Step state={stopImport} label="Get disk out of import mode" />
<Step state={finalizeDisk} label="Finalize disk and create snapshot" />
<Step state={createImage} label="Create image" duration={15} />
<Step
state={{
isPending: deleteDisk.isPending || deleteSnapshot.isPending,
isSuccess: deleteDisk.isSuccess && deleteSnapshot.isSuccess,
isError: deleteDisk.isError || deleteSnapshot.isError,
}}
label="Delete disk and snapshot"
/>
<Step
state={{
isPending: false,
isSuccess: allDone,
isError: false,
}}
label="Image uploaded successfully"
className={
allDone
? 'bg-accent *:text-accent transition-colors'
: 'transition-colors'
}
/>
</div>
</Modal.Section>
</Modal.Body>
<Modal.Footer
onDismiss={closeModal}
onAction={backToImages}
actionText="Done"
cancelText={modalError || allDone ? 'Back' : 'Cancel'}
disabled={!allDone}
/>
</Modal>
)}
<SideModalFormDocs docs={[docLinks.images]} />
</SideModalForm>
)
}
function BlockSizeNotice({
blockSize,
efiPartOffset,
isBootableCd,
}: {
blockSize: number
efiPartOffset: number
isBootableCd: boolean
}) {
const isEfi = efiPartOffset !== -1
// If the image doesn't look bootable, return null (`BootableNotice` does the work).
if (!isEfi && !isBootableCd) return null
// If we detect `EFI BOOT` and the block size is set correctly return null.
// (This includes hybrid GPT+ISO.)
if (isEfi && blockSize === efiPartOffset) return null
// If we detect only `CD001` and the block size is set correctly return null.
if (!isEfi && isBootableCd && blockSize === 2048) return null
// Block size is set incorrectly. If we detect `EFI BOOT`, always show that warning.
const content = isEfi
? `Detected “EFI PART” marker at offset ${efiPartOffset}, but block size is set to ${blockSize}.`
: 'Bootable CDs typically use a block size of 2048.'
return (
<Message variant="info" title="Block size might be set incorrectly" content={content} />
)
}
function BootableNotice({
efiPartOffset,
isBootableCd,
isCompressed,
}: {
efiPartOffset: number
isBootableCd: boolean
isCompressed: boolean
}) {
// this message should only appear if the image doesn't have a header
// marker we are looking for and does not appear to be compressed
const efiPartOrBootable = efiPartOffset !== -1 || isBootableCd
if (efiPartOrBootable && !isCompressed) return null
const content = (
<div className="flex flex-col space-y-2">
<ul className="ml-4 list-disc">
{!efiPartOrBootable && (
<li>
<div>Bootable markers not found at any block size.</div>
<div>
Expected either “EFI PART” marker at offsets 512 / 2048 / 4096 or “CD001” at
offset 0x8001 (for a bootable CD).
</div>
</li>
)}
{isCompressed && (
<li>
<div>This might be a compressed image.</div>
<div>
Only raw, uncompressed images are supported. Files such as qcow2, vmdk,
img.gz, iso.7z may not work.
</div>
</li>
)}
</ul>
<div>
Learn more about{' '}
<a
target="_blank"
rel="noreferrer"
href={links.preparingImagesDocs}
className="inline-flex items-center underline"
>
preparing images for import
<OpenLink12Icon className="ml-1" />
</a>
</div>
</div>
)
return (
<Message
variant="info"
title="This image might not be bootable"
className="*:space-y-2"
content={content}
/>
)
}
async function readAtOffset(file: File, offset: number, length: number) {
const reader = new FileReader()
const promise = new Promise<string | undefined>((resolve, reject) => {
reader.onloadend = (e) => {
if (
e.target?.readyState === FileReader.DONE &&
// should always be true because we're using readAsArrayBuffer
e.target.result instanceof ArrayBuffer
) {
resolve(String.fromCharCode(...new Uint8Array(e.target.result)))
return
}
resolve(undefined)
}
reader.onerror = (error) => {
const msg = `Error reading file at offset ${offset}:`
console.error(msg, error)
reject(new Error(msg))
}
})
reader.readAsArrayBuffer(file.slice(offset, offset + length))
return promise
}
async function getEfiPartOffset(file: File) {
const offsets = [512, 2048, 4096]
for (const offset of offsets) {
const isMatch = (await readAtOffset(file, offset, 8)) === 'EFI PART'
if (isMatch) return offset
}
return -1
}
const compressedExts = ['.gz', '.7z', '.qcow2', '.vmdk']
const validateImage = async (file: File) => {
const lowerFileName = file.name.toLowerCase()
return {
efiPartOffset: await getEfiPartOffset(file),
isBootableCd: (await readAtOffset(file, 0x8001, 5)) === 'CD001',
isCompressed: compressedExts.some((ext) => lowerFileName.endsWith(ext)),
}
}