-
Notifications
You must be signed in to change notification settings - Fork 0
/
embr
executable file
·701 lines (607 loc) · 20.5 KB
/
embr
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
#!/usr/bin/env bash
set -euo pipefail
# Enable command logging if TRACE variable is set
[[ -z "${TRACE:-}" ]] || set -x
# Helper methods for pretty output
_info() { echo -e "\e[92m[INFO] ${1:-}\e[0m"; }
_warn() { echo -e "\e[33m[WARN] ${1:-}\e[0m"; }
_error() {
echo -e "\e[31m[ERROR] ${1:-}\e[0m" >&2
exit 1
}
_debug() { if [[ -n "${DEBUG:-}" ]]; then echo -e "[DEBG] ${1:-}" >&2; fi; }
# Set a sensible default for XDG_RUNTIME_DIR if not set
XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/var/run/user/$(id -u)}"
EMBR_DIR="${HOME}/.config/embr"
RUNTIME_DIR="${XDG_RUNTIME_DIR}/embr"
# VM Configuration
VM_CPUS="${VM_CPUS:-8}"
VM_MEMORY="${VM_MEMORY:-16}"
VM_DISK="${VM_DISK:-20}"
VM_HOSTNAME="${VM_HOSTNAME:-dev}"
VM_SERIES="${VM_SERIES:-jammy}"
VM_USERDATA="$(pwd)/userdata.yaml"
# This is a JSON representation of a cloud-init file. This is a bit of a hack, and it's
# later turned into yaml with the correct '#cloud-config' heading using 'yq'. It's done
# like this to work around awkwardness with how heredocs handle spaces/tabs/indentation.
read -r -d '' USERDATA_TEMPLATE <<-EOF || true
{
"users": [
{
"name": "ubuntu",
"shell": "/bin/bash",
"groups": "sudo",
"sudo": "ALL=(ALL) NOPASSWD:ALL",
"ssh_authorized_keys": ["__KEY__"]
}
]
}
EOF
# Helper method for generating MAC octets
_random_octet() { printf '%02x' $((1 + RANDOM % 99)); }
# Helper method for generating random MAC addresses
_random_mac() { echo "aa:bb:00:$(_random_octet):$(_random_octet):$(_random_octet)"; }
# Helper method for downloading a file to a location on disk
_download() {
if [[ -f "$2" ]]; then
_debug "File '${2}' already exists; skipping download"
else
_info "Downloading: $1"
curl -fsSL -o "$2" "$1"
_debug "Downloaded '${1}' to '${2}'"
fi
}
# Helper method for making a request to the firecracker API
_firecracker_api_call() {
local method endpoint data
method="$1"
endpoint="$2"
data="${3:-}"
curl --unix-socket "$FIRECRACKER_SOCKET" \
-s \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "$data" \
-X "$method" "http://localhost/$endpoint"
_debug "Firecracker API request complete: $method $endpoint:\n$data"
}
cleanup() {
# Kill any dnsmasq processes started by the script
if [[ -e "${RUNTIME_DIR}/dnsmasq/pid" ]]; then
pid="$(cat "${RUNTIME_DIR}/dnsmasq/pid")"
if [[ -d "/proc/${pid}" ]]; then
sudo kill -9 "$pid"
_info "Killed: dnsmasq (PID $pid)"
fi
fi
# Kill each of the firecracker processes that are started
if [[ -n "${PURGE:-}" ]]; then
if pidof -q firecracker; then
sudo killall firecracker
fi
elif [[ -d "${EMBR_DIR}/vm" ]]; then
for d in "${EMBR_DIR}"/vm/*; do
n="$(echo "$d" | rev | cut -d"/" -f1 | rev)"
pid_file="${RUNTIME_DIR}/${n}/firecracker.pid"
if [[ ! -f "$pid_file" ]]; then
continue
fi
pid="$(cat "$pid_file")"
if [[ -d "/proc/${pid}" ]]; then
sudo kill -9 "$pid"
_info "Killed: firecracker (PID $pid)"
fi
done
fi
# Clean up network interfaces that are created by the script
for iface in $(\ip --brief link | grep -Po "embrtap0[^ ]+|embr[^ ]+"); do
sudo ip l del "$iface"
_info "Deleted interface: $iface"
done
# Directories to delete
directories=("${EMBR_DIR}/vm" "${RUNTIME_DIR}")
# If the PURGE variable is set, then delete downloaded images too
[[ -n "${PURGE:-}" ]] && directories+=("${EMBR_DIR}/images")
for d in "${directories[@]}"; do
if [[ -d "$d" ]]; then
rm -rf "$d"
_info "Deleted directory: $d"
fi
done
}
check_dependencies() {
# Ensure we have all the dependenices we need to run this demo
deps=(firecracker yq jq dnsmasq openssl ssh-keygen curl readelf truncate resize2fs killall)
for d in "${deps[@]}"; do
if ! command -v "$d" >/dev/null; then
_error "Could not find '$d' in \$PATH"
fi
done
}
fetch_cloud_image_artefacts() {
# This function handles downloading the relevant kernel, initrd and rootfs
mkdir -p "$DOWNLOAD_DIR"
local base_url
base_url="https://cloud-images.ubuntu.com/${VM_SERIES}/current"
# Download the rootfs if it doesn't exist
_download "${base_url}/${CI_ROOTFS_FILE}" "${DOWNLOAD_DIR}/${CI_ROOTFS_FILE}"
# Download the kernel if it doesn't exist
_download "${base_url}/unpacked/${CI_KERNEL_FILE}" "${DOWNLOAD_DIR}/${CI_KERNEL_FILE}"
# Download the initrd if it doesn't exist
_download "${base_url}/unpacked/${CI_INITRD_FILE}" "${DOWNLOAD_DIR}/${CI_INITRD_FILE}"
}
process_cloud_image_artefacts() {
local tmpdir sdnd_override_dir
# Check the disk image we generate is there; if not generate it
if [[ ! -f "${SERIES_ROOTFS_FILE}" ]]; then
_info "Generating disk image for series '${VM_SERIES}'"
# Create a new rootfs file
truncate -s "2G" "$SERIES_ROOTFS_FILE"
# Create an ext4 filesystem from our rootfs file
mkfs.ext4 "$SERIES_ROOTFS_FILE" -L "cloudimg-rootfs" >/dev/null 2>&1
# Mount the new disk image to a temporary directory
tmpdir="$(mktemp -d)"
sudo mount "$SERIES_ROOTFS_FILE" -o loop "$tmpdir"
# Extract the dowloaded disk image into the new disk image
sudo tar -C "$tmpdir" -xf "${DOWNLOAD_DIR}/${CI_ROOTFS_FILE}"
# Creating this override file stops systemd-netword-wait-online from waiting for the metadata
# interface to be online, causing the boot to wait for long periods
sdnd_override_dir="${tmpdir}/etc/systemd/system/systemd-networkd-wait-online.service.d"
sudo mkdir -p "$sdnd_override_dir"
cat <<-EOF | sudo tee "$sdnd_override_dir/override.conf" >/dev/null
[Service]
ExecStart=
ExecStart=/usr/lib/systemd/systemd-networkd-wait-online --any
EOF
# Unmount and cleanup the tmpdir
sudo umount "$tmpdir"
rm -rf "$tmpdir"
else
_debug "File '${SERIES_ROOTFS_FILE}' already exists; skipping generation"
fi
# Extract the vmlinux from the kernel image
if [[ ! -f "${SERIES_KERNEL_FILE}" ]]; then
local extractor
_info "Extracting kernel image for series '${VM_SERIES}'"
if command -v extract-vmlinux &>/dev/null; then
extractor="extract-vmlinux"
else
tmpdir="$(mktemp -d)"
_debug "Downloading 'extract-vmlinux' script from Github"
url="https://raw.githubusercontent.com/torvalds/linux/master/scripts/extract-vmlinux"
_download "$url" "${tmpdir}/extract-vmlinux"
chmod +x "${tmpdir}/extract-vmlinux"
extractor="${tmpdir}/extract-vmlinux"
fi
bash "$extractor" "${DOWNLOAD_DIR}/${CI_KERNEL_FILE}" >"${SERIES_KERNEL_FILE}"
rm -rf "$tmpdir"
else
_debug "File '${SERIES_KERNEL_FILE}' already exists; skipping generation"
fi
# Copy the initrd into the series folder
if [[ ! -f "${SERIES_INITRD_FILE}" ]]; then
_info "Copying initrd file for '${VM_SERIES}'"
cp "${DOWNLOAD_DIR}/${CI_INITRD_FILE}" "${SERIES_INITRD_FILE}"
else
_debug "File '${SERIES_INITRD_FILE}' already exists; skipping copy"
fi
}
setup_network_bridge() {
local default_interface
# Get the device name of the default gateway on the host
default_interface="$(\ip route get 1.1.1.1 | grep uid | sed "s/.* dev \([^ ]*\) .*/\1/")"
# If there is no bridge interface, create one
if ! ip l | grep -q "$BRIDGE_IFACE"; then
# Create the interface, give it an address and bring it up
sudo ip link add name "$BRIDGE_IFACE" type bridge
sudo ip addr add 172.20.0.1/24 dev "$BRIDGE_IFACE"
sudo ip link set "$BRIDGE_IFACE" up
# Setup the iptables and packet forwarding rules
sudo sysctl -w net.ipv4.ip_forward=1 &>/dev/null
sudo iptables -t nat -A POSTROUTING -o "$default_interface" -j MASQUERADE
sudo iptables -I FORWARD -i "$BRIDGE_IFACE" -j ACCEPT
sudo iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
_info "Created bridge interface '${BRIDGE_IFACE}'"
else
_debug "Bridge interface '${BRIDGE_IFACE}' already exists"
fi
}
start_dnsmasq() {
local dnsmasq_dir dnsmasq_pid
dnsmasq_dir="${RUNTIME_DIR}/dnsmasq"
mkdir -p "${dnsmasq_dir}"
# Check if there is already a PID file for dnsmasq
if [[ -f "${dnsmasq_dir}/pid" ]]; then
dnsmasq_pid="$(cat "${dnsmasq_dir}/pid")"
# If the PID exists in /proc, assume dnsmasq is running okay and just return
if [[ -d "/proc/${dnsmasq_pid}" ]]; then
_info "Found existing dnsmasq process; PID: ${dnsmasq_pid}"
return
fi
fi
# Start dnsmasq for DHCP on the bridge
sudo dnsmasq \
--strict-order \
--bind-interfaces \
--log-facility="${dnsmasq_dir}/log" \
--pid-file="${dnsmasq_dir}/pid" \
--dhcp-leasefile="${dnsmasq_dir}/leases" \
--domain="firecracker" \
--local="/firecracker/" \
--except-interface="lo" \
--interface="$BRIDGE_IFACE" \
--listen-address="172.20.0.1" \
--dhcp-no-override \
--dhcp-authoritative \
--dhcp-range "172.20.0.2,172.20.0.100,infinite"
dnsmasq_pid="$(cat "${dnsmasq_dir}/pid")"
_info "Started dnsmasq; PID: ${dnsmasq_pid}; logs: '${dnsmasq_dir}/log'"
}
create_vm() {
mkdir -p "$VM_DIR"
if [[ ! -f "$VM_ROOTFS_FILE" ]]; then
_debug "Creating and resizing disk image '${VM_ROOTFS_FILE}' to '${VM_DISK}G'"
# If there is no vm directory, create one and move the built kernel image and rootfs
# into the directory before we try to boot it
# Copy the series rootfs into the VM directory
cp "$SERIES_ROOTFS_FILE" "$VM_ROOTFS_FILE"
# Resize image to specified size
truncate -s "${VM_DISK}G" "$VM_ROOTFS_FILE"
resize2fs "$VM_ROOTFS_FILE" >/dev/null 2>&1 || e2fsck -fpy "$VM_ROOTFS_FILE" >/dev/null 2>&1
else
_debug "VM disk image '${VM_ROOTFS_FILE}' already exists; skipping creation"
fi
# Create symlinks for the kernel and initrd files
if [[ ! -e "$VM_KERNEL_FILE" ]]; then
_debug "Symlinking kernel '${SERIES_KERNEL_FILE}' to '${VM_KERNEL_FILE}'"
ln -s "$SERIES_KERNEL_FILE" "$VM_KERNEL_FILE"
else
_debug "VM kernel symlink '${VM_KERNEL_FILE}' already exists; skipping creation"
fi
if [[ ! -e "$VM_INITRD_FILE" ]]; then
_debug "Symlinking initrd '${SERIES_INITRD_FILE}' to '${VM_INITRD_FILE}'"
ln -s "$SERIES_INITRD_FILE" "$VM_INITRD_FILE"
else
_debug "VM initrd symlink '${VM_INITRD_FILE}' already exists; skipping creation"
fi
# Generate a name for the tap interfaces
TAP_IFACE_MAIN="embrtap0$(openssl rand -hex 2)"
TAP_IFACE_META="embrtap0$(openssl rand -hex 2)"
# Create the main network interface for the VM
if ! ip l | grep -q "$TAP_IFACE_MAIN"; then
sudo ip tuntap add dev "$TAP_IFACE_MAIN" mode tap
TAP_IFACE_MAIN_MAC="$(cat "/sys/class/net/${TAP_IFACE_MAIN}/address")"
TAP_IFACE_MAIN_MAC_INT="$(_random_mac)"
_info "Created tap interface '${TAP_IFACE_MAIN}' with MAC '${TAP_IFACE_MAIN_MAC}'"
sudo ip link set "$TAP_IFACE_MAIN" up
_debug "Set interface '${TAP_IFACE_MAIN}' up"
sudo ip link set "$TAP_IFACE_MAIN" master "$BRIDGE_IFACE"
_info "Added tap interface '${TAP_IFACE_MAIN}' to bridge '${BRIDGE_IFACE}'"
fi
# Create a network interface for the MMDS
if ! ip l | grep -q "$TAP_IFACE_META"; then
sudo ip tuntap add dev "$TAP_IFACE_META" mode tap
TAP_IFACE_META_MAC="$(cat "/sys/class/net/${TAP_IFACE_META}/address")"
TAP_IFACE_META_MAC_INT="$(_random_mac)"
_info "Created tap interface '${TAP_IFACE_META}' with MAC '${TAP_IFACE_META_MAC}'"
sudo ip link set "$TAP_IFACE_META" up
_debug "Set interface '${TAP_IFACE_META}' up"
fi
cat <<-EOF | jq >"$VM_DIR/vm.json"
{
"name": "$VM_HOSTNAME",
"specs": {
"vcpu_count": $VM_CPUS,
"mem_size_mib": $((1024 * "$VM_MEMORY"))
},
"interfaces": [
{
"iface_id": "eth0",
"host_dev_name": "$TAP_IFACE_META",
"guest_mac": "$TAP_IFACE_META_MAC_INT"
},
{
"iface_id": "eth1",
"host_dev_name": "$TAP_IFACE_MAIN",
"guest_mac": "$TAP_IFACE_MAIN_MAC_INT"
}
],
"boot_sources": {
"kernel_image_path": "$VM_KERNEL_FILE",
"initrd_path": "$VM_INITRD_FILE"
},
"disks": {
"rootfs": {
"drive_id": "rootfs",
"path_on_host": "$VM_ROOTFS_FILE",
"is_root_device": true,
"is_read_only": false
}
}
}
EOF
_info "Created virtual machine"
_debug "Virtual machine config:\n$(jq <"${VM_DIR}/vm.json")"
}
start_firecracker() {
local pid
mkdir -p "${RUNTIME_VM_DIR}"
touch "$FIRECRACKER_LOG"
rm -f "$FIRECRACKER_SOCKET"
# Start firecracker
firecracker \
--api-sock "$FIRECRACKER_SOCKET" \
--log-path "$FIRECRACKER_LOG" \
--level "Debug" &>"$FIRECRACKER_CONSOLE_LOG" &
pid="$!"
echo "$pid" >"${FIRECRACKER_PID}"
# Wait for API server to start
while [[ ! -e "$FIRECRACKER_SOCKET" ]]; do sleep 0.1s; done
_info "Started firecracker; PID: ${pid}; logs: '${FIRECRACKER_LOG}'"
}
configure_vm() {
local vconf netconfig metadata cmdline data
vconf="$VM_DIR/vm.json"
# Setup the machine CPU/Memory
_firecracker_api_call PUT "machine-config" "$(jq .specs "$vconf")"
# Setup the root filesystem drive
_firecracker_api_call PUT "drives/rootfs" "$(jq .disks.rootfs "$vconf")"
# Setup the eth0 interface - this is for the MMDS
data="$(jq '.interfaces[] | select(.iface_id=="eth0")' "$vconf")"
_firecracker_api_call PUT "network-interfaces/eth0" "$data"
# Setup the eth1 interface - this will be the main network interface for the vm
data="$(jq '.interfaces[] | select(.iface_id=="eth1")' "$vconf")"
_firecracker_api_call PUT "network-interfaces/eth1" "$data"
# Set the interface for the MMDS
_firecracker_api_call PUT "mmds/config" '{"network_interfaces": ["eth0"]}'
# Configure the boot source
read -r -d '' netconfig <<-EOF || true
{
"version": 2,
"ethernets": {
"eth0": {
"match": {
"macaddress": "$(jq -r '.interfaces[]|select(.iface_id=="eth0")|.guest_mac' "$vconf")"
},
"addresses": ["169.254.0.1/16"]
},
"eth1": {
"match": {
"macaddress": "$(jq -r '.interfaces[]|select(.iface_id=="eth1")|.guest_mac' "$vconf")"
},
"dhcp4": true
}
}
}
EOF
cmdline="reboot=k panic=1 pci=off console=ttyS0"
# Add the nocloud datasource for cloud-init to the kernel command line
cmdline="${cmdline} ds=nocloud-net;s=http://169.254.169.254/latest/"
# Add the network-config to the kernel command line (gzipped and base64 encoded)
compressed_netconfig="$(echo "$netconfig" | yq . | gzip -c - | base64 -w0)"
cmdline="${cmdline} network-config=${compressed_netconfig}"
# Send the boot sources to the firecracker API
data="$(jq --arg c "$cmdline" '.boot_sources + {"boot_args": $c}' "$vconf")"
_firecracker_api_call PUT "boot-source" "$data"
# Set some metadata on the MMDS
read -r -d '' metadata <<-EOF || true
{
"local-hostname": "${VM_HOSTNAME}"
}
EOF
data="$(echo "$metadata" | yq . | jq --raw-input --slurp '{ "latest": { "meta-data": . }}')"
_firecracker_api_call PUT "mmds" "$data"
# If there is a provided userdata file, then use it; otherwise generate one
if [[ -f "$VM_USERDATA" ]]; then
data="$(jq --raw-input --slurp '{ "latest": { "user-data": . }}' <"$VM_USERDATA")"
_firecracker_api_call PATCH "mmds" "$data"
else
# Generate an ssh-key for use with the VM
ssh-keygen -t ed25519 -q -N "" -C "stoked" -f "${VM_DIR}/id_ed25519"
# Update the userdata template with the new key
userdata="${USERDATA_TEMPLATE//__KEY__/$(cat "${VM_DIR}/id_ed25519.pub")}"
userdata="$(echo -e "#cloud-config\n$(echo "$userdata" | yq .)")"
# Configure firecracker with the vendor data
data="$(jq --raw-input --slurp '{ "latest": { "user-data": . }}' <<<"$userdata")"
_firecracker_api_call PATCH "mmds" "$data"
fi
}
start_vm() {
_firecracker_api_call PUT "actions" "{\"action_type\": \"InstanceStart\"}"
_info "Started virtual machine"
_info "Waiting for virtual machine to get a DHCP lease"
while ! grep -q "$TAP_IFACE_MAIN_MAC_INT" "${RUNTIME_DIR}/dnsmasq/leases"; do sleep 1s; done
# Grab the IP that's assigned to MAC of the interface attached to this VM
VM_SSH_IP="$(grep "$TAP_IFACE_MAIN_MAC_INT" "${RUNTIME_DIR}/dnsmasq/leases" | cut -d' ' -f3)"
# Figure out the ssh user and key
# TODO(jnsgruk): make this a little less naive.
if [[ ! -f "${VM_USERDATA}" ]]; then
# If there is no user data file, then fallback to the defaults
VM_SSH_USER="ubuntu"
VM_SSH_KEY="${VM_DIR}/id_ed25519"
else
# Query the user data from the MMDS to get the first specified user
userdata="$(_firecracker_api_call GET "mmds" | jq -r '.latest."user-data"')"
if echo "$userdata" | grep -q "users:"; then
VM_SSH_USER="$(echo "$userdata" | yq '.users[0].name')"
fi
fi
# Build a connection command from the info we know about the VM config
connect_cmd="ssh "
[[ -n "${VM_SSH_KEY:-}" ]] && connect_cmd="${connect_cmd}-i ${VM_SSH_KEY} "
[[ -n "${VM_SSH_USER:-}" ]] && connect_cmd="${connect_cmd}${VM_SSH_USER}@"
connect_cmd="${connect_cmd}${VM_SSH_IP}"
_info "Waiting for SSH server to become available"
while ! nc -w1 "${VM_SSH_IP}" 22 &>/dev/null; do sleep 1s; done
_info "Connect to virtual machine with: '${connect_cmd}'"
}
main() {
# Directories for the operation of this script
mkdir -p "$EMBR_DIR"
SERIES_DIR="${EMBR_DIR}/images/${VM_SERIES}"
DOWNLOAD_DIR="${SERIES_DIR}/downloads"
RUNTIME_VM_DIR="${RUNTIME_DIR}/${VM_HOSTNAME}"
VM_DIR="${EMBR_DIR}/vm/${VM_HOSTNAME}"
# Filenames for cloud image artefacts
CI_ROOTFS_FILE="${VM_SERIES}-server-cloudimg-amd64-root.tar.xz"
CI_KERNEL_FILE="${VM_SERIES}-server-cloudimg-amd64-vmlinuz-generic"
CI_INITRD_FILE="${VM_SERIES}-server-cloudimg-amd64-initrd-generic"
# Filenames for other artefacts
SERIES_ROOTFS_FILE="${SERIES_DIR}/rootfs.${VM_SERIES}"
SERIES_KERNEL_FILE="${SERIES_DIR}/kernel.${VM_SERIES}"
SERIES_INITRD_FILE="${SERIES_DIR}/initrd.${VM_SERIES}"
# Filenames for VM artefacts
VM_ROOTFS_FILE="${VM_DIR}/disk.ext4"
VM_KERNEL_FILE="${VM_DIR}/vmlinux"
VM_INITRD_FILE="${VM_DIR}/initrd"
# Name of the bridge interface on the host
BRIDGE_IFACE="embr0"
# Network interfaces for VM
TAP_IFACE_MAIN=""
TAP_IFACE_META=""
# MAC addresses of tap interfaces on host
TAP_IFACE_META_MAC=""
TAP_IFACE_MAIN_MAC=""
# MAC addresses of interfaces on the guest
TAP_IFACE_META_MAC_INT=""
TAP_IFACE_MAIN_MAC_INT=""
# Filenames for firecracker
FIRECRACKER_SOCKET="${RUNTIME_VM_DIR}/firecracker.socket"
FIRECRACKER_LOG="${RUNTIME_VM_DIR}/firecracker.log"
FIRECRACKER_CONSOLE_LOG="${RUNTIME_VM_DIR}/firecracker.console.log"
FIRECRACKER_PID="${RUNTIME_VM_DIR}/firecracker.pid"
check_dependencies
fetch_cloud_image_artefacts
process_cloud_image_artefacts
setup_network_bridge
start_dnsmasq
create_vm
start_firecracker
configure_vm
start_vm
}
usage() {
cat <<EOF
embr is a tool for creating and launching Ubuntu virtual machines with Firecracker.
USAGE:
embr <SUBCOMMAND> [OPTIONS]
SUBCOMMANDS:
launch
Launches a new or existing firecracker virtual machine
clean
Kills processes, removes files and removes network interfaces created by embr.
EOF
}
usage_launch() {
cat <<EOF
embr is a tool for creating and launching Ubuntu virtual machines with Firecracker.
USAGE:
embr launch [OPTIONS]
OPTIONS:
-n, --name <name>
Hostname of the virtual machine to create.
Default: dev
-c, --cpus <cpus>
Number of virtual CPUs to assign to the VM
Default: 8
-m, --memory <mem>
Amount of memory in GB to assign to the VM.
Default: 16
-d, --disk <disk>
Size of disk for the VM in GB.
Default: 20
-f, --cloud-init <file>
Filename of the cloud-init user data file to use for provisioning.
Default: userdata.yaml
-s, --series <series>
The Ubuntu series codename to use. E.g. xenial, bionic, focal, jammy
Default: jammy
-h, --help
Display this help message.
EOF
}
usage_clean() {
cat <<EOF
embr is a tool for creating and launching Ubuntu virtual machines with Firecracker.
USAGE:
embr clean [OPTIONS]
OPTIONS:
-p, --purge
Run usual cleanup, but also delete any downloaded cloud images, kernels, etc.
-h, --help
Display this help message.
EOF
}
entrypoint() {
local subcommand
subcommand="${1:-}"
if [[ ! "$subcommand" =~ "launch"|"clean" ]]; then usage; fi
if [[ "$subcommand" == "launch" ]]; then
if ! VALID_ARGS=$(getopt -o n:c:m:d:f:s:h --long name:,cpus:,memory:,disk:,cloud-init:,series:,help -- "$@"); then
_error "Could not parse arguments!"
usage_launch
fi
eval set -- "$VALID_ARGS"
while true; do
case "$1" in
-n | --name)
export VM_HOSTNAME="$2"
shift 2
;;
-c | --cpus)
export VM_CPUS="$2"
shift 2
;;
-m | --memory)
export VM_MEMORY="$2"
shift 2
;;
-d | --disk)
export VM_DISK="$2"
shift 2
;;
-f | --cloud-init)
export VM_USERDATA="$2"
shift 2
;;
-s | --series)
export VM_SERIES="$2"
shift 2
;;
-h | --help)
usage_launch
exit 0
;;
--)
shift
break
;;
esac
done
main
elif [[ "$subcommand" == "clean" ]]; then
if ! VALID_ARGS=$(getopt -o ph --long purge,help -- "$@"); then
_error "Could not parse arguments!"
usage_clean
fi
eval set -- "$VALID_ARGS"
while true; do
case "$1" in
-p | --purge)
export PURGE=1
shift
;;
-h | --help)
usage_clean
exit 0
;;
--)
shift
break
;;
esac
done
cleanup
fi
}
entrypoint "$@"