lxc-config/templates/lxc-overlay

106 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
set -ex
add_overlayfs(){
local base_rootfs="$1"
local root_path="$2"
local rootfs="$root_path/rootfs"
local path="$3"
local lower="$base_rootfs/${path}"
local upper="$root_path/.${path}-delta"
local work="$root_path/.${path}-work"
[[ -d "$rootfs" ]] || mkdir -p "$rootfs"
[[ -d "$work" ]] || mkdir -p "$work"
[[ -d "$upper" ]] || mkdir -p "$upper"
[[ -d "$lower" ]] || mkdir -p "$lower"
echo "overlay $path overlay lowerdir=$lower,upperdir=$upper,workdir=$work 0 0" >> "$root_path/fstab"
}
echo args $@
options=$(getopt -o n:4:6: -l name:,path:,rootfs:,mapped-uid:,mapped-gid: -- "$@")
if [ $? -ne 0 ]; then
usage $(basename $0)
exit 1
fi
eval set -- "$options"
while true
do
case "$1" in
-n|--name) name=$2; shift 2;;
--path) path=$2; shift 2;;
--rootfs) rootfs=$2; shift 2;;
--mapped-uid) uid=$2; shift 2;;
--mapped-gid) gid=$2; shift 2;;
--) shift 1; break ;;
*) break ;;
esac
done
if [ -z "${name}" ]; then
echo "missing required 'name' parameter"
exit 1
fi
if [ -z "${path}" ]; then
echo "missing required 'path' parameter"
exit 1
fi
if [ -z "${rootfs}" ]; then
echo "missing required 'rootfs' parameter"
exit 1
fi
overlay_conf="/etc/lxc/overlay.conf"
if [ ! -e "$overlay_conf" ]; then
echo "Configuration at /etc/lxc/overlay.conf does not exists"
exit 1
fi
base_rootfs=$(perl -ne 'print $1 if /lxc.rootfs\s*=\s*(.*)/' "$overlay_conf")
config="${path}/config"
touch "$path/fstab"
add_overlayfs "$base_rootfs" "$path" "var"
add_overlayfs "$base_rootfs" "$path" "etc"
add_overlayfs "$base_rootfs" "$path" "home"
add_overlayfs "$base_rootfs" "$path" "srv"
add_overlayfs "$base_rootfs" "$path" "mnt"
add_overlayfs "$base_rootfs" "$path" "root"
cat > "$config" <<EOF
lxc.include = $overlay_conf
lxc.include = ${path}/local.conf
lxc.mount = ${path}/fstab
lxc.utsname = $name
EOF
touch "$path/local.conf"
export LXC_ROOTFS_PATH="$path/rootfs"
export LXC_NAME=$name
export LXC_CONFIG_FILE="$config"
cat > "/tmp/${LXC_NAME}-hooks" <<EOF
#!/usr/bin/env bash
mount --bind "$path/fstab" /etc/fstab
mount --bind "$base_rootfs" "$LXC_ROOTFS_PATH" -o ro
cd "$LXC_ROOTFS_PATH"
mount -a
perl -n \
-e'/CREATE_HOOKS="([^"]+)"/ && map { system("/etc/lxc/hooks/\$_") == 0 or print("executing \$_ failed\n") } split(/\s+/, \$1)' \
"$overlay_conf"
EOF
chmod +x "/tmp/${LXC_NAME}-hooks"
unshare -m "/tmp/${LXC_NAME}-hooks"
rm "/tmp/${LXC_NAME}-hooks"
chown -R "$uid:$gid" "${path}"/* "${path}"/.*
chown -R "0:0" "${path}/config" "${path}/local.conf"
chmod +x "${path}"