-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathhandlers.ts
More file actions
2378 lines (2151 loc) · 82.4 KB
/
handlers.ts
File metadata and controls
2378 lines (2151 loc) · 82.4 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 { addHours } from 'date-fns'
import { delay } from 'msw'
import * as R from 'remeda'
import { lt as semverLessThan, rcompare as semverRCompare } from 'semver'
import { match } from 'ts-pattern'
import { validate as isUuid, v4 as uuid } from 'uuid'
import {
diskCan,
FLEET_ID,
INSTANCE_MAX_CPU,
INSTANCE_MAX_RAM_GiB,
INSTANCE_MIN_RAM_GiB,
MAX_DISKS_PER_INSTANCE,
MAX_NICS_PER_INSTANCE,
type AffinityGroupMember,
type AntiAffinityGroupMember,
type ApiTypes as Api,
type FleetRole,
type InstanceDiskAttachment,
type SamlIdentityProvider,
} from '@oxide/api'
import { json, makeHandlers, type Json } from '~/api/__generated__/msw-handlers'
import { instanceCan, OXQL_GROUP_BY_ERROR } from '~/api/util'
import { parseIpNet } from '~/util/ip'
import { commaSeries } from '~/util/str'
import { GiB } from '~/util/units'
import { defaultSilo, toIdp } from '../silo'
import { getTimestamps } from '../util'
import { defaultFirewallRules } from '../vpc'
import {
db,
getIpFromPool,
lookup,
lookupById,
notFoundErr,
resolvePoolSelector,
utilizationForSilo,
} from './db'
import {
currentUser,
errIfExists,
errIfInvalidDiskSize,
forbiddenErr,
getBlockSize,
handleMetrics,
handleOxqlMetrics,
ipRangeLen,
NotImplemented,
paginated,
randomHex,
requireFleetAdmin,
requireFleetAdminOrSiloAdmin,
requireFleetCollab,
requireFleetViewer,
requireRole,
resolveIpStack,
unavailableErr,
updateDesc,
userHasRole,
} from './util'
// Note the *JSON types. Those represent actual API request and response bodies,
// the snake-cased objects coming straight from the API before the generated
// client camel-cases the keys and parses date fields. Inside the mock API everything
// is *JSON type.
export const handlers = makeHandlers({
logout: () => 204,
ping: () => ({ status: 'ok' }),
deviceAuthRequest: () => 200,
deviceAuthConfirm: ({ body }) => (body.user_code === 'ERRO-RABC' ? 400 : 200),
deviceAccessToken: () => 200,
loginLocal: ({ body: { password } }) => (password === 'bad' ? 401 : 200),
groupList: (params) => paginated(params.query, db.userGroups),
groupView: (params) => lookupById(db.userGroups, params.path.groupId),
projectList: ({ query, cookies }) => {
// this is used to test for the IdP misconfig situation where the user has
// no role on the silo (see error-pages.e2e.ts). requireRole checks for _at
// least_ viewer, and viewer is the weakest role, so checking for viewer
// effectively means "do I have any role at all"
const user = currentUser(cookies)
requireRole(cookies, 'silo', user.silo_id, 'viewer')
// Filter projects by the current user's silo, strip internal silo_id field
const siloProjects = db.projects
.filter((p) => p.silo_id === user.silo_id)
.map((p) => R.omit(p, ['silo_id']))
return paginated(query, siloProjects)
},
projectCreate({ body, cookies }) {
const user = currentUser(cookies)
errIfExists(db.projects, { name: body.name, silo_id: user.silo_id }, 'project')
const newProject = {
id: uuid(),
...body,
...getTimestamps(),
silo_id: user.silo_id,
}
db.projects.push(newProject)
return json(R.omit(newProject, ['silo_id']), { status: 201 })
},
projectView: ({ path }) => {
if (path.project.endsWith('error-503')) {
throw unavailableErr()
} else if (path.project.endsWith('error-403')) {
throw forbiddenErr()
}
return R.omit(lookup.project({ ...path }), ['silo_id'])
},
projectUpdate({ body, path }) {
const project = lookup.project({ ...path })
if (body.name) {
// only check for existing name if it's being changed
if (body.name !== project.name) {
errIfExists(db.projects, { name: body.name })
}
project.name = body.name
}
updateDesc(project, body)
return R.omit(project, ['silo_id'])
},
projectDelete({ path }) {
const project = lookup.project({ ...path })
// imitate API logic (TODO: check for every other kind of project child)
if (db.vpcs.some((vpc) => vpc.project_id === project.id)) {
throw 'Project to be deleted contains a VPC'
}
db.projects = db.projects.filter((p) => p.id !== project.id)
return 204
},
diskList({ query }) {
const project = lookup.project(query)
const disks = db.disks.filter((d) => d.project_id === project.id)
return paginated(query, disks)
},
diskCreate({ body, query }) {
const project = lookup.project(query)
errIfExists(db.disks, { name: body.name, project_id: project.id })
if (body.name === 'disk-create-500') throw 500
const { name, description, size, disk_backend } = body
const diskSource = disk_backend.type === 'distributed' ? disk_backend.disk_source : null
const { image_id, snapshot_id, read_only, state } = match(diskSource)
.with({ type: 'image' }, (s) => ({
image_id: s.image_id,
snapshot_id: null,
read_only: s.read_only === true,
state: { state: 'detached' } as const,
}))
.with({ type: 'snapshot' }, (s) => ({
image_id: null,
snapshot_id: s.snapshot_id,
read_only: s.read_only === true,
state: { state: 'detached' } as const,
}))
.with({ type: 'importing_blocks' }, () => ({
image_id: null,
snapshot_id: null,
read_only: false,
// https://github.com/oxidecomputer/omicron/blob/dd74446/nexus/src/app/sagas/disk_create.rs#L805-L850
state: { state: 'import_ready' } as const,
}))
.otherwise(() => ({
image_id: null,
snapshot_id: null,
read_only: false,
state: { state: 'detached' } as const,
}))
const newDisk: Json<Api.Disk> = {
id: uuid(),
project_id: project.id,
state,
device_path: '/mnt/disk',
name,
description,
size,
block_size: getBlockSize(disk_backend),
disk_type: disk_backend.type,
image_id,
snapshot_id,
read_only,
...getTimestamps(),
}
db.disks.push(newDisk)
return json(newDisk, { status: 201 })
},
diskView: ({ path, query }) => lookup.disk({ ...path, ...query }),
diskDelete({ path, query }) {
const disk = lookup.disk({ ...path, ...query })
if (!diskCan.delete(disk)) {
throw 'Cannot delete disk in state ' + disk.state.state
}
db.disks = db.disks.filter((d) => d.id !== disk.id)
return 204
},
async diskBulkWriteImportStart({ path, query }) {
const disk = lookup.disk({ ...path, ...query })
if (disk.name === 'import-start-500') throw 500
if (disk.state.state !== 'import_ready') {
throw 'Can only enter state importing_from_bulk_write from import_ready'
}
await delay(2000) // slow it down for the tests
db.diskBulkImportState.set(disk.id, { blocks: {} })
disk.state = { state: 'importing_from_bulk_writes' }
return 204
},
async diskBulkWriteImportStop({ path, query }) {
const disk = lookup.disk({ ...path, ...query })
if (disk.name === 'import-stop-500') throw 500
if (disk.state.state !== 'importing_from_bulk_writes') {
throw 'Can only stop import for disk in state importing_from_bulk_write'
}
await delay(2000) // slow it down for the tests
db.diskBulkImportState.delete(disk.id)
disk.state = { state: 'import_ready' }
return 204
},
async diskBulkWriteImport({ path, query, body }) {
const disk = lookup.disk({ ...path, ...query })
const diskImport = db.diskBulkImportState.get(disk.id)
if (!diskImport) throw notFoundErr(`disk import for disk '${disk.id}'`)
await delay(1000) // slow it down for the tests
// if (Math.random() < 0.01) throw 400
diskImport.blocks[body.offset] = true
return 204
},
diskFinalizeImport: ({ path, query, body }) => {
const disk = lookup.disk({ ...path, ...query })
if (disk.name === 'disk-finalize-500') throw 500
if (disk.state.state !== 'import_ready') {
throw `Cannot finalize disk in state ${disk.state.state}. Must be import_ready.`
}
// for now, don't check that the file is complete. the API doesn't
disk.state = { state: 'detached' }
if (body.snapshot_name) {
const newSnapshot: Json<Api.Snapshot> = {
id: uuid(),
name: body.snapshot_name,
description: 'temporary snapshot for making an image',
...getTimestamps(),
state: 'ready',
project_id: disk.project_id,
disk_id: disk.id,
size: disk.size,
}
db.snapshots.push(newSnapshot)
}
return 204
},
floatingIpCreate({ body, query }) {
const project = lookup.project(query)
errIfExists(db.floatingIps, { name: body.name, project_id: project.id })
const addressAllocator = body.address_allocator || { type: 'auto' }
// Determine the pool and IP
// Floating IPs must use unicast pools
let pool: Json<Api.IpPool>
let ip: string
if (addressAllocator.type === 'explicit') {
// Pool is inferred from the IP address since IP pools cannot have overlapping ranges
ip = addressAllocator.ip
// Find the pool that contains this IP by checking all ranges
const poolWithIp = db.ipPools.find((p) => {
if (p.pool_type !== 'unicast') return false
const ranges = db.ipPoolRanges.filter((r) => r.ip_pool_id === p.id)
return ranges.some(() => {
// Simple check - in real API this would do proper IP range comparison
return true // For mock purposes, just use first unicast pool
})
})
pool = poolWithIp || resolvePoolSelector(undefined, 'unicast')
} else {
// type === 'auto'
pool = resolvePoolSelector(addressAllocator.pool_selector, 'unicast')
ip = getIpFromPool(pool)
}
const newFloatingIp: Json<Api.FloatingIp> = {
id: uuid(),
project_id: project.id,
ip,
ip_pool_id: pool.id,
description: body.description,
name: body.name,
...getTimestamps(),
}
db.floatingIps.push(newFloatingIp)
return json(newFloatingIp, { status: 201 })
},
floatingIpList({ query }) {
const project = lookup.project(query)
const ips = db.floatingIps.filter((i) => i.project_id === project.id)
return paginated(query, ips)
},
floatingIpView: ({ path, query }) => lookup.floatingIp({ ...path, ...query }),
floatingIpUpdate: ({ path, query, body }) => {
const floatingIp = lookup.floatingIp({ ...path, ...query })
if (body.name) {
// only check for existing name if it's being changed
if (body.name !== floatingIp.name) {
errIfExists(db.floatingIps, { name: body.name, project_id: floatingIp.project_id })
}
floatingIp.name = body.name
}
updateDesc(floatingIp, body)
return floatingIp
},
floatingIpDelete({ path, query }) {
const floatingIp = lookup.floatingIp({ ...path, ...query })
db.floatingIps = db.floatingIps.filter((i) => i.id !== floatingIp.id)
return 204
},
floatingIpAttach({ path: { floatingIp }, query: { project }, body }) {
const dbFloatingIp = lookup.floatingIp({ floatingIp, project })
if (dbFloatingIp.instance_id) {
throw 'floating IP cannot be attached to one instance while still attached to another'
}
// Following the API logic here, which says that when the instance is passed
// by name, we pull the project ID off the floating IP.
//
// https://github.com/oxidecomputer/omicron/blob/e434307/nexus/src/app/external_ip.rs#L171-L201
const dbInstance = lookup.instance({
instance: body.parent,
project: isUuid(body.parent) ? undefined : project,
})
dbFloatingIp.instance_id = dbInstance.id
return dbFloatingIp
},
floatingIpDetach({ path, query }) {
const floatingIp = lookup.floatingIp({ ...path, ...query })
db.floatingIps = db.floatingIps.map((ip) =>
ip.id !== floatingIp.id ? ip : { ...ip, instance_id: undefined }
)
return floatingIp
},
imageList({ query }) {
if (query.project) {
const project = lookup.project(query)
const images = db.images.filter((i) => i.project_id === project.id)
return paginated(query, images)
}
// silo images
const images = db.images.filter((i) => !i.project_id)
return paginated(query, images)
},
imageCreate({ body, query }) {
let project_id: string | undefined = undefined
if (query.project) {
project_id = lookup.project(query).id
}
errIfExists(db.images, { name: body.name, project_id })
const size =
body.source.type === 'snapshot'
? lookup.snapshot({ snapshot: body.source.id }).size
: 100
const newImage: Json<Api.Image> = {
id: uuid(),
project_id,
size,
block_size: 512,
...body,
...getTimestamps(),
}
db.images.push(newImage)
return json(newImage, { status: 201 })
},
imageView: ({ path, query }) => lookup.image({ ...path, ...query }),
imageDelete({ path, query, cookies }) {
// if it's a silo image, you need silo write to delete it
if (!query.project) {
requireRole(cookies, 'silo', defaultSilo.id, 'collaborator')
}
const image = lookup.image({ ...path, ...query })
db.images = db.images.filter((i) => i.id !== image.id)
return 204
},
imagePromote({ path, query }) {
const image = lookup.image({ ...path, ...query })
delete image.project_id
return json(image, { status: 202 })
},
imageDemote({ path: { image }, query: { project } }) {
// unusual case because the project is never used to resolve the image. you
// can only demote silo images, and whether we have an image name or ID, if
// there is no project specified, the lookup assumes it's a silo image
const dbImage = lookup.image({ image })
const dbProject = lookup.project({ project })
dbImage.project_id = dbProject.id
return json(dbImage, { status: 202 })
},
instanceList({ query }) {
const project = lookup.project(query)
const instances = db.instances.filter((i) => i.project_id === project.id)
return paginated(query, instances)
},
instanceCreate({ body, query }) {
const project = lookup.project(query)
if (body.name === 'no-default-pool') {
throw notFoundErr('default IP pool for current silo')
}
errIfExists(db.instances, { name: body.name, project_id: project.id }, 'instance')
const instanceId = uuid()
if (body.memory > INSTANCE_MAX_RAM_GiB * GiB) {
throw `Memory can be at most ${INSTANCE_MAX_RAM_GiB} GiB`
}
if (body.memory < INSTANCE_MIN_RAM_GiB * GiB) {
throw `Memory must be at least ${INSTANCE_MIN_RAM_GiB} GiB`
}
if (body.ncpus > INSTANCE_MAX_CPU) {
throw `vCPUs must be less than ${INSTANCE_MAX_CPU}`
}
if (body.ncpus < 1) {
throw `Must have at least 1 vCPU`
}
/**
* Eagerly check for disk errors. Execution will stop early and prevent orphaned disks from
* being created if there's a failure. In omicron this is done automatically via an undo on the saga.
*/
const allDisks: Json<InstanceDiskAttachment>[] = []
if (body.disks) allDisks.push(...body.disks)
if (body.boot_disk) allDisks.push(body.boot_disk)
if (allDisks.length > MAX_DISKS_PER_INSTANCE) {
throw `Cannot attach more than ${MAX_DISKS_PER_INSTANCE} disks to an instance`
}
for (const diskParams of allDisks) {
if (diskParams.type === 'create') {
errIfExists(db.disks, { name: diskParams.name, project_id: project.id }, 'disk')
errIfInvalidDiskSize(diskParams)
} else {
const disk = lookup.disk({ ...query, disk: diskParams.name })
if (disk.state.state !== 'detached')
throw `Disk '${diskParams.name}' is already attached to an instance`
}
}
/**
* Eagerly check for nic lookup failures. Execution will stop early and prevent orphaned nics from
* being created if there's a failure. In omicron this is done automatically via an undo on the saga.
*/
if (body.network_interfaces?.type === 'create') {
if (body.network_interfaces.params.length > MAX_NICS_PER_INSTANCE) {
throw `Cannot create more than ${MAX_NICS_PER_INSTANCE} nics per instance`
}
body.network_interfaces.params.forEach(({ vpc_name, subnet_name }) => {
lookup.vpc({ ...query, vpc: vpc_name })
lookup.vpcSubnet({ ...query, vpc: vpc_name, subnet: subnet_name })
})
}
// validate floating IP attachments before we actually do anything
// Determine what IP stacks the instance will have based on network interfaces
let hasIpv4Nic = false
let hasIpv6Nic = false
const nicType = body.network_interfaces?.type
if (nicType === 'default_ipv4') {
hasIpv4Nic = true
} else if (nicType === 'default_ipv6') {
hasIpv6Nic = true
} else if (nicType === 'default_dual_stack') {
hasIpv4Nic = true
hasIpv6Nic = true
} else if (nicType === 'create' && body.network_interfaces) {
// Derive from the first NIC's ip_config (first NIC becomes primary)
const primaryNicConfig = body.network_interfaces.params[0]?.ip_config
if (primaryNicConfig?.type === 'v4') {
hasIpv4Nic = true
} else if (primaryNicConfig?.type === 'v6') {
hasIpv6Nic = true
} else if (primaryNicConfig?.type === 'dual_stack') {
hasIpv4Nic = true
hasIpv6Nic = true
} else {
// ip_config not provided = defaults to dual-stack
hasIpv4Nic = true
hasIpv6Nic = true
}
}
// If nicType is 'none' or undefined, both remain false
body.external_ips?.forEach((ip) => {
if (ip.type === 'floating') {
// throw if floating IP doesn't exist
const floatingIp = lookup.floatingIp({
project: project.id,
floatingIp: ip.floating_ip,
})
if (floatingIp.instance_id) {
throw 'floating IP cannot be attached to one instance while still attached to another'
}
} else {
// just make sure we can get one. technically this will only throw
// if there are no ranges in the pool or if the pool doesn't exist,
// which aren't quite as good as checking that there are actually IPs
// available, but they are good things to check
// Ephemeral IPs must use unicast pools
const pool = resolvePoolSelector(ip.pool_selector, 'unicast')
getIpFromPool(pool)
// Validate that external IP version matches NIC's IP stack
// Based on Omicron validation in nexus/db-queries/src/db/datastore/external_ip.rs:544-661
const ipVersion = pool.ip_version
if (ipVersion === 'v4' && !hasIpv4Nic) {
throw json(
{
error_code: 'InvalidRequest',
message: `The ephemeral external IP is an IPv4 address, but the instance with ID ${body.name} does not have a primary network interface with a VPC-private IPv4 address. Add a VPC-private IPv4 address to the interface, or attach a different IP address`,
},
{ status: 400 }
)
}
if (ipVersion === 'v6' && !hasIpv6Nic) {
throw json(
{
error_code: 'InvalidRequest',
message: `The ephemeral external IP is an IPv6 address, but the instance with ID ${body.name} does not have a primary network interface with a VPC-private IPv6 address. Add a VPC-private IPv6 address to the interface, or attach a different IP address`,
},
{ status: 400 }
)
}
}
})
//////////////////////////////////////////////////////////////////////////
// DB WRITES START HERE
//
// We don't have transactions or sagas, so we need to make sure we do all
// our validation and throw any errors about bad input before we make any
// changes to the DB that would have to be undone on failure.
//////////////////////////////////////////////////////////////////////////
for (const diskParams of allDisks) {
if (diskParams.type === 'create') {
const { size, name, description, disk_backend } = diskParams
const diskSource =
disk_backend.type === 'distributed' ? disk_backend.disk_source : null
const read_only = match(diskSource)
.with({ type: 'image', read_only: true }, () => true)
.with({ type: 'snapshot', read_only: true }, () => true)
.otherwise(() => false)
const newDisk: Json<Api.Disk> = {
id: uuid(),
name,
description,
size,
project_id: project.id,
state: { state: 'attached', instance: instanceId },
device_path: '/mnt/disk',
block_size: getBlockSize(disk_backend),
disk_type: disk_backend.type,
read_only,
...getTimestamps(),
}
db.disks.push(newDisk)
} else {
const disk = lookup.disk({ ...query, disk: diskParams.name })
disk.state = { state: 'attached', instance: instanceId }
}
}
// at this point, the boot disk has been created, so just retrieve it again
const bootDiskId = body.boot_disk?.name
? lookup.disk({ disk: body.boot_disk.name, project: project.id }).id
: undefined
// just use the first VPC in the project and first subnet in the VPC. bit of
// a hack but not very important
const anyVpc = db.vpcs.find((v) => v.project_id === project.id)
const anySubnet = db.vpcSubnets.find((s) => s.vpc_id === anyVpc?.id)
const niType = body.network_interfaces?.type
if (
(niType === 'default_ipv4' ||
niType === 'default_ipv6' ||
niType === 'default_dual_stack') &&
anyVpc &&
anySubnet
) {
db.networkInterfaces.push({
id: uuid(),
description: 'The default network interface',
instance_id: instanceId,
primary: true,
mac: '00:00:00:00:00:00',
ip_stack:
niType === 'default_dual_stack'
? {
type: 'dual_stack',
value: {
v4: { ip: '127.0.0.1', transit_ips: [] },
v6: { ip: '::1', transit_ips: [] },
},
}
: niType === 'default_ipv6'
? { type: 'v6', value: { ip: '::1', transit_ips: [] } }
: { type: 'v4', value: { ip: '127.0.0.1', transit_ips: [] } },
name: 'default',
vpc_id: anyVpc.id,
subnet_id: anySubnet.id,
...getTimestamps(),
})
} else if (body.network_interfaces?.type === 'create') {
body.network_interfaces.params.forEach(
({ name, description, ip_config, subnet_name, vpc_name }, i) => {
db.networkInterfaces.push({
id: uuid(),
name,
description,
instance_id: instanceId,
primary: i === 0,
mac: '00:00:00:00:00:00',
ip_stack: ip_config
? resolveIpStack(ip_config)
: {
type: 'v4',
value: { ip: '127.0.0.1', transit_ips: [] },
},
vpc_id: lookup.vpc({ ...query, vpc: vpc_name }).id,
subnet_id: lookup.vpcSubnet({ ...query, vpc: vpc_name, subnet: subnet_name })
.id,
...getTimestamps(),
})
}
)
}
// actually set up IPs. looks very similar to validation step but this time
// we are writing to the DB
body.external_ips?.forEach((ip) => {
if (ip.type === 'floating') {
const floatingIp = lookup.floatingIp({
project: project.id,
floatingIp: ip.floating_ip,
})
// we've already validated that the IP isn't attached
floatingIp.instance_id = instanceId
} else if (ip.type === 'ephemeral') {
// Ephemeral IPs must use unicast pools
const pool = resolvePoolSelector(ip.pool_selector, 'unicast')
const firstAvailableAddress = getIpFromPool(pool)
db.ephemeralIps.push({
instance_id: instanceId,
external_ip: {
ip: firstAvailableAddress,
ip_pool_id: pool.id,
kind: 'ephemeral',
},
})
}
})
const newInstance: Json<Api.Instance> = {
id: instanceId,
project_id: project.id,
...R.pick(body, [
'name',
'description',
'hostname',
'memory',
'ncpus',
'cpu_platform',
]),
...getTimestamps(),
run_state: 'creating',
time_run_state_updated: new Date().toISOString(),
boot_disk_id: bootDiskId,
auto_restart_enabled: true,
}
if (body.start) {
setTimeout(() => {
newInstance.run_state = 'starting'
}, 1500)
setTimeout(() => {
newInstance.run_state = 'running'
}, 4000)
}
db.instances.push(newInstance)
return json(newInstance, { status: 201 })
},
instanceView: ({ path, query }) => lookup.instance({ ...path, ...query }),
instanceUpdate({ path, query, body }) {
const instance = lookup.instance({ ...path, ...query })
if (instance.name === 'instance-update-error') {
throw 'Cannot update instance'
}
const resize = body.ncpus !== instance.ncpus || body.memory !== instance.memory
if (resize && !instanceCan.resize({ runState: instance.run_state })) {
const states = instanceCan.resize.states
throw `Instance can only be resized if ${commaSeries(states, 'or')}`
}
// always present on the body, always set them
instance.ncpus = body.ncpus
instance.memory = body.memory
const rejectSetBootDisk = `Boot disk can only be changed if instance is ${commaSeries(instanceCan.updateBootDisk.states, 'or')}`
if (body.boot_disk) {
// Only include project if it's a name, otherwise lookup will error.
// This will 404 if the disk doesn't exist, which I think is right.
const disk = lookup.disk({
disk: body.boot_disk,
project: isUuid(body.boot_disk) ? undefined : query.project,
})
// blow up if we're trying to change the boot disk but instance isn't stopped
if (
disk.id !== instance.boot_disk_id &&
!instanceCan.updateBootDisk({ runState: instance.run_state })
) {
throw rejectSetBootDisk
}
const isAttached =
disk.state.state === 'attached' && disk.state.instance === instance.id
if (!(diskCan.setAsBootDisk(disk) && isAttached)) {
throw 'Boot disk must be attached to the instance'
}
instance.boot_disk_id = disk.id
} else {
// we're clearing the boot disk!
// if we already have a boot disk, the request is trying to unset it, so blow
// up if that's not allowed
if (
instance.boot_disk_id &&
!instanceCan.updateBootDisk({ runState: instance.run_state })
) {
throw rejectSetBootDisk
}
instance.boot_disk_id = undefined
}
// AUTO RESTART
// null is meaningful: it unsets the value
instance.auto_restart_policy = body.auto_restart_policy
instance.cpu_platform = body.cpu_platform
// We depart here from nexus in that nexus does both of the following
// calculations at view time (when converting model to view). We can't
// do that/don't need because our mock DB stores and returns the view
// representation directly.
// https://github.com/oxidecomputer/omicron/blob/0c6ab099e/nexus/db-queries/src/db/datastore/instance.rs#L228-L239
instance.auto_restart_enabled = match(instance.auto_restart_policy)
.with(null, () => true)
.with('best_effort', () => true)
.with('never', () => false)
.exhaustive()
// Nexus has something slightly more complicated because it's possible the
// default cooldown of one hour can be overridden at the instance level, but
// that is currently only used in tests, so we should assume all instances
// have the default of 1 hour. It's worth noting this may never come into
// effect unless we deliberately set time_last_auto_restarted on a mock
// instance because the mock API has no ability to actually auto-restart
// an instance.
// https://github.com/oxidecomputer/omicron/blob/0c6ab099e/nexus/db-queries/src/db/datastore/instance.rs#L206-L226
instance.auto_restart_cooldown_expiration = instance.time_last_auto_restarted
? addHours(instance.time_last_auto_restarted, 1).toISOString()
: undefined
return instance
},
instanceDelete({ path, query }) {
const instance = lookup.instance({ ...path, ...query })
db.instances = db.instances.filter((i) => i.id !== instance.id)
// delete instance from any affinity / anti-affinity groups with it as a member
db.affinityGroupMemberLists = db.affinityGroupMemberLists.filter(
(member) => member.affinity_group_member.id !== instance.id
)
db.antiAffinityGroupMemberLists = db.antiAffinityGroupMemberLists.filter(
(member) => member.anti_affinity_group_member.id !== instance.id
)
return 204
},
instanceDiskList({ path, query }) {
const instance = lookup.instance({ ...path, ...query })
// TODO: Should disk instance state be `instance_id` instead of `instance`?
const disks = db.disks.filter(
(d) => 'instance' in d.state && d.state.instance === instance.id
)
return paginated(query, disks)
},
instanceDiskAttach({ body, path, query: projectParams }) {
const instance = lookup.instance({ ...path, ...projectParams })
if (instance.run_state !== 'stopped') {
throw 'Cannot attach disk to instance that is not stopped'
}
const attachedDisks = db.disks.filter(
(d) => 'instance' in d.state && d.state.instance === instance.id
)
if (attachedDisks.length >= MAX_DISKS_PER_INSTANCE) {
throw `Cannot attach more than ${MAX_DISKS_PER_INSTANCE} disks to an instance`
}
const disk = lookup.disk({ ...projectParams, disk: body.disk })
disk.state = {
state: 'attached',
instance: instance.id,
}
return disk
},
instanceDiskDetach({ body, path, query: projectParams }) {
const instance = lookup.instance({ ...path, ...projectParams })
if (!instanceCan.detachDisk({ runState: instance.run_state })) {
const states = commaSeries(instanceCan.detachDisk.states, 'or')
throw `Can only detach disk from instance that is ${states}`
}
const disk = lookup.disk({
disk: body.disk,
// use instance project ID because project may not be specified in params
project: isUuid(body.disk) ? undefined : instance.project_id,
})
if (!diskCan.detach(disk)) {
const states = commaSeries(diskCan.detach.states, 'or')
throw `Can only detach disk that is ${states}`
}
disk.state = { state: 'detached' }
return disk
},
instanceEphemeralIpAttach({ path, query: projectParams, body }) {
const instance = lookup.instance({ ...path, ...projectParams })
// Ephemeral IPs must use unicast pools
const pool = resolvePoolSelector(body.pool_selector, 'unicast')
const ip = getIpFromPool(pool)
// Validate that external IP version matches primary NIC's IP stack
// https://github.com/oxidecomputer/omicron/blob/558f89e/nexus/db-queries/src/db/datastore/external_ip.rs#L673-L687
const nics = db.networkInterfaces.filter((n) => n.instance_id === instance.id)
const primaryNic = nics.find((n) => n.primary)
if (!primaryNic) {
throw json(
{
error_code: 'InvalidRequest',
message: `Instance ${instance.name} has no primary network interface`,
},
{ status: 400 }
)
}
const ipVersion = pool.ip_version
const stackType = primaryNic.ip_stack.type
if (ipVersion === 'v4' && stackType !== 'v4' && stackType !== 'dual_stack') {
throw json(
{
error_code: 'InvalidRequest',
message: `The ephemeral external IP is an IPv4 address, but the instance with ID ${instance.name} does not have a primary network interface with a VPC-private IPv4 address. Add a VPC-private IPv4 address to the interface, or attach a different IP address`,
},
{ status: 400 }
)
}
if (ipVersion === 'v6' && stackType !== 'v6' && stackType !== 'dual_stack') {
throw json(
{
error_code: 'InvalidRequest',
message: `The ephemeral external IP is an IPv6 address, but the instance with ID ${instance.name} does not have a primary network interface with a VPC-private IPv6 address. Add a VPC-private IPv6 address to the interface, or attach a different IP address`,
},
{ status: 400 }
)
}
const externalIp = { ip, ip_pool_id: pool.id, kind: 'ephemeral' as const }
db.ephemeralIps.push({
instance_id: instance.id,
external_ip: externalIp,
})
return externalIp
},
instanceEphemeralIpDetach({ path, query }) {
// When an instance has both IPv4 and IPv6 ephemeral IPs attached, Omicron
// requires an explicit `ipVersion` query param to disambiguate which to
// detach.
// https://github.com/oxidecomputer/omicron/blob/558f89e/nexus/types/src/external_api/params.rs#L267-L277
// https://github.com/oxidecomputer/omicron/blob/558f89e/nexus/src/app/sagas/instance_ip_detach.rs#L75-L99
// https://github.com/oxidecomputer/omicron/blob/558f89e/nexus/src/external_api/http_entrypoints.rs#L4913-L4939
const { ipVersion, ...instanceQuery } = query
const instance = lookup.instance({ ...path, ...instanceQuery })
const attachedIps = db.ephemeralIps.filter((eip) => eip.instance_id === instance.id)
if (attachedIps.length === 0) {
throw notFoundErr(`ephemeral IP for instance ${instance.name}`)
}
const versionOf = (ip: string) => (ip.includes(':') ? 'v6' : 'v4')
const attachedVersions = new Set(
attachedIps.map((eip) => versionOf(eip.external_ip.ip))
)
if (attachedVersions.size > 1 && !ipVersion) {
throw json(
{
error_code: 'InvalidRequest',
message: `Instance ${instance.name} has both IPv4 and IPv6 ephemeral IPs; ipVersion is required to detach one`,
},
{ status: 400 }
)
}
const ip =
ipVersion === undefined
? attachedIps[0]
: attachedIps.find((eip) => versionOf(eip.external_ip.ip) === ipVersion)
if (!ip) throw notFoundErr(`ephemeral IP (${ipVersion}) for instance ${instance.name}`)
db.ephemeralIps = db.ephemeralIps.filter((eip) => eip !== ip)
return 204
},
instanceExternalIpList({ path, query }) {
const instance = lookup.instance({ ...path, ...query })
const ephemeralIps = db.ephemeralIps
.filter((eip) => eip.instance_id === instance.id)
.map((eip) => eip.external_ip)
const snatIps = db.snatIps
.filter((sip) => sip.instance_id === instance.id)
.map((sip) => sip.external_ip)
// floating IPs are missing their `kind` field in the DB so we add it
const floatingIps = db.floatingIps
.filter((f) => f.instance_id === instance.id)
.map((f) => ({ kind: 'floating' as const, ...f }))
// endpoint is not paginated. or rather, it's fake paginated
return { items: [...ephemeralIps, ...snatIps, ...floatingIps] }
},
instanceNetworkInterfaceList({ query }) {
const instance = lookup.instance(query)