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