1#!/bin/sh 2# 3# Perform a bind mount, copying existing files as we do so to ensure the 4# overlaid path has the necessary content. 5# If the target is a directory and overlayfs is available (and the environment 6# variable MOUNT_COPYBIND_AVOID_OVERLAYFS=1 is not set), then an overlay mount 7# will be attempted first. 8 9if [ $# -lt 2 ]; then 10 echo >&2 "Usage: $0 spec mountpoint [OPTIONS]" 11 exit 1 12fi 13 14# e.g. /var/volatile/lib 15spec=$1 16 17# e.g. /var/lib 18mountpoint=$2 19 20if [ $# -gt 2 ]; then 21 options=$3 22else 23 options= 24fi 25 26[ -n "$options" ] && options=",$options" 27 28mkdir -p "${spec%/*}" 29 30if [ -d "$mountpoint" ]; then 31 32 if [ -d "$spec" ]; then 33 specdir_existed=yes 34 else 35 specdir_existed=no 36 mkdir "$spec" 37 # If the $spec directory is created we need to take care that 38 # the selinux context is correct 39 if command -v selinuxenabled > /dev/null 2>&1; then 40 if selinuxenabled; then 41 restorecon "$spec" 42 fi 43 fi 44 fi 45 46 # Fast version of calculating `dirname ${spec}`/.`basename ${spec}`-work 47 overlay_workdir="${spec%/*}/.${spec##*/}-work" 48 mkdir "${overlay_workdir}" 49 50 # Try to mount using overlay, which is must faster than copying files. 51 # If that fails, fall back to slower copy. 52 if command -v selinuxenabled > /dev/null 2>&1; then 53 if selinuxenabled; then 54 mountcontext=",rootcontext=$(matchpathcon -n "$mountpoint")" 55 fi 56 fi 57 if [ "$MOUNT_COPYBIND_AVOID_OVERLAYFS" = 1 ] || ! mount -t overlay overlay -olowerdir="$mountpoint",upperdir="$spec",workdir="$overlay_workdir""$mountcontext" "$mountpoint" > /dev/null 2>&1; then 58 59 if [ "$specdir_existed" != "yes" ]; then 60 cp -aPR "$mountpoint"/. "$spec/" 61 fi 62 63 mount -o "bind$options" "$spec" "$mountpoint" 64 # restore the selinux context. 65 if command -v selinuxenabled > /dev/null 2>&1; then 66 if selinuxenabled; then 67 restorecon -R "$mountpoint" 68 fi 69 fi 70 fi 71elif [ -f "$mountpoint" ]; then 72 if [ ! -f "$spec" ]; then 73 cp -aP "$mountpoint" "$spec" 74 fi 75 76 mount -o "bind$options" "$spec" "$mountpoint" 77 # restore the selinux context. 78 if command -v selinuxenabled > /dev/null 2>&1; then 79 if selinuxenabled; then 80 restorecon -R "$mountpoint" 81 fi 82 fi 83fi 84