Debian Codegraph @

bin/mount-image-callback

raw
1 #!/bin/bash
2
3 VERBOSITY=0
4 TEMP_D=""
5 UMOUNTS=( )
6 QEMU_DISCONNECT=""
7 CR=$'\n'
8 TAB=$'\t'
9
10 error() { echo "$@" 1>&2; }
11
12 Usage() {
13 cat <<EOF
14 Usage: ${0##*/} [ options ] file cmd [ args ]
15
16 mount a file to a temporary mount point and then
17 invoke the provided cmd with args
18
19 supported 'file' are:
20 file : any disk format supported by qemu-nbd
21
22 the temporary mountpoint will be put in an a environment variable
23 named MOUNTPOINT.
24
25 if any of the arguments are the literal string '_MOUNTPOINT_', then
26 they will be replaced with the mount point. Example:
27 ${0##*/} my.img chroot _MOUNTPOINT_ /bin/sh
28
29 Additionally, the helper program 'mchroot' will be added to the path
30 and can be used effectively as 'chroot _MOUNTPOINT_':
31 ${0##*/} my.img mchroot
32
33 options:
34 -v | --verbose increase verbosity
35 -h | --help print this message.
36
37 --read-only use read-only mount.
38 -C | --cd-mountpoint change dir to mountpoint before executing cmd.
39 -m | --mountpoint MP mount to directory MP rather than a temp dir
40 --overlay mount via overlayfs
41 -P | --partition PARTNUM mount partition PARTNUM (default 'auto')
42 if 'auto', then mount part 1 if image is
43 partitioned otherwise mount image
44 -p | --proc bind mount /proc
45 -s | --sys bind mount /sys
46 -d | --dev bind mount /dev
47
48 --system-mounts bind mount /sys, /proc, /dev
49 --system-resolvconf copy host's resolvconf into /etc/resolvconf
50 --format FMT specify the format of the image.
51 default is to automatically determine
52 EOF
53 }
54
55 # umount_r(mp) : unmount any filesystems under r
56 # this is useful to unmount a chroot that had sys, proc ... mounted
57 umount_r() {
58 local p
59 for p in "$@"; do
60 [ -n "$p" ] || continue
61 tac /proc/mounts | sh -c '
62 p=$1
63 didumount=0
64 while read s mp t opt a b ; do
65 [ "${mp}" = "${p}" -o "${mp#${p}/}" != "${mp}" ] ||
66 continue
67 umount "$mp" || exit 1
68 didumount=1
69 done
70 [ $didumount -eq 1 ] || exit 1
71 exit 0' umount_r "${p%/}"
72 [ $? -eq 0 ] || return
73 done
74 }
75
76 bad_Usage() { Usage 1>&2; [ $# -eq 0 ] || error "$@"; exit 1; }
77
78 has_cmd() {
79 command -v "$1" >/dev/null 2>&1
80 }
81
82 disconnect_qemu() {
83 [ -n "$QEMU_DISCONNECT" ] || return 0
84 local out="" nbd="$QEMU_DISCONNECT"
85 debug 1 "disconnecting $nbd"
86 local pid="" pfile="/sys/block/${nbd#/dev/}/pid"
87 { read pid < "$pfile" ; } >/dev/null 2>&1
88 [ -n "$pid" -a ! -d "/proc/$pid" ] &&
89 error "qemu-nbd process seems to have died. was '$pid'"
90 out=$(qemu-nbd --disconnect "$nbd" 2>&1) &&
91 QEMU_DISCONNECT="" || {
92 error "failed to disconnect $nbd";
93 error "$out"
94 return 1;
95 }
96 }
97
98 do_umounts() {
99 local um="" fails=0 mydir="$PWD/" mounts="" i=0
100 mounts=( "$@" )
101 for((i=${#mounts[@]}-1;i>=0;i--)); do
102 um=${mounts[$i]}
103 um=$(readlink -f "$um") || {
104 error "WARNING: failed to get full path to '$um'";
105 fails=$(($fails+1))
106 continue;
107 }
108 [ "${mydir#${um}/}" != "${mydir}" ] && {
109 error "WARNING: leaving '$mydir' to unmount $um";
110 cd /
111 }
112 umount_r "$um" || {
113 error "WARNING: unmounting filesystem at $um failed!"
114 fails=$(($fails+1))
115 }
116 done
117 return $fails
118 }
119
120 cleanup() {
121 if [ "${#UMOUNTS[@]}" -ne 0 ]; then
122 debug 2 "umounts: ${UMOUNTS[*]}"
123 do_umounts "${UMOUNTS[@]}" ||
124 { error "failed cleaning up mounts"; return 1; }
125 fi
126 disconnect_qemu
127 rm -Rf "$TEMP_D" || error "removal of temp dir failed!"
128 }
129
130 debug() {
131 local level="$1"; shift;
132 [ "${level}" -gt "${VERBOSITY}" ] && return
133 error "${@}"
134 }
135
136 get_image_format() {
137 local img="$1" out=""
138 out=$(qemu-img info "$img") &&
139 out=$(echo "$out" | awk '$0 ~ /^file format:/ { print $3 }') &&
140 _RET="$out"
141 }
142
143 get_partition() {
144 # return in _RET the 'auto' partition for a image.
145 # _RET=partition number for a partitioned image
146 # _RET=0 for unpartitioned
147 local img="$1"
148 out=$(LANG=C sfdisk --list -uS "$img" 2>&1) || {
149 error "failed determining if partitioned: $out";
150 return 1;
151 }
152 if echo "$out" | grep -q 'Device.*Start.*End'; then
153 _RET=1
154 else
155 _RET=0
156 fi
157 }
158
159 add_bin() {
160 cat > "$1" || { error "failed to write to $1"; return 1; }
161 chmod 755 "$1" || { error "failed to set perms on $1"; return 1; }
162 }
163
164 add_helpers() {
165 local d="$1"
166 local umap="$1" gmap="$2"
167 [ -d "$1" ] || mkdir -p "$1"
168 add_bin "$d/mchroot" <<"EOF" || return 1
169 #!/bin/sh
170 exec chroot "$MOUNTPOINT" "$@"
171 EOF
172 return
173 }
174
175 mount_overlay() {
176 local lower="$1" upper="$2" workdir="$3"
177 local olayopts="lowerdir=$lower,upperdir=$upper"
178 # 3.18+ require 'workdir=' option.
179 case "$(uname -r)" in
180 2*|3.1[01234567]*|3.[0-9].*) :;;
181 *) olayopts="${olayopts},workdir=$workdir"
182 mkdir -p "$workdir" ||
183 { _ERR="Failed to create workdir '$workdir'"; return 1; }
184 ;;
185 esac
186
187 local cmd="" fstype="" ret="" out="" fsfile="/proc/filesystems"
188 _ERR=""
189 for fstype in overlay overlayfs; do
190 cmd=( mount -t "$fstype" -o "$olayopts" "$lower" "$upper" )
191 debug 2 "attempting '$fstype' mount with: ${cmd[*]}"
192 out=$("${cmd[@]}" 2>&1)
193 ret=$?
194 if [ $ret -eq 0 ]; then
195 debug 1 "mounted '$fstype' via $fstype: ${cmd[*]}"
196 return 0
197 fi
198 _ERR="${_ERR}Failed [$ret]: ${cmd[*]}:${CR}"
199 _ERR="${_ERR}$out${CR}"
200 if [ -r "$fsfile" ] && grep -q "${TAB}${fstype}$" "$fsfile"; then
201 # this failed and we have support in kernel. do not try further.
202 return $ret
203 fi
204 done
205 return $ret
206 }
207
208 assert_nbd_support() {
209 if [ ! -e /sys/block/nbd0 ] && ! grep -q nbd /proc/modules; then
210 debug 1 "trying to load nbd module"
211 modprobe nbd >/dev/null 2>&1
212 has_cmd udevadm && udevadm settle >/dev/null 2>&1
213 fi
214 [ -e /sys/block/nbd0 ] || {
215 error "Cannot use nbd: no nbd kernel support."
216 return 1;
217 }
218 }
219
220 find_unused_nbd() {
221 # return a path to an unused nbd device (/dev/nbd?)
222 local f roflag=""
223 for f in /sys/block/nbd*; do
224 [ -d "$f" -a ! -f "$f/pid" ] &&
225 { _RET="/dev/${f##*/}"; return 0; }
226 done
227 error "failed to find an nbd device"
228 return 1;
229 }
230
231 connect_nbd() {
232 local img="$1" fmt="$2" ptnum="${3:-auto}" rwmode="${3:-ro}"
233 local nbd="" pidfile="" pid="" cmd="" ret="" roflag="" nptnum="" i=""
234 if [ "$rwmode" = "ro" ]; then
235 roflag="--read-only"
236 fi
237 # yes, there is a race condition here.
238 find_unused_nbd || return
239 nbd="$_RET"
240 cmd=( qemu-nbd $roflag "--format=$fmt" --connect "$nbd" "$img" )
241 "${cmd[@]}" && QEMU_DISCONNECT="$nbd"
242 ret=$?
243 if [ $ret -ne 0 ]; then
244 error "Failed [$ret]: $*"
245 return $ret
246 fi
247 pidfile="/sys/block/${nbd#/dev/}/pid"
248 if [ ! -f "$pidfile" ]; then
249 debug 1 "waiting on pidfile for $nbd in $pidfile"
250 i=0
251 while [ ! -f "$pidfile" ] && i=$(($i+1)); do
252 if [ $i -eq 200 ]; then
253 error "giving up on pidfile $pidfile for $nbd"
254 disconnect_qemu
255 return 1
256 fi
257 sleep .1
258 debug 2 "."
259 done
260 fi
261 read pid < "$pidfile" && debug 2 "pid for $nbd is $pid" || {
262 error "reading pid from $pidfile for $nbd failed!";
263 disconnect_qemu
264 return 1
265 }
266
267 debug 1 "connected $img_in ($fmt) ${rwmode} to $nbd. waiting for device."
268
269 local out=""
270 # This can fail due to udev events, but we ignore that. We need to ensure
271 # it happens for where it does not happen automatically (LP: #1741300)
272 out=$(blockdev --rereadpt "$nbd" 2>&1) ||
273 debug 1 "blockdev rereadpt $nbd failed"
274 has_cmd udevadm && udevadm settle
275
276 i=0
277 while i=$(($i+1)); do
278 get_partition "$nbd" && nptnum="$_RET" && break
279 [ $i -eq 40 ] && {
280 error "gave up on $nbd"
281 disconnect_qemu
282 return 1
283 }
284 [ $(($i%10)) -eq 0 ] &&
285 debug 1 "waiting for $nbd to be ready."
286 sleep .1
287 done
288
289 if [ "${ptnum}" = "auto" ]; then
290 if [ "$nptnum" = "0" ]; then
291 debug 1 "unpartitioned disk."
292 else
293 debug 1 "partitioned disk."
294 fi
295 ptnum=$nptnum
296 else
297 if [ "$nptnum" = "0" -a "$ptnum" != "0" ]; then
298 error "img $img does not appear partitioned but ptnum=$ptnum provided."
299 return 1
300 fi
301 fi
302 if [ "$ptnum" -ne 0 ]; then
303 mdev="${nbd}p${ptnum}"
304 else
305 mdev="${nbd}"
306 fi
307
308 i=0
309 while :; do
310 [ -b "$mdev" ] && break
311 i=$(($i+1))
312 [ $i -eq 100 ] && {
313 error "gave up on waiting for $mdev"
314 disconnect_qemu
315 return 1
316 }
317 [ $(($i%10)) -eq 0 ] &&
318 debug 1 "waiting for $mdev part=$ptnum to be ready."
319 sleep .1
320 done
321
322 _RET_NBD="$nbd"
323 _RET_PT="$ptnum"
324 _RET_DEV="$mdev"
325 }
326
327 mount_nbd() {
328 local img="$1" mp="$2" fmt="$3" ptnum="$4" rwmode="${5:-rw}" opts="$6"
329 if [ -z "$fmt" ]; then
330 get_image_format "$img" && fmt="$_RET" || {
331 error "failed to get image format for '$img' (try --format)"
332 return 1
333 }
334 fi
335 assert_nbd_support || return
336 connect_nbd "$img" "$fmt" "$ptnum" "$rwmode" || return
337 local ptnum="$_RET_PT" mdev="$_RET_DEV" nbd="$_RET_NBD"
338 if ( set -f; mount -o "$rwmode" $opts "$mdev" "$img_mp" ); then
339 debug 1 "mounted $mdev via qemu-nbd $nbd at $img_mp"
340 else
341 error "failed to mount $mdev"
342 return 1
343 fi
344 }
345
346 mount_callback_umount() {
347 local img_in="$1" dev="" out="" mp="" ret="" img="" readonly=false
348 local opts="" bmounts="" system_resolvconf=false ptnum=auto
349 local cd_mountpoint=false fmt="" overlay=false rwmode="rw"
350 local img_mp=""
351
352 short_opts="Cdhm:P:psSv"
353 long_opts="cd-mountpoint,dev,help,format:,mountpoint:,overlay,partition:,proc,read-only,sys,system-mounts,system-resolvconf,verbose"
354 getopt_out=$(getopt -n "${0##*/}" \
355 -o "${short_opts}" -l "${long_opts}" -- "$@") &&
356 eval set -- "${getopt_out}" ||
357 { bad_Usage; return 1; }
358
359 while [ $# -ne 0 ]; do
360 cur=${1}; next=${2};
361 case "$cur" in
362 -C|--cd-mountpoint) cd_mountpoint=true;;
363 -d|--dev) bmounts="${bmounts:+${bmounts} }/dev";;
364 --format) fmt=$next;;
365 -h|--help) Usage ; exit 0;;
366 -m|--mountpoint) mp=$next;;
367 -P|--partition) ptnum=$next;;
368 --overlay) overlay=true;;
369 -p|--proc) bmounts="${bmounts:+${bmounts} }/proc";;
370 -s|--sys) bmounts="${bmounts:+${bmounts} }/sys";;
371 -S|--system-mounts) bmounts="/dev /proc /sys";;
372 --system-resolvconf) system_resolvconf=true;;
373 -v|--verbose) VERBOSITY=$((${VERBOSITY}+1));;
374 --opts) opts="${opts} $next"; shift;;
375 --read-only) readonly=true; rwmode="ro";;
376 --) shift; break;;
377 esac
378 shift;
379 done
380
381 [ $# -ge 2 ] || { bad_Usage "must provide image and cmd"; return 1; }
382
383 $readonly && { $system_resolvconf && ! $overlay; } && {
384 error "--read-only is incompatible with system-resolvconf";
385 error "maybe try with --overlay"
386 return 1;
387 }
388
389 img_in="$1"
390 shift 1
391
392 if [ "${img_in#lxd:}" != "${img_in}" -a ! -f "${img_in}" ]; then
393 error "${img_in}: lxd is no longer supported."
394 return 1;
395 fi
396
397 img=$(readlink -f "$img_in") ||
398 { error "failed to get full path to $img_in"; return 1; }
399 [ -f "$img" ] ||
400 { error "$img: not a file"; return 1; }
401
402 [ "$(id -u)" = "0" ] ||
403 { error "sorry, must be root"; return 1; }
404
405 trap cleanup EXIT
406 TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX") ||
407 { error "failed to make tempdir"; return 1; }
408 if [ -z "$mp" ]; then
409 mp="${TEMP_D}/mp"
410 mkdir "$mp" || return
411 else
412 [ -d "$mp" ] ||
413 { error "mountpoint '$mp': not a directory"; return 1; }
414 mp=$(readlink -f "$mp") || {
415 error "failed to get full path to provided mountpoint";
416 return 1;
417 }
418 fi
419 if $overlay; then
420 img_mp="${TEMP_D}/underlay"
421 mkdir -p "$img_mp" || return
422 else
423 img_mp=$mp
424 fi
425
426 out=""
427 if [ "$ptnum" = "auto" -o "$ptnum" = "0" ] &&
428 out=$(set -f; mount -o "loop,$rwmode" $opts "$img" "$img_mp" 2>&1); then
429 debug 1 "mounted simple fs image $rwmode in '$img_in' at $img_mp"
430 UMOUNTS[${#UMOUNTS[@]}]="$img_mp"
431 else
432 local hasqemu=false
433 command -v "qemu-nbd" >/dev/null 2>&1 && hasqemu=true
434 if ! $hasqemu; then
435 error "simple mount of '$img_in' failed."
436 error "if this is not a simple unpartitioned raw image, then"
437 error "you must have qemu-nbd (apt-get install qemu-utils)"
438 if [ -n "$out" ]; then
439 error "mount failed with: $out"
440 fi
441 return 1
442 fi
443 mount_nbd "$img" "$img_mp" "$fmt" "$ptnum" "$rwmode" "$opts" || return
444 UMOUNTS[${#UMOUNTS[@]}]="$img_mp"
445 fi
446
447 if $overlay; then
448 mount_overlay "$img_mp" "$mp" "${TEMP_D}/workdir" || {
449 [ -n "${_ERR}" ] && error "${_ERR}"
450 error "Unable to mount overlay filesystem. Maybe no kernel support?"
451 return 1
452 }
453 UMOUNTS[${#UMOUNTS[@]}]="$mp"
454 fi
455
456 local bindmp=""
457 for bindmp in $bmounts; do
458 [ -d "$mp${bindmp}" ] || mkdir "$mp${bindmp}" ||
459 { error "failed mkdir $bindmp in mount"; return 1; }
460 mount --bind "$bindmp" "$mp${bindmp}" ||
461 { error "failed bind mount '$bindmp'"; return 1; }
462 UMOUNTS[${#UMOUNTS[@]}]="$mp${bindmp}"
463 debug 1 "mounted $bindmp to $mp${bindmp}"
464 done
465
466 if ${system_resolvconf}; then
467 local rcf="$mp/etc/resolv.conf"
468 debug 1 "replacing /etc/resolvconf"
469 if [ -e "$rcf" -o -L "$rcf" ]; then
470 local trcf="$rcf.${0##*/}.$$"
471 rm -f "$trcf" &&
472 mv "$rcf" "$trcf" && ORIG_RESOLVCONF="$trcf" ||
473 { error "failed mv $rcf"; return 1; }
474 fi
475 cp "/etc/resolv.conf" "$rcf" ||
476 { error "failed copy /etc/resolv.conf"; return 1; }
477 fi
478
479 local cmd="" arg="" found=false
480 cmd=( )
481 for arg in "$@"; do
482 if [ "${arg}" = "_MOUNTPOINT_" ]; then
483 debug 1 "replaced string _MOUNTPOINT_ in arguments arg ${#cmd[@]}"
484 arg=$mp
485 fi
486 cmd[${#cmd[@]}]="$arg"
487 done
488 if [ "${cmd[0]##*/}" = "bash" -o "${cmd[0]##*/}" = "sh" ] &&
489 [ ${#cmd[@]} -eq 0 ]; then
490 debug 1 "invoking shell ${cmd[0]}"
491 error "MOUNTPOINT=$mp"
492 fi
493
494 add_helpers "$TEMP_D/bin" "$SUBUID" "$SUBGID" || {
495 error "failed to add helpers to $TEMP_D";
496 return 1;
497 }
498 PATH="$TEMP_D/bin:$PATH"
499
500 local startwd="$PWD"
501 debug 1 "invoking: MOUNTPOINT=$mp" "${cmd[@]}"
502
503 ${cd_mountpoint} && cd "$mp"
504 MOUNTPOINT="$mp" "${cmd[@]}"
505 ret=$?
506 cd "$startwd"
507
508 if ${system_resolvconf}; then
509 local rcf="$mp/etc/resolv.conf"
510 cmp -s "/etc/resolv.conf" "$rcf" >/dev/null ||
511 error "WARN: /etc/resolv.conf changed in image!"
512 rm "$rcf" &&
513 { [ -z "$ORIG_RESOLVCONF" ] || mv "$ORIG_RESOLVCONF" "$rcf"; } ||
514 { error "failed to restore /etc/resolv.conf"; return 1; }
515 fi
516
517 debug 1 "cmd returned $ret. unmounting $mp"
518 do_umounts "${UMOUNTS[@]}" && UMOUNTS=( ) ||
519 { error "failed umount $img"; return 1; }
520
521 if [ -n "$QEMU_DISCONNECT" ]; then
522 disconnect_qemu || return 1;
523 fi
524 return $ret
525 }
526
527 mount_callback_umount "$@"
528
529 # vi: ts=4 noexpandtab