-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathNetworkingTab.tsx
More file actions
581 lines (536 loc) · 19.7 KB
/
Copy pathNetworkingTab.tsx
File metadata and controls
581 lines (536 loc) · 19.7 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
/*
* 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 { useQuery } from '@tanstack/react-query'
import { createColumnHelper, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import { useCallback, useMemo, useState } from 'react'
import { type LoaderFunctionArgs } from 'react-router'
import { match } from 'ts-pattern'
import {
api,
instanceCan,
q,
qErrorsAllowed,
queryClient,
useApiMutation,
usePrefetchedQuery,
type ExternalIp,
type InstanceNetworkInterface,
type InstanceState,
} from '@oxide/api'
import { IpGlobal24Icon, Networking24Icon } from '@oxide/design-system/icons/react'
import { Badge } from '@oxide/design-system/ui'
import { AttachEphemeralIpModal } from '~/components/AttachEphemeralIpModal'
import { AttachFloatingIpModal } from '~/components/AttachFloatingIpModal'
import { orderIps } from '~/components/ExternalIps'
import { HL } from '~/components/HL'
import { ListPlusCell } from '~/components/ListPlusCell'
import { CreateNetworkInterfaceForm } from '~/forms/network-interface-create'
import { EditNetworkInterfaceForm } from '~/forms/network-interface-edit'
import {
getInstanceSelector,
useInstanceSelector,
useProjectSelector,
} from '~/hooks/use-params'
import { confirmAction } from '~/stores/confirm-action'
import { confirmDelete } from '~/stores/confirm-delete'
import { addToast } from '~/stores/toast'
import { DescriptionCell } from '~/table/cells/DescriptionCell'
import { EmptyCell, SkeletonCell } from '~/table/cells/EmptyCell'
import { IpPoolCell } from '~/table/cells/IpPoolCell'
import { LinkCell } from '~/table/cells/LinkCell'
import { useColsWithActions, type MenuAction } from '~/table/columns/action-col'
import { Columns } from '~/table/columns/common'
import { Table } from '~/table/Table'
import { Button } from '~/ui/lib/Button'
import { CardBlock } from '~/ui/lib/CardBlock'
import { CopyableIp } from '~/ui/lib/CopyableIp'
import { EmptyMessage } from '~/ui/lib/EmptyMessage'
import { TableEmptyBox } from '~/ui/lib/Table'
import { TipIcon } from '~/ui/lib/TipIcon'
import { Tooltip } from '~/ui/lib/Tooltip'
import { ALL_ISH } from '~/util/consts'
import { pb } from '~/util/path-builder'
import { fancifyStates } from './common'
const VpcNameFromId = ({ value }: { value: string }) => {
const { project } = useProjectSelector()
const { data: vpc, isError } = useQuery(
q(api.vpcView, { path: { vpc: value } }, { throwOnError: false })
)
// If we can't find it, it must have been deleted. This is probably not
// possible because you can't delete a VPC that has child resources, but let's
// be safe
if (isError) return <Badge color="neutral">Deleted</Badge>
if (!vpc) return <SkeletonCell />
return <LinkCell to={pb.vpc({ project, vpc: vpc.name })}>{vpc.name}</LinkCell>
}
const SubnetNameFromId = ({ value }: { value: string }) => {
const { data: subnet, isError } = useQuery(
q(api.vpcSubnetView, { path: { subnet: value } }, { throwOnError: false })
)
// same deal as VPC: probably not possible but let's be safe
if (isError) return <Badge color="neutral">Deleted</Badge>
if (!subnet) return <SkeletonCell /> // loading
return <span className="text-default">{subnet.name}</span>
}
const NonFloatingEmptyCell = ({ kind }: { kind: 'snat' | 'ephemeral' }) => (
<Tooltip
content={`${kind === 'snat' ? 'SNAT' : 'Ephemeral'} IPs don’t have names or descriptions`}
placement="top"
>
<div>
<EmptyCell />
</div>
</Tooltip>
)
export async function clientLoader({ params }: LoaderFunctionArgs) {
const { project, instance } = getInstanceSelector(params)
await Promise.all([
queryClient.fetchQuery(
q(api.instanceNetworkInterfaceList, {
// we want this to cover all NICs; TODO: determine actual limit?
query: { project, instance, limit: ALL_ISH },
})
),
queryClient.fetchQuery(q(api.floatingIpList, { query: { project, limit: ALL_ISH } })),
// dupe of page-level fetch but that's fine, RQ dedupes
queryClient.fetchQuery(
q(api.instanceExternalIpList, { path: { instance }, query: { project } })
),
// This is covered by the InstancePage loader but there's no downside to
// being redundant. If it were removed there, we'd still want it here.
queryClient.fetchQuery(q(api.instanceView, { path: { instance }, query: { project } })),
// Fetch IP Pools and preload into RQ cache so fetches by ID in
// IpPoolCell and AttachFloatingIpModal can be mostly instant
queryClient
.fetchQuery(q(api.projectIpPoolList, { query: { limit: ALL_ISH } }))
.then((pools) => {
for (const pool of pools.items) {
// both IpPoolCell and the fetch in the model use errors-allowed
// versions to avoid blowing up in the unlikely event of an error
const { queryKey } = qErrorsAllowed(api.projectIpPoolView, {
path: { pool: pool.id },
})
queryClient.setQueryData(queryKey, { type: 'success', data: pool })
}
}),
// Fetch VPCs for Add NIC form
queryClient.fetchQuery(q(api.vpcList, { query: { project, limit: ALL_ISH } })),
])
return null
}
// Bit of a hack: by putting the instance state in the row data, we can avoid
// remaking the row actions callback whenever the instance state changes, which
// causes the whole table to get re-rendered, which jarringly closes any open
// row actions menus
type NicRow = InstanceNetworkInterface & {
instanceState: InstanceState
}
const colHelper = createColumnHelper<NicRow>()
const staticCols = [
colHelper.accessor('name', {
header: 'name',
cell: (info) => (
<>
<span>{info.getValue()}</span>
{info.row.original.primary && <Badge className="ml-2">primary</Badge>}
</>
),
}),
colHelper.accessor('description', Columns.description),
colHelper.accessor('ip', {
header: 'Private IP',
cell: (info) => <CopyableIp ip={info.getValue()} isLinked={false} />,
}),
colHelper.accessor('vpcId', {
header: 'vpc',
cell: (info) => <VpcNameFromId value={info.getValue()} />,
}),
colHelper.accessor('subnetId', {
header: 'subnet',
cell: (info) => <SubnetNameFromId value={info.getValue()} />,
}),
colHelper.accessor('transitIps', {
header: 'Transit IPs',
cell: (info) => (
<ListPlusCell tooltipTitle="Other transit IPs">
{info.getValue()?.map((ip) => (
<div key={ip}>{ip}</div>
))}
</ListPlusCell>
),
}),
]
const updateNicStates = fancifyStates(instanceCan.updateNic.states)
const ipColHelper = createColumnHelper<ExternalIp>()
const staticIpCols = [
ipColHelper.accessor('ip', {
cell: (info) => (
<div className="flex items-center gap-2">
<CopyableIp ip={info.getValue()} />
{info.row.original.kind === 'snat' && (
<Tooltip content="Outbound traffic uses this IP and port range" placement="top">
{/* div needed for Tooltip */}
<div>
<Badge color="neutral">
{info.row.original.firstPort}–{info.row.original.lastPort}
</Badge>
</div>
</Tooltip>
)}
</div>
),
}),
ipColHelper.accessor('kind', {
header: () => (
<>
Kind
<TipIcon className="ml-2">
Floating IPs can be detached from this instance and attached to another. SNAT IPs
cannot receive traffic; they are used for outbound traffic when there are no
ephemeral or floating IPs.
</TipIcon>
</>
),
cell: (info) => <Badge color="neutral">{info.getValue()}</Badge>,
}),
ipColHelper.accessor('ipPoolId', {
header: 'IP pool',
cell: (info) => <IpPoolCell ipPoolId={info.getValue()} />,
}),
ipColHelper.accessor('name', {
cell: (info) =>
info.row.original.kind === 'floating' ? (
info.getValue()
) : (
<NonFloatingEmptyCell kind={info.row.original.kind} />
),
}),
ipColHelper.accessor((row) => ('description' in row ? row.description : undefined), {
header: 'description',
cell: (info) =>
info.row.original.kind === 'floating' ? (
<DescriptionCell text={info.getValue()} />
) : (
<NonFloatingEmptyCell kind={info.row.original.kind} />
),
}),
]
export const handle = { crumb: 'Networking' }
export default function NetworkingTab() {
const instanceSelector = useInstanceSelector()
const { instance: instanceName, project } = instanceSelector
const [createModalOpen, setCreateModalOpen] = useState(false)
const [editing, setEditing] = useState<InstanceNetworkInterface | null>(null)
const [attachEphemeralModalOpen, setAttachEphemeralModalOpen] = useState(false)
const [attachFloatingModalOpen, setAttachFloatingModalOpen] = useState(false)
// Fetch the floating IPs to show in the "Attach floating IP" modal
const { data: ips } = usePrefetchedQuery(
q(api.floatingIpList, { query: { project, limit: ALL_ISH } })
)
// Filter out the IPs that are already attached to an instance
const availableIps = useMemo(() => ips.items.filter((ip) => !ip.instanceId), [ips])
const createNic = useApiMutation(api.instanceNetworkInterfaceCreate, {
onSuccess() {
queryClient.invalidateEndpoint('instanceNetworkInterfaceList')
setCreateModalOpen(false)
},
})
const { mutateAsync: deleteNic } = useApiMutation(api.instanceNetworkInterfaceDelete, {
onSuccess(_data, variables) {
queryClient.invalidateEndpoint('instanceNetworkInterfaceList')
addToast(<>Network interface <HL>{variables.path.interface}</HL> deleted</>) // prettier-ignore
},
})
const { mutate: editNic } = useApiMutation(api.instanceNetworkInterfaceUpdate, {
onSuccess() {
queryClient.invalidateEndpoint('instanceNetworkInterfaceList')
},
})
const { data: instance } = usePrefetchedQuery(
q(api.instanceView, { path: { instance: instanceName }, query: { project } })
)
const nics = usePrefetchedQuery(
q(api.instanceNetworkInterfaceList, {
query: { ...instanceSelector, limit: ALL_ISH },
})
).data.items
const multipleNics = nics.length > 1
const makeActions = useCallback(
(nic: NicRow): MenuAction[] => {
const canUpdateNic = instanceCan.updateNic({ runState: nic.instanceState })
const deleteDisabledReason = () => {
if (!canUpdateNic) {
return <>The instance must be {updateNicStates} to delete a network interface</>
}
// If the NIC is primary, we can't delete it if there are other NICs. Per Ben N:
// > There is always zero or one primary NIC. There may zero or more secondary NICs (up to 7 today), but only if there is already a primary.
// > The primary NIC is where we attach all the external networking state, like external addresses, and the VPC information like routes, subnet information, internet gateways, etc.
// > You may delete any secondary NIC. You may delete the primary NIC only if it's the only NIC (there are no secondary NICs).
if (nic.primary && multipleNics) {
return 'The primary interface can’t be deleted while other interfaces are attached. To delete it, make another interface primary.'
}
return undefined
}
return [
{
label: 'Make primary',
onActivate() {
editNic({
path: { interface: nic.name },
query: instanceSelector,
body: { ...nic, primary: true },
})
},
disabled: nic.primary
? 'This network interface is already set as primary'
: !canUpdateNic && (
<>
The instance must be {updateNicStates} to change its primary network
interface
</>
),
},
{
label: 'Edit',
onActivate() {
setEditing(nic)
},
disabled: !canUpdateNic && (
<>
The instance must be {updateNicStates} before editing a network
interface's settings
</>
),
},
{
label: 'Delete',
onActivate: confirmDelete({
doDelete: () =>
deleteNic({
path: { interface: nic.name },
query: instanceSelector,
}),
label: nic.name,
}),
disabled: deleteDisabledReason(),
},
]
},
[deleteNic, editNic, instanceSelector, multipleNics]
)
const columns = useColsWithActions(staticCols, makeActions)
const nicRows = useMemo(
() => nics.map((nic) => ({ ...nic, instanceState: instance.runState })),
[nics, instance]
)
const tableInstance = useReactTable({
columns,
data: nicRows,
getCoreRowModel: getCoreRowModel(),
})
// Attached IPs Table
const { data: eips } = usePrefetchedQuery(
q(api.instanceExternalIpList, {
path: { instance: instanceName },
query: { project },
})
)
const { mutateAsync: ephemeralIpDetach } = useApiMutation(api.instanceEphemeralIpDetach, {
onSuccess() {
queryClient.invalidateEndpoint('instanceExternalIpList')
addToast({ content: 'Ephemeral IP detached' })
},
onError: (err) => {
addToast({ title: 'Error', content: err.message, variant: 'error' })
},
})
const { mutateAsync: floatingIpDetach } = useApiMutation(api.floatingIpDetach, {
onSuccess(_data, variables) {
queryClient.invalidateEndpoint('floatingIpList')
queryClient.invalidateEndpoint('instanceExternalIpList')
addToast(<>Floating IP <HL>{variables.path.floatingIp}</HL> detached</>) // prettier-ignore
},
onError: (err) => {
addToast({ title: 'Error', content: err.message, variant: 'error' })
},
})
const makeIpActions = useCallback(
(externalIp: ExternalIp): MenuAction[] => {
const copyAction = {
label: 'Copy IP address',
onActivate: () => {
window.navigator.clipboard.writeText(externalIp.ip)
},
}
if (externalIp.kind === 'snat') {
return [
copyAction,
{
label: 'Detach',
disabled: "SNAT IPs can't be detached",
onActivate: () => {},
},
]
}
const doDetach = match(externalIp)
.with(
{ kind: 'ephemeral' },
() => () =>
ephemeralIpDetach({ path: { instance: instanceName }, query: { project } })
)
.with(
{ kind: 'floating' },
({ name }) =>
() =>
floatingIpDetach({ path: { floatingIp: name }, query: { project } })
)
.exhaustive()
const label = match(externalIp)
.with({ kind: 'ephemeral' }, () => 'this ephemeral IP')
.with(
{ kind: 'floating' },
({ name }) => <>floating IP <HL>{name}</HL></> // prettier-ignore
)
.exhaustive()
return [
copyAction,
{
label: 'Detach',
onActivate: () =>
confirmAction({
actionType: 'danger',
doAction: doDetach,
modalTitle: `Confirm detach ${externalIp.kind} IP`,
modalContent: (
<p>
Are you sure you want to detach {label} from <HL>{instanceName}</HL>? The
instance will no longer be reachable at <HL>{externalIp.ip}</HL>.
</p>
),
errorTitle: `Error detaching ${externalIp.kind} IP`,
}),
},
]
},
[ephemeralIpDetach, floatingIpDetach, instanceName, project]
)
const ipTableInstance = useReactTable({
columns: useColsWithActions(staticIpCols, makeIpActions),
data: useMemo(() => orderIps(eips.items), [eips]),
getCoreRowModel: getCoreRowModel(),
})
// If there's already an ephemeral IP, or if there are no network interfaces,
// they shouldn't be able to attach an ephemeral IP
const enableEphemeralAttachButton =
eips.items.filter((ip) => ip.kind === 'ephemeral').length === 0 && nics.length > 0
const floatingDisabledReason =
eips.items.filter((ip) => ip.kind === 'floating').length >= 32
? 'Floating IP address limit of 32 reached for this instance'
: availableIps.length === 0
? 'No available floating IPs'
: null
return (
<div className="space-y-5">
<CardBlock>
<CardBlock.Header title="External IPs" titleId="attached-ips-label">
<div className="flex gap-3">
{/*
We normally wouldn't hide this button and would just have a disabled state on it,
but it is very rare for this button to be necessary, and it would be disabled
most of the time, for most users. To reduce clutter on the screen, we're hiding it.
*/}
{enableEphemeralAttachButton && (
<Button size="sm" onClick={() => setAttachEphemeralModalOpen(true)}>
Attach ephemeral IP
</Button>
)}
<Button
size="sm"
onClick={() => setAttachFloatingModalOpen(true)}
disabled={!!floatingDisabledReason}
disabledReason={floatingDisabledReason}
>
Attach floating IP
</Button>
</div>
</CardBlock.Header>
<CardBlock.Body>
{eips.items.length > 0 ? (
<Table
aria-labelledby="attached-ips-label"
table={ipTableInstance}
className="table-inline"
/>
) : (
<TableEmptyBox border={false}>
<EmptyMessage
icon={<IpGlobal24Icon />}
title="No external IPs"
body="Attach an external IP to see it here"
/>
</TableEmptyBox>
)}
</CardBlock.Body>
{attachEphemeralModalOpen && (
<AttachEphemeralIpModal onDismiss={() => setAttachEphemeralModalOpen(false)} />
)}
{attachFloatingModalOpen && (
<AttachFloatingIpModal
floatingIps={availableIps}
instance={instance}
onDismiss={() => setAttachFloatingModalOpen(false)}
/>
)}
</CardBlock>
<CardBlock>
<CardBlock.Header title="Network interfaces" titleId="nics-label">
<Button
size="sm"
onClick={() => setCreateModalOpen(true)}
disabled={!instanceCan.updateNic(instance)}
disabledReason={
<>
A network interface cannot be created or edited unless the instance is{' '}
{updateNicStates}
</>
}
>
Add network interface
</Button>
</CardBlock.Header>
<CardBlock.Body>
{nics.length > 0 ? (
<Table
aria-labelledby="nics-label"
table={tableInstance}
className="table-inline"
/>
) : (
<TableEmptyBox border={false}>
<EmptyMessage
icon={<Networking24Icon />}
title="No network interfaces"
body="Create a network interface to see it here"
/>
</TableEmptyBox>
)}
</CardBlock.Body>
{createModalOpen && (
<CreateNetworkInterfaceForm
onDismiss={() => setCreateModalOpen(false)}
onSubmit={(body) => createNic.mutate({ query: instanceSelector, body })}
submitError={createNic.error}
/>
)}
{editing && (
<EditNetworkInterfaceForm editing={editing} onDismiss={() => setEditing(null)} />
)}
</CardBlock>
</div>
)
}