summaryrefslogtreecommitdiff
path: root/bin/vm
blob: 35a107e742c84c247a2fc4690c3419e48d6a0858 (plain)
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
#!/bin/sh

# Manage virtual machines
#
# Prereq:
#  - curl
#  - cdrtools (isoinfo)
#  - expect
#  - qemu
#  - screen
#
# TODO:
#  - extract bzImage and initrd.gz with isoinfo
#  - ssh scripts to finish install (once ssh is ready)
#
# DONE:
#  - setup vde and networking
#  - setup ssh keys so it is possible to ssh in vm from host
#
unset CDPATH
export LC_ALL=C IFS=' 	
'

version='vm-0.1'

arch=$(uname -m)
sys=$(uname -s)
alpine_version='3.15.0'
pubkey=$HOME/.ssh/id_rsa.pub
dir="${VM_DIR:-$HOME/.vm}"

console() {
	usage 'console name' 'Attach a console to a virtual machine' && return
	[ "$1" ] || die "missing argument"
	is_running "$1" && screen -r "vm!$1!"
}

create_arch() {
	usage 'create_arch [-s size] name' 'Create an archlinux disk image' && return
	size=8g
	while getopts :s: opt; do
		case $opt in
		s) size=$OPTARG ;;
		*) Opth=2 create_arch; return ;;
		esac
	done
	shift $((OPTIND - 1))
	[ -d "$dir/$1" ] && die "create failed: $dir/$1 already exists"
	mkdir "$dir/$1"
	cd "$dir/$1" || die "create failed: invalid directory $dir/$1"
	qemu-img create "$1.raw" "$size" || die "create failed"
	mac=$(new_macaddr)
	ip=$(new_ip)
	hdd="$1.raw"
	echo "hdd=$hdd
mac=$mac
ip=$ip" >> config

	mkfs.ext4 "$1.raw"
	mkdir -p mnt
	sudo mount "$1.raw" mnt
	sudo pacstrap mnt base base-devel
	sudo umount mnt
}

create() {
	usage 'create [-s size] name' 'Create an alpinelinux disk image' && return
	size=8g
	while getopts :s: opt; do
		case $opt in
		s) size=$OPTARG ;;
		*) Opth=2 create_arch; return ;;
		esac
	done
	shift $((OPTIND - 1))
	[ -d "$dir/$1" ] && die "create failed: $dir/$1 already exists"
	mkdir "$dir/$1"
	cd "$dir/$1" || die "create failed: invalid directory $dir/$1"
	qemu-img create "$1.raw" "$size" || die "create failed"
	mac=$(new_macaddr)
	ip=$(new_ip)
	hdd="$1.raw"
	echo "hdd=$hdd
mac=$mac
ip=$ip" >> config

	# Before install do not use virtio, as devices may not recognized as bootable
	# TODO: alternate way: extract kernel and initrd files and pass them directly to qemu
	screen -S "vm!$1!" -d -m qemu-system-$arch -nographic \
		-cdrom ../alpine-iso/alpine-virt-$alpine_version-$arch.iso \
		-hdd "$hdd" -net nic,macaddr=$mac -net vde
	setup_alpine "$1"
	post_setup_alpine "$1"
}

die() { [ "$1" ] && echo "$0: $*" >&2; exit 1; }

help() {
	usage 'help' 'Print this help text' && return
        printf "$version\n  Manage virtual machines\n\nUsage: vm command [options] [args]\n"
        Opth=1; for c in $Cmdlist; do $c; done
}

init() {
	mkdir -p "$dir"
}

init_alpine_iso() {
	usage init_alpine_iso '' && return
	mkdir -p "$dir/alpine-iso"
	iso_url="https://dl-cdn.alpinelinux.org/alpine/v${alpine_version%.*}/releases/$arch"
	iso="alpine-virt-$alpine_version-$arch.iso"
	cd "$dir/alpine-iso" 
	[ -f "$iso" ] || curl -LO "$iso_url/$iso" || rm -f "$iso"
	echo "iso=$iso
" > config
	echo 10 > ../index
}

is_running() { screen -ls "vm!$1!" >/dev/null 2>&1; }

ls() {
	usage 'ls' 'list virtual machines' && return
	init && cd "$dir" || die "could not change dir to $dir"
	for i in */; do
		i=${i%/}
		[ "$i" = '*' ] && continue
		is_running "$i" && state=active || state=stopped
		printf "%-20s %s\n" "$i" "$state"
	done
}

new_ip() {
	read index < $dir/index
	index=$((index + 1))
	echo "$index" > $dir/index
	echo "10.0.2.$index/24"
}

new_macaddr() { printf 'de:ad:be:ef:%02x:%02x\n' $((RANDOM % 256)) $((RANDOM % 256)); }

pidof() {
	usage 'pidof name' 'print the PID of a virtual machine' && return
	p=$(screen -ls "vm!$1!" | awk 'NR==2 {print substr($1, 1, index($1, ".")-1)}')
	[ "$p" ] && pgrep -P $p
}

post_setup_alpine() {
	start "$1"
	read proto key id < "$pubkey"
	# echo '
	expect -c '
		set timeout -1
		spawn screen -x "vm!'$1'!"
		expect {
			" login: " { send "root\r"; exp_continue }
			"Password: " { send "root\r"; exp_continue }
			":~# "
		}
		send "mkdir -pm 0700 .ssh\r"
		expect ":~# "
		send "echo '$proto' '$key' '$id' >.ssh/authorized_keys\r"
		expect ":~# "
		send "exit\r"
	'
}

# setup_alpine automates alpine installation from iso to image.
# When done, base image system is ready, with storage and network up.
# No user nor ssh access configured yet.
# TODO: custom network (in case of no dhcp).
setup_alpine() {
	usage 'setup_alpine' && return
	expect -c '
		set timeout -1
		spawn screen -x "vm!'$1'!"
		expect {
			"localhost login: "                     { send "root\r"; exp_continue }
			"localhost:~# "                         { send "SWAP_SIZE=0 setup-alpine\r"; exp_continue }
			"Select keyboard layout: "              { send "\r"; exp_continue }
			"Enter system hostname"                 { send "'$1'\r"; exp_continue }
			"Which one do you want to initialize?"  { send "\r"; exp_continue }
			"Ip address for eth0?"                  { send "'$ip'\r"; exp_continue }
			"Gateway?"                              { send "10.0.2.2\r"; exp_continue }
			"manual network configuration?"         { send "\r"; exp_continue }
			"DNS domain name?"                      { send "lan\r"; exp_continue }
			"DNS nameserver(s)?"                    { send "10.0.2.2 1.1.1.1\r"; exp_continue }
			"New password:"                         { send "root\r"; exp_continue }
			"Retype password:"                      { send "root\r"; exp_continue }
			"Which timezone are you in?"            { send "\r"; exp_continue }
			"HTTP/FTP proxy URL?"                   { send "\r"; exp_continue }
			"Enter mirror number "                  { send "\r"; exp_continue }
			"Which SSH server?"                     { send "\r"; exp_continue }
			"Which disk(s) would you like to use?"  { send "sda\r"; exp_continue }
			"How would you like to use it?"         { send "sys\r"; exp_continue }
			"Erase the above disk(s) and continue?" { send "y\r"; exp_continue }
			"Installation is complete"              { send "poweroff\r" }
		}
		interact
	'
}

start_vde() {
	usage start_vde && return
	sudo sh <<- EOT
		vde_switch -tap tap0 -sock /tmp/vde.ctl -daemon -mod 666
		sleep 1
		ip address add 10.0.2.2/24 dev tap0
		ip link set tap0 up
		echo 1 > /proc/sys/net/ipv4/ip_forward
		iptables -t nat -A POSTROUTING -s 10.0.2.0/24 -o eth0 -j MASQUERADE
		iptables -t nat -A POSTROUTING -s 10.0.2.0/24 -o wlan0 -j MASQUERADE
	EOT
	#slirpvde --dhcp --daemon
}

stop_vde() {
	# killall slirpvde
	sudo sh <<- EOT
		iptables -t nat -D POSTROUTING -s 10.0.2.0/24 -o eth0 -j MASQUERADE
		iptables -t nat -D POSTROUTING -s 10.0.2.0/24 -o wlan0 -j MASQUERADE
		ip link set tap0 down
		killall vde_switch
	EOT
}

start() {
	usage 'start [-acd] name' 'start a virtual machine' && return
	while getopts :acd opt; do
		case $opt in
		a) opta=1 ;;
		c) boot=c ;;
		d) boot=d ;;
		esac
	done
	shift $((OPTIND -1))
	[ "$1" ] || die 'start failed: name missing'
	cd "$dir/$1" || die "start failed: invalid directory $dir/$1"
	is_running "$1" || start_qemu "$1"
	[ "$opta" ] && console "$1"
}

start_qemu() (
	opt='-nographic -cpu max'
	[ "$sys" = Linux ] && opt="$opt -enable-kvm"
	. ./config || die "could not source $PWD/config"
	exec 1>>qemu.log 2>&1
	date +%F_%T
	set -x
	screen -S "vm!$1!" -d -m qemu-system-$arch $opt \
		${smp+-smp $smp} \
		${ram+-m $ram} \
		${mac+-net nic,macaddr=$mac,model=virtio-net-pci} -net vde \
		${hdd+-drive file="$hdd",if=virtio,media=disk,format=raw} \
		${iso+-drive file="$iso",if=virtio,media=cdrom,format=raw} \
		${boot+-boot $boot}
)

stop() {
	usage 'stop name' 'stop a virtual machine' && return
	is_running "$1" && kill "$(pidof "$1")"
}

usage() {
	case $Opth in
	1) printf " %-34s %s\n" "$1" "$2" ;;
	2) printf "$0 $1\n\t$2\n" ;;
	*) return 1 ;;
	esac
}

version() {
	usage 'version' 'Print version' && return
	echo "$version"
}

Cmdlist='console create help init_alpine_iso ls pidof setup_alpine start start_vde stop version'
[ "$1" ] && C=$1 && shift 1 || { help; exit 1; }
#for c in $Cmdlist; do
#	case $c in
#	("$C")  cmd=$c; break ;;
#	("$C"*) [ "$cmd" ] && die "ambiguous command $C" || cmd=$c ;;
#	esac
#done
cmd=$C
[ "$cmd" ] || { help; exit 1; } && $cmd "$@"