FreedomBoxBlog

sourcecode of ps_rootfs

Rob van der Hoeven
Sun Dec 29 2013

This sourcecode is part of the Program Space Construction Set (PSCS) which you can download at the Downloads page.

#!/bin/bash
# This script is part of the PSCS version 0.7
# Copyright (C) 2013 Rob van der Hoeven
# Support at http://freedomboxblog.nl
# License: GPL version 3 or later.

init_process=$(ps -p 1 -o comm=)
ps_name=$1

if [ "$(id -u)" != "0" ]
then
    echo "ERROR: this script must be run by root"
    exit 1
fi

if [ $init_process != "init" ]
then
    echo "ERROR: this script must run from user space"
    exit 1
fi

if [ -z "$ps_name" ]
then
    echo "ERROR: please give the name of the program space as a parameter: e.g. ps_rootfs test1"
    exit 1
fi

ps_add_directory()
{
    if [ ! -d $1 ]
    then
        mkdir -p $1
    fi
}

ps_dir=/programspace
ps_data_dir=$ps_dir/$ps_name/data
ps_rootfs_dir=$ps_dir/$ps_name/rootfs
us_rootfs_dirs="bin etc lib lib64 run sbin srv usr var"

# create rootfs dir and make it a mount point

ps_add_directory $ps_rootfs_dir
mount --bind $ps_rootfs_dir $ps_rootfs_dir

# add normal directories to rootfs, use aufs to make user space
# directories read-only, all changes end up in data directory

for us_dir in $us_rootfs_dirs
do
    if [ -d /$us_dir ]
    then
        ps_add_directory $ps_data_dir/$us_dir
        ps_add_directory $ps_rootfs_dir/$us_dir
        mount -t aufs -o br=$ps_data_dir/$us_dir=rw:/$us_dir=ro none $ps_rootfs_dir/$us_dir
    else
        echo "/$us_dir does not exists, skipping"
    fi
done

# add special directories to rootfs

ps_add_directory $ps_rootfs_dir/dev/shm
ps_add_directory $ps_rootfs_dir/sys
ps_add_directory $ps_rootfs_dir/proc
ps_add_directory $ps_rootfs_dir/tmp
chmod 1777 $ps_rootfs_dir/tmp

mount -t tmpfs shm $ps_rootfs_dir/dev/shm
mount -t sysfs sysfs $ps_rootfs_dir/sys

psc $ps_name --chrootfs $ps_rootfs_dir

# add device nodes

psc $ps_name --run bash<<PROGRAMSPACE
[ ! -c /dev/null ] && mknod /dev/null c 1 3
[ ! -c /dev/zero ] && mknod /dev/zero c 1 5
[ ! -c /dev/random ] && mknod /dev/random c 1 8
[ ! -c /dev/urandom ] && mknod /dev/urandom c 1 9
exit
PROGRAMSPACE

# rootfs mount is now attached in program space, no need for it anymore

umount -l $ps_rootfs_dir