Debian Codegraph @

templates/lxc-alpine.in

raw
1 #!/bin/sh
2 # vim: set ts=4:
3
4 # Exit on error and treat unset variables as an error.
5 set -eu
6
7 #
8 # LXC template for Alpine Linux 3+
9 #
10
11 # Note: Do not replace tabs with spaces, it would break heredocs!
12
13 # Authors:
14 # Jakub Jirutka <[email protected]>
15
16 # This library is free software; you can redistribute it and/or
17 # modify it under the terms of the GNU Lesser General Public
18 # License as published by the Free Software Foundation; either
19 # version 2.1 of the License, or (at your option) any later version.
20 #
21 # This library is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 # Lesser General Public License for more details.
25 #
26 # You should have received a copy of the GNU Lesser General Public
27 # License along with this library; if not, write to the Free Software
28 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29
30
31 #=========================== Constants ============================#
32
33 # Make sure the usual locations are in PATH
34 export PATH=$PATH:/usr/sbin:/usr/bin:/sbin:/bin
35
36 readonly LOCAL_STATE_DIR='@LOCALSTATEDIR@'
37 readonly LXC_TEMPLATE_CONFIG='@LXCTEMPLATECONFIG@'
38 readonly LXC_CACHE_DIR="${LXC_CACHE_PATH:-"$LOCAL_STATE_DIR/cache/lxc"}/alpine"
39
40 # SHA256 checksums of GPG keys for APK.
41 readonly APK_KEYS_SHA256="\
42 9c102bcc376af1498d549b77bdbfa815ae86faa1d2d82f040e616b18ef2df2d4 [email protected]
43 ebf31683b56410ecc4c00acd9f6e2839e237a3b62b5ae7ef686705c7ba0396a9 [email protected]
44 1bb2a846c0ea4ca9d0e7862f970863857fc33c32f5506098c636a62a726a847b [email protected]
45 12f899e55a7691225603d6fb3324940fc51cd7f133e7ead788663c2b7eecb00c [email protected]
46 73867d92083f2f8ab899a26ccda7ef63dfaa0032a938620eda605558958a8041 [email protected]
47 9a4cd858d9710963848e6d5f555325dc199d1c952b01cf6e64da2c15deedbd97 [email protected]
48 780b3ed41786772cbc7b68136546fa3f897f28a23b30c72dde6225319c44cfff [email protected]
49 59c01c57b446633249f67c04b115dd6787f4378f183dff2bbf65406df93f176d [email protected]
50 db0b49163f07ffba64a5ca198bcf1688610b0bd1f0d8d5afeaf78559d73f2278 [email protected]
51 207e4696d3c05f7cb05966aee557307151f1f00217af4143c1bcaf33b8df733f [email protected]
52 128d34d4aec39b0daedea8163cd8dc24dff36fd3d848630ab97eeb1d3084bbb3 [email protected]
53 10877cce0a935e46ad88cb79e174a2491680508eccda08e92bf04fb9bf37fbc1 [email protected]
54 4a095a9daca86da496a3cd9adcd95ee2197fdbeb84638656d469f05a4d740751 [email protected]
55 0caf5662fde45616d88cfd7021b7bda269a2fcaf311e51c48945a967a609ec0b [email protected]
56 ebe717d228555aa58133c202314a451f81e71f174781fd7ff8d8970d6cfa60da [email protected]
57 d11f6b21c61b4274e182eb888883a8ba8acdbf820dcc7a6d82a7d9fc2fd2836d [email protected]
58 40a216cbd163f22e5f16a9e0929de7cde221b9cbae8e36aa368b1e128afe0a31 [email protected]"
59
60 readonly APK_KEYS_URI='https://git.alpinelinux.org/aports/plain/main/alpine-keys/'
61 readonly DEFAULT_MIRROR_URL='http://dl-cdn.alpinelinux.org/alpine'
62
63 : ${APK_KEYS_DIR:=/etc/apk/keys}
64 if ! ls "$APK_KEYS_DIR"/alpine* >/dev/null 2>&1; then
65 APK_KEYS_DIR="$LXC_CACHE_DIR/bootstrap/keys"
66 fi
67 readonly APK_KEYS_DIR
68
69 : ${APK:=$(command -v apk || true)}
70 if [ ! -x "$APK" ]; then
71 APK="$LXC_CACHE_DIR/bootstrap/sbin/apk.static"
72 fi
73 readonly APK
74
75
76 #======================== Helper Functions ========================#
77
78 usage() {
79 cat <<-EOF
80 Template specific options can be passed to lxc-create after a '--' like this:
81
82 lxc-create --name=NAME [lxc-create-options] -- [template-options] [PKG...]
83
84 PKG Additional APK package(s) to install into the container.
85
86 Template options:
87 -a ARCH, --arch=ARCH The container architecture (e.g. x86, x86_64); defaults
88 to the host arch.
89 -d, --debug Run this script in a debug mode (set -x and wget w/o -q).
90 -F, --flush-cache Remove cached files before build.
91 -m URL --mirror=URL The Alpine mirror to use; defaults to $DEFAULT_MIRROR_URL.
92 -r VER, --release=VER The Alpine release branch to install; default is the
93 latest stable.
94
95 Environment variables:
96 APK The apk-tools binary to use when building rootfs. If not set
97 or not executable and apk is not on PATH, then the script
98 will download the latest apk-tools-static.
99 APK_KEYS_DIR Path to directory with GPG keys for APK. If not set and
100 /etc/apk/keys does not contain alpine keys, then the script
101 will download the keys from ${APK_KEYS_URI}.
102 LXC_CACHE_PATH Path to the cache directory where to store bootstrap files
103 and APK packages.
104 EOF
105 }
106
107 die() {
108 local retval=$1; shift
109
110 printf 'ERROR: %s\n' "$@" 1>&2
111 exit $retval
112 }
113
114 einfo() {
115 printf "\n==> $1\n"
116 }
117
118 fetch() {
119 if [ "$DEBUG" = 'yes' ]; then
120 wget -T 10 -O - $@
121 else
122 wget -T 10 -O - -q $@
123 fi
124 }
125
126 latest_release_branch() {
127 local arch="$1"
128 local branch=$(fetch "$MIRROR_URL/latest-stable/releases/$arch/latest-releases.yaml" \
129 | sed -En 's/^[ \t]*branch: (.*)$/\1/p' \
130 | head -n 1)
131 [ -n "$branch" ] && echo "$branch"
132 }
133
134 parse_arch() {
135 case "$1" in
136 x86 | i[3-6]86) echo 'x86';;
137 x86_64 | amd64) echo 'x86_64';;
138 aarch64 | arm64) echo 'aarch64';;
139 armv7) echo 'armv7';;
140 arm*) echo 'armhf';;
141 ppc64le) echo 'ppc64le';;
142 *) return 1;;
143 esac
144 }
145
146 run_exclusively() {
147 local lock_name="$1"
148 local timeout=$2
149 shift 2
150
151 mkdir -p "$LOCAL_STATE_DIR/lock/subsys"
152
153 local retval
154 {
155 echo -n "Obtaining an exclusive lock..."
156 if ! flock -x 9; then
157 echo ' failed.'
158 return 1
159 fi
160 echo ' done'
161
162 "$@"; retval=$?
163 } 9> "$LOCAL_STATE_DIR/lock/subsys/lxc-alpine-$lock_name"
164
165 return $retval
166 }
167
168
169 #============================ Bootstrap ===========================#
170
171 bootstrap() {
172 if [ "$FLUSH_CACHE" = 'yes' ] && [ -d "$LXC_CACHE_DIR/bootstrap" ]; then
173 einfo 'Cleaning cached bootstrap files'
174 rm -Rf "$LXC_CACHE_DIR/bootstrap"
175 fi
176
177 einfo 'Fetching and/or verifying APK keys'
178 fetch_apk_keys "$APK_KEYS_DIR"
179
180 if [ ! -x "$APK" ]; then
181 einfo 'Fetching apk-tools static binary'
182
183 local host_arch=$(parse_arch $(uname -m))
184 fetch_apk_static "$LXC_CACHE_DIR/bootstrap" "$host_arch"
185 fi
186 }
187
188 fetch_apk_keys() {
189 local dest="$1"
190 local line keyname
191
192 mkdir -p "$dest"
193 cd "$dest"
194
195 echo "$APK_KEYS_SHA256" | while read -r line; do
196 keyname="${line##* }"
197 if [ ! -s "$keyname" ]; then
198 fetch "$APK_KEYS_URI/$keyname" > "$keyname"
199 fi
200 echo "$line" | sha256sum -c -
201 done || exit 2
202
203 cd - >/dev/null
204 }
205
206 find_keyfile() {
207 ls -1 "$1".alpine-*.pub 2>/dev/null | head -n 1
208 }
209
210 fetch_apk_static() {
211 local dest="$1"
212 local arch="$2"
213 local pkg_name='apk-tools-static'
214
215 mkdir -p "$dest"
216
217 local pkg_ver=$(fetch "$MIRROR_URL/latest-stable/main/$arch/APKINDEX.tar.gz" \
218 | tar -xzO APKINDEX \
219 | sed -n "/P:${pkg_name}/,/^$/ s/V:\(.*\)$/\1/p")
220
221 [ -n "$pkg_ver" ] || die 2 "Cannot find a version of $pkg_name in APKINDEX"
222
223 fetch "$MIRROR_URL/latest-stable/main/$arch/${pkg_name}-${pkg_ver}.apk" \
224 | tar -xz -C "$dest" sbin/ # --extract --gzip --directory
225
226 local apk=$dest/sbin/apk.static
227 [ -s "$apk" ] || die 2 'apk.static not found'
228
229 local sigprefix=$apk.SIGN.RSA.sha256
230 local algorithm=sha256
231 if ! [ -s "$(find_keyfile "$sigprefix")" ]; then
232 sigprefix=${sigprefix%.*}
233 algorithm=sha1
234 fi
235 local keyfile=$(find_keyfile "$sigprefix")
236 if ! openssl dgst -$algorithm \
237 -verify "$APK_KEYS_DIR/${keyfile#$sigprefix.}" \
238 -signature "$keyfile" \
239 "$apk"; then
240
241 rm -f "$apk"
242 die 2 'Signature verification for apk.static failed'
243 fi
244
245 # Note: apk doesn't return 0 for --version
246 local out=$("$apk" --version)
247 echo "$out"
248
249 [ "${out%% *}" = 'apk-tools' ] || die 3 'apk.static --version failed'
250 }
251
252
253 #============================ Install ============================#
254
255 install() {
256 local dest="$1"
257 local arch="$2"
258 local branch="$3"
259 local extra_packages="$4"
260 local apk_cache="$LXC_CACHE_DIR/apk/$arch"
261
262 if [ "$FLUSH_CACHE" = 'yes' ] && [ -d "$apk_cache" ]; then
263 einfo "Cleaning cached APK packages for $arch"
264 rm -Rf "$apk_cache"
265 fi
266 mkdir -p "$apk_cache"
267
268 einfo "Installing Alpine Linux in $dest"
269 cd "$dest"
270
271 mkdir -p etc/apk
272 ln -s "$apk_cache" etc/apk/cache
273
274 local repo; for repo in main community; do
275 echo "$MIRROR_URL/$branch/$repo" >> etc/apk/repositories
276 done
277
278 install_packages "$arch" "alpine-base $extra_packages"
279 make_dev_nodes
280 setup_inittab
281 setup_hosts
282 setup_network
283 setup_services
284
285 chroot . /bin/true \
286 || die 3 'Failed to execute /bin/true in chroot, the builded rootfs is broken!'
287
288 rm etc/apk/cache
289 cd - >/dev/null
290 }
291
292 install_packages() {
293 local arch="$1"
294 local packages="$2"
295
296 $APK --arch="$arch" --root=. --keys-dir="$APK_KEYS_DIR" \
297 --update-cache --initdb add $packages
298 }
299
300 make_dev_nodes() {
301 mkdir -p -m 755 dev/pts
302 mkdir -p -m 1777 dev/shm
303
304 local i; for i in $(seq 0 4); do
305 mknod -m 620 dev/tty$i c 4 $i
306 chown 0:5 dev/tty$i # root:tty
307 done
308
309 mknod -m 666 dev/tty c 5 0
310 chown 0:5 dev/tty # root:tty
311 mknod -m 666 dev/ptmx c 5 2
312 chown 0:5 dev/ptmx # root:tty
313 }
314
315 setup_inittab() {
316 # Remove unwanted ttys.
317 sed -i '/^tty[5-9]\:\:.*$/d' etc/inittab
318
319 cat <<-EOF >> etc/inittab
320 # Main LXC console console
321 ::respawn:/sbin/getty 38400 console
322 EOF
323 }
324
325 setup_hosts() {
326 # This runscript injects localhost entries with the current hostname
327 # into /etc/hosts.
328 cat <<'EOF' > etc/init.d/hosts
329 #!/sbin/openrc-run
330
331 start() {
332 local start_tag='# begin generated'
333 local end_tag='# end generated'
334
335 local content=$(
336 cat <<-EOF
337 $start_tag by /etc/init.d/hosts
338 127.0.0.1 $(hostname).local $(hostname) localhost
339 ::1 $(hostname).local $(hostname) localhost
340 $end_tag
341 EOF
342 )
343
344 if grep -q "^${start_tag}" /etc/hosts; then
345 # escape \n, busybox sed doesn't like them
346 content=${content//$'\n'/\\$'\n'}
347
348 sed -ni "/^${start_tag}/ {
349 a\\${content}
350 # read and discard next line and repeat until $end_tag or EOF
351 :a; n; /^${end_tag}/!ba; n
352 }; p" /etc/hosts
353 else
354 printf "$content" >> /etc/hosts
355 fi
356 }
357 EOF
358 chmod +x etc/init.d/hosts
359
360 # Wipe it, will be generated by the above runscript.
361 echo -n > etc/hosts
362 }
363
364 setup_network() {
365 # Note: loopback is automatically started by LXC.
366 cat <<-EOF > etc/network/interfaces
367 auto eth0
368 iface eth0 inet dhcp
369 hostname \$(hostname)
370 EOF
371 }
372
373 setup_services() {
374 local svc_name
375
376 # Specify the LXC subsystem.
377 sed -i 's/^#*rc_sys=.*/rc_sys="lxc"/' etc/rc.conf
378
379 # boot runlevel
380 for svc_name in bootmisc hosts syslog; do
381 ln -s /etc/init.d/$svc_name etc/runlevels/boot/$svc_name
382 done
383
384 # default runlevel
385 for svc_name in networking cron crond; do
386 # issue 1164: alpine renamed cron to crond
387 # Use the one that exists.
388 if [ -e etc/init.d/$svc_name ]; then
389 ln -s /etc/init.d/$svc_name etc/runlevels/default/$svc_name
390 fi
391 done
392 }
393
394
395 #=========================== Configure ===========================#
396
397 configure_container() {
398 local config="$1"
399 local hostname="$2"
400 local arch="$3"
401
402 cat <<-EOF >> "$config"
403
404 # Specify container architecture.
405 lxc.arch = $arch
406
407 # Set hostname.
408 lxc.uts.name = $hostname
409
410 # If something doesn't work, try to comment this out.
411 # Dropping sys_admin disables container root from doing a lot of things
412 # that could be bad like re-mounting lxc fstab entries rw for example,
413 # but also disables some useful things like being able to nfs mount, and
414 # things that are already namespaced with ns_capable() kernel checks, like
415 # hostname(1).
416 lxc.cap.drop = sys_admin
417
418 # Comment this out if you have to debug processes by tracing.
419 lxc.cap.drop = sys_ptrace
420
421 # Comment this out if required by your applications.
422 lxc.cap.drop = setpcap
423
424 # Include common configuration.
425 lxc.include = $LXC_TEMPLATE_CONFIG/alpine.common.conf
426 EOF
427 }
428
429
430 #============================= Main ==============================#
431
432 if [ "$(id -u)" != "0" ]; then
433 die 1 "This script must be run as 'root'"
434 fi
435
436 # Parse command options.
437 options=$(getopt -o a:dFm:n:p:r:h -l arch:,debug,flush-cache,mirror:,name:,\
438 path:,release:,rootfs:,help,mapped-uid:,mapped-gid: -- "$@")
439 eval set -- "$options"
440
441 # Clean variables and set defaults.
442 arch="$(uname -m)"
443 debug='no'
444 flush_cache='no'
445 mirror_url=
446 name=
447 path=
448 release=
449 rootfs=
450
451 # Process command options.
452 while [ $# -gt 0 ]; do
453 case $1 in
454 -a | --arch)
455 arch=$2; shift 2
456 ;;
457 -d | --debug)
458 debug='yes'; shift 1
459 ;;
460 -F | --flush-cache)
461 flush_cache='yes'; shift 1
462 ;;
463 -m | --mirror)
464 mirror_url=$2; shift 2
465 ;;
466 -n | --name)
467 name=$2; shift 2
468 ;;
469 -p | --path)
470 path=$2; shift 2
471 ;;
472 -r | --release)
473 release=$2; shift 2
474 ;;
475 --rootfs)
476 rootfs=$2; shift 2
477 ;;
478 -h | --help)
479 usage; exit 0
480 ;;
481 --)
482 shift; break
483 ;;
484 --mapped-[ug]id)
485 die 1 "This template can't be used for unprivileged containers." \
486 'You may want to try the "download" template instead.'
487 ;;
488 *)
489 echo "Unknown option: $1" 1>&2
490 usage; exit 1
491 ;;
492 esac
493 done
494
495 extra_packages="$@"
496
497 [ "$debug" = 'yes' ] && set -x
498
499 # Set global variables.
500 readonly DEBUG="$debug"
501 readonly FLUSH_CACHE="$flush_cache"
502 readonly MIRROR_URL="${mirror_url:-$DEFAULT_MIRROR_URL}"
503
504 # Validate options.
505 [ -n "$name" ] || die 1 'Missing required option --name'
506 [ -n "$path" ] || die 1 'Missing required option --path'
507
508 if [ -z "$rootfs" ] && [ -f "$path/config" ]; then
509 rootfs="$(sed -nE 's/^lxc.rootfs.path\s*=\s*(.*)$/\1/p' "$path/config")"
510 fi
511 if [ -z "$rootfs" ]; then
512 rootfs="$path/rootfs"
513 fi
514
515 arch=$(parse_arch "$arch") \
516 || die 1 "Unsupported architecture: $arch"
517
518 if [ -z "$release" ]; then
519 release=$(latest_release_branch "$arch") \
520 || die 2 'Failed to resolve Alpine last release branch'
521 fi
522
523 # Here we go!
524 run_exclusively 'bootstrap' 10 bootstrap
525 run_exclusively "$arch" 30 install "$rootfs" "$arch" "$release" "$extra_packages"
526 configure_container "$path/config" "$name" "$arch"
527
528 einfo "Container's rootfs and config have been created"
529 cat <<-EOF
530 Edit the config file $path/config to check/enable networking setup.
531 The installed system is preconfigured for a loopback and single network
532 interface configured via DHCP.
533
534 To start the container, run "lxc-start -n $name".
535 The root password is not set; to enter the container run "lxc-attach -n $name".
536 EOF