From time to time one may receive a request from the QA in line of:
For testing purposes, I need that /opt/test/xxx directory be limited to 10 Megabytes. This directory is used by the zzz application ran as user tester.
How could the directory size be limited in Linux? Is it even possible? – these are fair questions and the answer is yes. One needs to:
Use the directory as a mount point for a size-limited storage device;
Use the proper mount options to allow full access to the non-root user specified;
Disable Selinux (easy) or allow that particular user to access data on mount points (complicated).
Let’s start with the beginning, the storage device. There are multiple options here:
A simple loop device (a regular file used as a file system);
A logical volume (LVM), assuming the disk setup is based on this technology and there is enough free space left to accomodate the new device;
Attaching a new storage device (e.g. in a Cloud environment like Amazon Web Services).
There are pros and cons to each of these; the loop device solution is by far the simplest to implement but one must be aware of the lower I/O performance compared to the other solutions. E.g.:
/* create a directory to hold the image file */ # mkdir /var/spool/loop-files /* create a 10Mb zero-filled image file */ # dd if=/dev/zero of=/var/spool/loop-files/xxx.img bs=1024 count=10240 /* determine the first unused loop device */ # losetup -f /dev/loop2 /* associate the image file with the loop device */ # losetup /dev/loop2 /var/spool/loop-files/xxx.img /* create the file system on the device */ # mkfs.ext4 /dev/loop2 /* update fstab to allow for non-privileged user mounting */ # echo "/dev/loop2 /opt/test/xxx ext4 defaults,noauto,user 0 0" >> /etc/fstab /* mount as user */ # su - tester "mount /opt/test/xxx" /* check the mounted devices */ # df ... ...
Note: the size of the file system cannot be set to any precise size due to the block / superblock / journal / other meta fields sizes. The available storage size once the filesystem is created also varies so the “10 Megabytes” requests can be satisfied to the nearest possible value through some trial and error sizing.
Follow Up: there is a limit of 8 loop devices that can be defined on a non-tweaked installation. To increase this number one needs to:
/* tell the kernel module to support more devices */ # modprobe loop max_loop=64 /* create the devices, e.g: */ # mknod -m 660 /dev/loop36 b 7 36
This should solve the problem we started with. Thank you for your read!