-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathinstance-create.tsx
More file actions
1147 lines (1068 loc) · 39.9 KB
/
instance-create.tsx
File metadata and controls
1147 lines (1068 loc) · 39.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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 { useEffect, useMemo, useRef, useState } from 'react'
import { useController, useForm, useWatch, type Control } from 'react-hook-form'
import { Link, useNavigate, type LoaderFunctionArgs } from 'react-router'
import * as R from 'remeda'
import { match, P } from 'ts-pattern'
import type { SetRequired } from 'type-fest'
import {
api,
diskCan,
genName,
INSTANCE_MAX_CPU,
INSTANCE_MAX_RAM_GiB,
isUnicastPool,
MAX_DISK_SIZE_GiB,
poolHasIpVersion,
q,
queryClient,
useApiMutation,
usePrefetchedQuery,
type ExternalIpCreate,
type FloatingIp,
type Image,
type InstanceCreate,
type InstanceDiskAttachment,
type InstanceNetworkInterfaceAttachment,
type IpVersion,
type NameOrId,
type UnicastIpPool,
} from '@oxide/api'
import {
Images16Icon,
Instances16Icon,
Instances24Icon,
IpGlobal16Icon,
Storage16Icon,
} from '@oxide/design-system/icons/react'
import { DocsPopover } from '~/components/DocsPopover'
import { CheckboxField } from '~/components/form/fields/CheckboxField'
import { ComboboxField } from '~/components/form/fields/ComboboxField'
import { DescriptionField } from '~/components/form/fields/DescriptionField'
import { DiskSizeField } from '~/components/form/fields/DiskSizeField'
import {
DisksTableField,
type DiskTableItem,
} from '~/components/form/fields/DisksTableField'
import { FileField } from '~/components/form/fields/FileField'
import { BootDiskImageSelectField as ImageSelectField } from '~/components/form/fields/ImageSelectField'
import { ListboxField } from '~/components/form/fields/ListboxField'
import { NameField } from '~/components/form/fields/NameField'
import { NetworkInterfaceField } from '~/components/form/fields/NetworkInterfaceField'
import { NumberField } from '~/components/form/fields/NumberField'
import { RadioFieldDyn } from '~/components/form/fields/RadioField'
import { SshKeysField } from '~/components/form/fields/SshKeysField'
import { Form } from '~/components/form/Form'
import { FullPageForm } from '~/components/form/FullPageForm'
import { HL } from '~/components/HL'
import { toIpPoolItem } from '~/components/IpPoolListboxItem'
import { getProjectSelector, useProjectSelector } from '~/hooks/use-params'
import { addToast } from '~/stores/toast'
import { Button } from '~/ui/lib/Button'
import { toComboboxItems } from '~/ui/lib/Combobox'
import { FormDivider } from '~/ui/lib/Divider'
import { EmptyMessage } from '~/ui/lib/EmptyMessage'
import { Listbox } from '~/ui/lib/Listbox'
import { Message } from '~/ui/lib/Message'
import { MiniTable } from '~/ui/lib/MiniTable'
import { Modal } from '~/ui/lib/Modal'
import { PageHeader, PageTitle } from '~/ui/lib/PageHeader'
import { RadioCard } from '~/ui/lib/Radio'
import { Slash } from '~/ui/lib/Slash'
import { Tabs } from '~/ui/lib/Tabs'
import { HintLink, TextInputHint } from '~/ui/lib/TextInput'
import { TipIcon } from '~/ui/lib/TipIcon'
import { Tooltip } from '~/ui/lib/Tooltip'
import { Wrap } from '~/ui/util/wrap'
import { ALL_ISH } from '~/util/consts'
import { cpuPlatformItems, type FormCpuPlatform } from '~/util/cpu-platform'
import { readBlobAsBase64 } from '~/util/file'
import { ipHasVersion } from '~/util/ip'
import { docLinks, links } from '~/util/links'
import { diskSizeNearest10 } from '~/util/math'
import { pb } from '~/util/path-builder'
import { GiB } from '~/util/units'
// for referential stability
const EMPTY_NAME_OR_ID_LIST: NameOrId[] = []
const getBootDiskAttachment = (
values: InstanceCreateInput,
images: Array<Image>
): InstanceDiskAttachment => {
if (values.bootDiskSourceType === 'disk') {
return { type: 'attach', name: values.diskSource }
}
const source =
values.bootDiskSourceType === 'siloImage'
? values.siloImageSource
: values.projectImageSource
const sourceName = images.find((image) => image.id === source)?.name
return {
type: 'create',
name: values.bootDiskName || genName(values.name, sourceName || source),
description: `Created as a boot disk for ${values.name}`,
size: values.bootDiskSize * GiB,
diskBackend: {
type: 'distributed',
diskSource: {
type: 'image',
imageId: source,
readOnly: false,
},
},
}
}
type BootDiskSourceType = 'siloImage' | 'projectImage' | 'disk'
export type InstanceCreateInput = Assign<
// API accepts undefined but it's easier if we don't
SetRequired<Omit<InstanceCreate, 'externalIps'>, 'networkInterfaces'>,
{
presetId: (typeof PRESETS)[number]['id']
otherDisks: DiskTableItem[]
bootDiskName: string
bootDiskSize: number
// bootDiskSourceType is a switch picking between the three sources listed below it
bootDiskSourceType: BootDiskSourceType
siloImageSource: string
projectImageSource: string
diskSource: string
bootDiskReadOnly: boolean
userData: File | null
// ssh keys are always specified. we do not need the undefined case
sshPublicKeys: NonNullable<InstanceCreate['sshPublicKeys']>
// Ephemeral IP fields (dual stack support)
ephemeralIpv4: boolean
ephemeralIpv4Pool: string
ephemeralIpv6: boolean
ephemeralIpv6Pool: string
// Selected floating IPs to attach on create.
floatingIps: NameOrId[]
// CPU platform preference
cpuPlatform: FormCpuPlatform
}
>
// Stable array refs to avoid useEffect churn when
// getCompatibleVersionsFromNicType is used in dependency arrays
const IP_VERSIONS_V4: IpVersion[] = ['v4']
const IP_VERSIONS_V6: IpVersion[] = ['v6']
const IP_VERSIONS_DUAL: IpVersion[] = ['v4', 'v6']
const IP_VERSIONS_NONE: IpVersion[] = []
/**
* Determine compatible IP versions based on network interface configuration.
* External IPs route through the primary interface, so only its IP stack matters.
*/
function getCompatibleVersionsFromNicType(
networkInterfaces: InstanceNetworkInterfaceAttachment
): IpVersion[] {
return match(networkInterfaces)
.returnType<IpVersion[]>()
.with({ type: 'default_ipv4' }, () => IP_VERSIONS_V4)
.with({ type: 'default_ipv6' }, () => IP_VERSIONS_V6)
.with({ type: 'default_dual_stack' }, () => IP_VERSIONS_DUAL)
.with({ type: 'none' }, () => IP_VERSIONS_NONE)
.with({ type: 'create', params: [] }, () => IP_VERSIONS_NONE)
.with({ type: 'create', params: P.select() }, (params) =>
// Derive from the first NIC's ipConfig (first NIC becomes primary).
// ipConfig not provided = defaults to dual-stack
match(params[0].ipConfig?.type)
.returnType<IpVersion[]>()
.with('v4', () => IP_VERSIONS_V4)
.with('v6', () => IP_VERSIONS_V6)
.with('dual_stack', () => IP_VERSIONS_DUAL)
.with(P.nullish, () => IP_VERSIONS_DUAL)
.exhaustive()
)
.exhaustive()
}
const baseDefaultValues: InstanceCreateInput = {
name: '',
description: '',
/**
* This value controls the selector which drives memory and ncpus. It's not actually
* submitted to the API.
*/
presetId: 'general-xs',
memory: 8,
ncpus: 2,
hostname: '',
bootDiskName: '',
bootDiskSize: 10,
bootDiskSourceType: 'siloImage',
siloImageSource: '',
projectImageSource: '',
diskSource: '',
bootDiskReadOnly: false,
otherDisks: [],
networkInterfaces: { type: 'default_ipv4' },
sshPublicKeys: [],
start: true,
userData: null,
ephemeralIpv4: false,
ephemeralIpv4Pool: '',
ephemeralIpv6: false,
ephemeralIpv6Pool: '',
floatingIps: [],
cpuPlatform: 'none',
}
export async function clientLoader({ params }: LoaderFunctionArgs) {
const { project } = getProjectSelector(params)
await Promise.all([
// fetch both project and silo images
queryClient.prefetchQuery(q(api.imageList, { query: { project } })),
queryClient.prefetchQuery(q(api.imageList, {})),
queryClient.prefetchQuery(q(api.diskList, { query: { project, limit: ALL_ISH } })),
queryClient.prefetchQuery(q(api.currentUserSshKeyList, {})),
queryClient.prefetchQuery(q(api.ipPoolList, { query: { limit: ALL_ISH } })),
queryClient.prefetchQuery(
q(api.floatingIpList, { query: { project, limit: ALL_ISH } })
),
queryClient.prefetchQuery(q(api.vpcList, { query: { project, limit: ALL_ISH } })),
])
return null
}
export const handle = { crumb: 'New instance' }
const EPHEMERAL_IP_FIELDS = {
v4: {
checkboxName: 'ephemeralIpv4',
poolFieldName: 'ephemeralIpv4Pool',
displayVersion: 'IPv4',
},
v6: {
checkboxName: 'ephemeralIpv6',
poolFieldName: 'ephemeralIpv6Pool',
displayVersion: 'IPv6',
},
} as const
function EphemeralIpCheckbox({
control,
ipVersion,
compatibleVersions,
unicastPools,
isSubmitting,
}: {
control: Control<InstanceCreateInput>
ipVersion: IpVersion
compatibleVersions: IpVersion[]
unicastPools: UnicastIpPool[]
isSubmitting: boolean
}) {
const { checkboxName, poolFieldName, displayVersion } = EPHEMERAL_IP_FIELDS[ipVersion]
const ephemeralIpField = useController({ control, name: checkboxName })
const ephemeralIpPoolField = useController({ control, name: poolFieldName })
const checked = ephemeralIpField.field.value
const pools = useMemo(
() => unicastPools.filter((pool) => pool.ipVersion === ipVersion),
[unicastPools, ipVersion]
)
const isCompatible = compatibleVersions.includes(ipVersion)
const hasPools = pools.length > 0
const canAttach = isCompatible && hasPools
let disabledReason: React.ReactNode
if (!canAttach) {
disabledReason = isCompatible ? (
<>
No IP{ipVersion} pools available
<br />
for this instance’s network interfaces
</>
) : (
<>
Add an IP{ipVersion} network interface
<br />
to attach an ephemeral IP{ipVersion} address
</>
)
}
// Track previous canAttach to detect false→true transitions (NIC type
// change re-enabling this IP version). A ref because we need to compare
// across renders without triggering re-renders when we update it.
const prevCanAttachRef = useRef<boolean | undefined>(undefined)
useEffect(() => {
if (checked && !canAttach) {
ephemeralIpField.field.onChange(false)
ephemeralIpPoolField.field.onChange('')
} else if (canAttach && prevCanAttachRef.current === false && !checked) {
const defaultPool = pools.find((p) => p.isDefault)
if (defaultPool) {
ephemeralIpField.field.onChange(true)
ephemeralIpPoolField.field.onChange(defaultPool.name)
}
}
prevCanAttachRef.current = canAttach
}, [canAttach, checked, pools, ephemeralIpField, ephemeralIpPoolField])
return (
<div className="max-w-lg space-y-2">
<Wrap when={!!disabledReason} with={<Tooltip content={disabledReason} />}>
{/* span makes tooltip show on label hover, not just the checkbox */}
<span>
<CheckboxField
control={control}
name={checkboxName}
disabled={!canAttach || isSubmitting}
>
Allocate {displayVersion} address
{checked && ' from pool:'}
</CheckboxField>
</span>
</Wrap>
<div className={`my-2 ml-6 ${checked ? '' : 'hidden'}`}>
<ListboxField
name={poolFieldName}
control={control}
items={pools.map(toIpPoolItem)}
disabled={isSubmitting}
required={checked}
hideOptionalTag
label={`${displayVersion} pool`}
hideLabel
placeholder="Select a pool"
noItemsPlaceholder="No pools available"
/>
</div>
</div>
)
}
export default function CreateInstanceForm() {
const [isSubmitting, setIsSubmitting] = useState(false)
const { project } = useProjectSelector()
const navigate = useNavigate()
const createInstance = useApiMutation(api.instanceCreate, {
onSuccess(instance) {
// refetch list of instances
queryClient.invalidateEndpoint('instanceList')
// avoid the instance fetch when the instance page loads since we have the data
const instanceView = q(api.instanceView, {
path: { instance: instance.name },
query: { project },
})
queryClient.setQueryData(instanceView.queryKey, instance)
// prettier-ignore
addToast(<>Instance <HL>{instance.name}</HL> created</>)
navigate(pb.instance({ project, instance: instance.name }))
},
})
const siloImages = usePrefetchedQuery(q(api.imageList, {})).data.items
const projectImages = usePrefetchedQuery(q(api.imageList, { query: { project } })).data
.items
const allImages = [...siloImages, ...projectImages]
const defaultImage = allImages[0]
const allDisks = usePrefetchedQuery(
q(api.diskList, { query: { project, limit: ALL_ISH } })
).data.items
const disks = useMemo(() => toComboboxItems(allDisks.filter(diskCan.attach)), [allDisks])
const { data: sshKeys } = usePrefetchedQuery(q(api.currentUserSshKeyList, {}))
const allKeys = useMemo(() => sshKeys.items.map((key) => key.id), [sshKeys])
// ipPoolList fetches the pools linked to the current silo
const { data: siloPools } = usePrefetchedQuery(
q(api.ipPoolList, { query: { limit: ALL_ISH } })
)
// Only unicast pools can be used for ephemeral IPs. Sort once here so
// downstream filters (default pool pick, compatible pool list) preserve
// the order without needing to re-sort.
const unicastPools = useMemo(
() =>
R.sortBy(
(siloPools?.items || []).filter(isUnicastPool),
(p) => !p.isDefault, // defaults first
(p) => p.ipVersion, // v4 first
(p) => p.name
),
[siloPools]
)
// Check if VPCs exist to determine default network interface type
const { data: vpcs } = usePrefetchedQuery(
q(api.vpcList, { query: { project, limit: ALL_ISH } })
)
const hasVpcs = vpcs.items.length > 0
// Determine default network interface type:
// - If VPCs exist: default to dual-stack (API default, works with both IPv4 and IPv6 subnets)
// - If no VPCs exist: default to 'none' (user must create VPC first or use custom NICs)
// Note: Decoupled from external IP pool configuration, as NIC IP stack and external IPs are separate concerns
const defaultNetworkInterfaceType: InstanceNetworkInterfaceAttachment['type'] = hasVpcs
? 'default_dual_stack'
: 'none'
const defaultSource =
siloImages.length > 0 ? 'siloImage' : projectImages.length > 0 ? 'projectImage' : 'disk'
const defaultCompatibleVersions = getCompatibleVersionsFromNicType({
type: defaultNetworkInterfaceType,
})
const compatibleDefaultPools = unicastPools
.filter(poolHasIpVersion(defaultCompatibleVersions))
.filter((p) => p.isDefault)
// Get default pools for initial values
const defaultV4Pool = compatibleDefaultPools.find((p) => p.ipVersion === 'v4')
const defaultV6Pool = compatibleDefaultPools.find((p) => p.ipVersion === 'v6')
const defaultValues: InstanceCreateInput = {
...baseDefaultValues,
networkInterfaces: { type: defaultNetworkInterfaceType },
bootDiskSourceType: defaultSource,
sshPublicKeys: allKeys,
bootDiskSize: diskSizeNearest10(defaultImage?.size / GiB),
ephemeralIpv4: !!defaultV4Pool && defaultCompatibleVersions.includes('v4'),
ephemeralIpv4Pool: defaultV4Pool?.name || '',
ephemeralIpv6: !!defaultV6Pool && defaultCompatibleVersions.includes('v6'),
ephemeralIpv6Pool: defaultV6Pool?.name || '',
floatingIps: [],
}
const form = useForm({ defaultValues })
const { control, setValue } = form
const bootDiskSourceType = useWatch({ control: control, name: 'bootDiskSourceType' })
const siloImageSource = useWatch({ control: control, name: 'siloImageSource' })
const projectImageSource = useWatch({ control: control, name: 'projectImageSource' })
const diskSource = useWatch({ control: control, name: 'diskSource' })
const bootDiskSource =
bootDiskSourceType === 'siloImage'
? siloImageSource
: bootDiskSourceType === 'projectImage'
? projectImageSource
: diskSource
const bootDiskSize = useWatch({ control: control, name: 'bootDiskSize' })
const image = allImages.find((i) => i.id === bootDiskSource)
const imageSizeGiB = image?.size ? Math.ceil(image.size / GiB) : undefined
useEffect(() => {
if (createInstance.error) {
setIsSubmitting(false)
}
}, [createInstance.error])
const otherDisks = useWatch({ control, name: 'otherDisks' })
const unavailableDiskNames = [
...allDisks, // existing disks from the API
...otherDisks.filter((disk) => disk.action === 'create'), // disks being created here
].map((d) => d.name)
// additional form elements for projectImage and siloImage tabs
const bootDiskSizeAndName = (
<>
<div key="divider1" className="my-6! content-['a']" />
<DiskSizeField
key="diskSizeField"
label="Disk size"
name="bootDiskSize"
control={control}
min={imageSizeGiB || 1}
// Max size applies: this disk can only be distributed
max={MAX_DISK_SIZE_GiB}
validate={(diskSizeGiB: number) => {
if (imageSizeGiB && diskSizeGiB < imageSizeGiB) {
return `Must be as large as selected image (min. ${imageSizeGiB} GiB)`
}
}}
disabled={isSubmitting}
/>
<div key="divider2" className="my-6! content-['a']" />
<NameField
key="bootDiskName"
name="bootDiskName"
label="Disk name"
// TODO: would be cool to generate the name already and use it as a placeholder
description="A name will be generated if left blank"
required={false}
control={control}
disabled={isSubmitting}
validate={(name) => {
// don't allow the user to use an existing disk name for the boot disk's name
if (unavailableDiskNames.includes(name)) {
return 'Name is already in use'
}
}}
/>
{/* Read-only disk creation disabled pending propolis fix
https://github.com/oxidecomputer/console/issues/3071
<div key="divider3" className="my-6! content-['a']" />
<CheckboxField
key="bootDiskReadOnly"
name="bootDiskReadOnly"
control={control}
disabled={isSubmitting}
>
Make disk read-only
</CheckboxField>
*/}
</>
)
const bootDiskName = useWatch({ control, name: 'bootDiskName' })
return (
<>
<PageHeader>
<PageTitle icon={<Instances24Icon />}>Create instance</PageTitle>
<DocsPopover
heading="instances"
icon={<Instances16Icon />}
summary="Instances are virtual machines that run on the Oxide platform."
links={[docLinks.instances, docLinks.instanceActions, docLinks.quickStart]}
/>
</PageHeader>
<FullPageForm
submitDisabled={allImages.length ? undefined : 'Image required'}
id="create-instance-form"
form={form}
onSubmit={async (values) => {
setIsSubmitting(true)
// we should never have a presetId that's not in the list
const preset = PRESETS.find((option) => option.id === values.presetId)!
const instance =
values.presetId === 'custom'
? { memory: values.memory, ncpus: values.ncpus }
: { memory: preset.memory, ncpus: preset.ncpus }
const bootDisk = getBootDiskAttachment(values, allImages)
const externalIps: ExternalIpCreate[] = []
if (values.ephemeralIpv4) {
externalIps.push({
type: 'ephemeral',
poolSelector: { type: 'explicit', pool: values.ephemeralIpv4Pool },
})
}
if (values.ephemeralIpv6) {
externalIps.push({
type: 'ephemeral',
poolSelector: { type: 'explicit', pool: values.ephemeralIpv6Pool },
})
}
for (const floatingIp of values.floatingIps) {
externalIps.push({ type: 'floating', floatingIp })
}
const userData = values.userData
? await readBlobAsBase64(values.userData)
: undefined
await createInstance.mutateAsync({
query: { project },
body: {
name: values.name,
hostname: values.name,
description: values.description,
memory: instance.memory * GiB,
ncpus: instance.ncpus,
cpuPlatform: values.cpuPlatform === 'none' ? null : values.cpuPlatform,
disks: values.otherDisks.map(
(d): InstanceDiskAttachment =>
d.action === 'attach'
? { type: 'attach', name: d.name }
: {
type: 'create',
name: d.name,
description: d.description,
size: d.size,
diskBackend: d.diskBackend,
}
),
bootDisk,
externalIps,
start: values.start,
networkInterfaces: values.networkInterfaces,
sshPublicKeys: values.sshPublicKeys,
userData,
},
})
}}
loading={createInstance.isPending}
submitError={createInstance.error}
>
<NameField name="name" control={control} disabled={isSubmitting} />
<DescriptionField name="description" control={control} disabled={isSubmitting} />
<CheckboxField
id="start-instance"
name="start"
control={control}
disabled={isSubmitting}
>
Start Instance
</CheckboxField>
<FormDivider />
<Form.Heading id="hardware">Hardware</Form.Heading>
<TextInputHint id="hw-gp-help-text" className="text-sans-md mb-12 max-w-xl">
Pick a pre-configured machine type that offers balanced vCPU and memory for most
workloads or create a custom machine.
</TextInputHint>
<Tabs.Root
id="choose-cpu-ram"
className="full-width"
defaultValue="general"
onValueChange={(val) => {
// Having an option selected from a non-current tab is confusing,
// especially in combination with the custom inputs. So we auto
// select the first option from the current tab
const firstOption = PRESETS.find((preset) => preset.category === val)
if (firstOption) {
setValue('presetId', firstOption.id)
}
}}
>
<Tabs.List aria-labelledby="hardware">
<Tabs.Trigger value="general" disabled={isSubmitting}>
General Purpose
</Tabs.Trigger>
<Tabs.Trigger value="highCPU" disabled={isSubmitting}>
High CPU
</Tabs.Trigger>
<Tabs.Trigger value="highMemory" disabled={isSubmitting}>
High Memory
</Tabs.Trigger>
<Tabs.Trigger value="custom" disabled={isSubmitting}>
Custom
</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="general">
<RadioFieldDyn name="presetId" control={control} disabled={isSubmitting}>
{renderLargeRadioCards('general')}
</RadioFieldDyn>
</Tabs.Content>
<Tabs.Content value="highCPU">
<RadioFieldDyn name="presetId" control={control} disabled={isSubmitting}>
{renderLargeRadioCards('highCPU')}
</RadioFieldDyn>
</Tabs.Content>
<Tabs.Content value="highMemory">
<RadioFieldDyn name="presetId" control={control} disabled={isSubmitting}>
{renderLargeRadioCards('highMemory')}
</RadioFieldDyn>
</Tabs.Content>
<Tabs.Content value="custom">
<NumberField
required
label="CPUs"
name="ncpus"
min={1}
control={control}
validate={(cpus) => {
if (cpus < 1) {
return `Must be at least 1 vCPU`
}
if (cpus > INSTANCE_MAX_CPU) {
return `Can be at most ${INSTANCE_MAX_CPU}`
}
}}
disabled={isSubmitting}
/>
<NumberField
units="GiB"
required
label="Memory"
name="memory"
min={1}
control={control}
validate={(memory) => {
if (memory < 1) {
return `Must be at least 1 GiB`
}
if (memory > INSTANCE_MAX_RAM_GiB) {
return `Can be at most ${INSTANCE_MAX_RAM_GiB} GiB`
}
}}
disabled={isSubmitting}
/>
</Tabs.Content>
</Tabs.Root>
<FormDivider />
<Form.Heading id="boot-disk">Boot disk</Form.Heading>
<Tabs.Root
id="boot-disk-tabs"
className="full-width"
// default to the project images tab if there are only project images
defaultValue={defaultSource}
onValueChange={(val) => {
setValue('bootDiskSourceType', val as BootDiskSourceType)
if (imageSizeGiB && imageSizeGiB > bootDiskSize) {
setValue('bootDiskSize', diskSizeNearest10(imageSizeGiB))
}
}}
>
<Tabs.List aria-describedby="boot-disk">
<Tabs.Trigger
value={'siloImage' satisfies BootDiskSourceType}
disabled={isSubmitting}
>
Silo images
</Tabs.Trigger>
<Tabs.Trigger
value={'projectImage' satisfies BootDiskSourceType}
disabled={isSubmitting}
>
Project images
</Tabs.Trigger>
<Tabs.Trigger
value={'disk' satisfies BootDiskSourceType}
disabled={isSubmitting}
>
Existing disks
</Tabs.Trigger>
</Tabs.List>
{allImages.length === 0 && disks.length === 0 && (
<Message
className="mb-8 ml-10 max-w-lg"
variant="notice"
content="Images or disks are required to create or attach a boot disk."
/>
)}
<Tabs.Content
value={'siloImage' satisfies BootDiskSourceType}
className="space-y-4"
>
{siloImages.length === 0 ? (
<div className="border-default flex max-w-lg items-center justify-center rounded-lg border p-6">
<EmptyMessage
icon={<Images16Icon />}
title="No silo images found"
body="Promote a project image to see it here"
/>
</div>
) : (
<>
<ImageSelectField
images={siloImages}
control={control}
disabled={isSubmitting}
name="siloImageSource"
/>
{bootDiskSizeAndName}
</>
)}
</Tabs.Content>
<Tabs.Content
value={'projectImage' satisfies BootDiskSourceType}
className="space-y-4"
>
{projectImages.length === 0 ? (
<div className="border-default flex max-w-lg items-center justify-center rounded-lg border p-6">
<EmptyMessage
icon={<Images16Icon />}
title="No project images found"
body="Upload an image to see it here"
buttonText="Upload image"
onClick={() => navigate(pb.projectImagesNew({ project }))}
/>
</div>
) : (
<>
<ImageSelectField
images={projectImages}
control={control}
disabled={isSubmitting}
name="projectImageSource"
/>
{bootDiskSizeAndName}
</>
)}
</Tabs.Content>
<Tabs.Content value={'disk' satisfies BootDiskSourceType} className="space-y-4">
{disks.length === 0 ? (
<div className="border-default flex max-w-lg items-center justify-center rounded-lg border p-6">
<EmptyMessage
icon={<Storage16Icon />}
title="No detached disks found"
body="Only detached disks can be used as a boot disk"
/>
</div>
) : (
<ComboboxField
label="Disk"
name="diskSource"
description="Existing disks that are not attached to an instance"
items={disks}
required
control={control}
placeholder="Select a disk"
/>
)}
</Tabs.Content>
</Tabs.Root>
<FormDivider />
<Form.Heading id="additional-disks">Additional disks</Form.Heading>
<DisksTableField
control={control}
disabled={isSubmitting}
// Don't allow the user to create a new disk with a name that matches other disk names (either the boot disk,
// the names of disks that will be created and attached to this instance, or disks that already exist).
unavailableDiskNames={[bootDiskName, ...unavailableDiskNames]}
/>
<FormDivider />
<Form.Heading id="authentication">Authentication</Form.Heading>
<SshKeysField control={control} isSubmitting={isSubmitting} />
<FormDivider />
<Form.Heading id="networking">Networking</Form.Heading>
<NetworkingSection
control={control}
isSubmitting={isSubmitting}
unicastPools={unicastPools}
hasVpcs={hasVpcs}
/>
<FormDivider />
<Form.Heading id="advanced">Advanced</Form.Heading>
<ListboxField
control={control}
name="cpuPlatform"
label="CPU platform"
description="If a CPU platform is specified, the instance will only be placed on compatible hosts."
items={cpuPlatformItems}
className="max-w-lg"
disabled={isSubmitting}
/>
<FileField
id="user-data-input"
description={<UserDataDescription />}
name="userData"
label="User Data"
control={control}
disabled={isSubmitting}
/>
<Form.Actions>
<Form.Submit loading={createInstance.isPending}>Create instance</Form.Submit>
<Form.Cancel onClick={() => navigate(pb.instances({ project }))} />
</Form.Actions>
</FullPageForm>
</>
)
}
const FloatingIpLabel = ({ ip }: { ip: FloatingIp }) => (
<div>
<div>{ip.name}</div>
<div className="text-secondary selected:text-accent-secondary flex gap-0.5">
<div>{ip.ip}</div>
{ip.description && (
<>
<Slash />
<div className="grow overflow-hidden text-left text-ellipsis whitespace-pre">
{ip.description}
</div>
</>
)}
</div>
</div>
)
const NetworkingSection = ({
control,
isSubmitting,
unicastPools,
hasVpcs,
}: {
control: Control<InstanceCreateInput>
isSubmitting: boolean
unicastPools: UnicastIpPool[]
hasVpcs: boolean
}) => {
const networkInterfaces = useWatch({ control, name: 'networkInterfaces' })
const [floatingIpModalOpen, setFloatingIpModalOpen] = useState(false)
const [selectedFloatingIp, setSelectedFloatingIp] = useState<FloatingIp | undefined>()
const floatingIpsField = useController({ control, name: 'floatingIps' })
const attachedFloatingIpNames = floatingIpsField.field.value ?? EMPTY_NAME_OR_ID_LIST
// Calculate compatible IP versions based on NIC type
const compatibleVersions = useMemo(
() => getCompatibleVersionsFromNicType(networkInterfaces),
[networkInterfaces]
)
const { project } = useProjectSelector()
const { data: floatingIpList } = usePrefetchedQuery(
q(api.floatingIpList, { query: { project, limit: ALL_ISH } })
)
// Derive attached+available lists from one indexed pass to avoid repeated
// lookups
const { attachedFloatingIps, availableFloatingIps } = useMemo(() => {
// Filter out the IPs that are already attached to an instance
const attachableFloatingIps = floatingIpList.items.filter((ip) => !ip.instanceId)
const attachedNames = new Set(attachedFloatingIpNames)
const attachableByName = new Map(
attachableFloatingIps.map((ip) => [ip.name, ip] as const)
)
const attachedFloatingIps = attachedFloatingIpNames
.map((name) => attachableByName.get(name))
.filter((ip) => !!ip)
// To find available floating IPs, remove the ones already committed to this
// instance and filter by IP version compatibility with configured NICs.
const availableFloatingIps = attachableFloatingIps
.filter((ip) => !attachedNames.has(ip.name))
.filter(ipHasVersion(compatibleVersions))
return { attachedFloatingIps, availableFloatingIps }
}, [floatingIpList.items, attachedFloatingIpNames, compatibleVersions])
const closeFloatingIpModal = () => {
setFloatingIpModalOpen(false)
setSelectedFloatingIp(undefined)
}
const attachFloatingIp = () => {
if (selectedFloatingIp) {
const current = floatingIpsField.field.value || []
const next = current.includes(selectedFloatingIp.name)
? current
: [...current, selectedFloatingIp.name]
floatingIpsField.field.onChange(next)
}
closeFloatingIpModal()
}
const detachFloatingIp = (name: string) => {
const current = floatingIpsField.field.value || []
floatingIpsField.field.onChange(current.filter((floatingIp) => floatingIp !== name))
}
const selectedFloatingIpMessage = (
<>
This instance will be reachable at{' '}
{selectedFloatingIp ? <HL>{selectedFloatingIp.ip}</HL> : 'the selected IP'}
</>
)
return (
<>
{!hasVpcs && (
<Message
className="mb-4"
variant="notice"
content={
<>
A VPC is required to add network interfaces.{' '}
<Link to={pb.vpcsNew({ project })}>Create a VPC</Link> to enable networking.
</>
}
/>
)}
<NetworkInterfaceField control={control} disabled={isSubmitting} hasVpcs={hasVpcs} />
<div className="flex flex-1 flex-col gap-4">
<h2 className="text-sans-md flex items-center">
Ephemeral IP{' '}
<TipIcon className="ml-1.5">
Ephemeral IPs are allocated when the instance is created and deallocated when it
is deleted
</TipIcon>
</h2>
<div className="flex flex-col gap-2">
<EphemeralIpCheckbox
control={control}