- Настройка дисковых квот в Linux
- Установка пакета quota
- Настройка раздела
- Корневая директория (/) + XFS
- Включение квот
- Ext и другие
- Установка квот
- Квоты пользователей
- Квоты для групп
- Копирование квот
- Настройка периода отсрочки
- Просмотр и проверка квот
- Отчет по квотам
- Проверка
- Другие квоты
- Квота на директорию
- Квоты в samba
- Квоты в vsftpd
- What is quotas in linux
- Other Tutorials
Настройка дисковых квот в Linux
Пошагово разберем процесс установки ограничений на использование дискового пространства в системах Linux. Какой дистрибутив — не важно. Процесс немного различается для файловых систем XFS и EXT4/остальных — мы разберем оба варианта.
Установка пакета quota
Установка пакета для управления квотами выполняется из репозитория.
а) для систем на базе RPM (Red Hat, CentOS):
yum install quota
б) для систем на базе deb (Debian, Ubuntu):
apt-get install quota
Настройка раздела
Для возможности управлять квотами для определенного раздела необходимо его смонтировать с соответствующими опциями. Для файловых систем XFS и не XFS (например, ext) эти опции различаются:
- Для XFS — uquota (для пользователей) и/или gquota (для групп).
- Для ext и других — usrquota (для пользователей)и/или grpquota (для групп).
И так, чтобы добавить нужные опции для включения квотирования, откроем файл fstab:
Находим настройку для монтирования раздела, на который необходимо установить квоту и добавим нужные опции:
/dev/sda / ext4 defaults ,usrquota,grpquota 0 0
/dev/sdb /var xfs defaults ,uquota,gquota 0 0
* в данном примере мы добавили опции usrquota и grpquota для устройства /dev/sda, примонтированного в качестве корневого раздела / с файловой системой ext. А также опции uquota и gquota для устройства /dev/sdb (монтируется в /var с файловой системой xfs). Если необходимо включить квоту только для пользователей или групп, оставляем соответствующие опции.
* существуют и другие опции, например, jqfmt нужна для указания формата квоты при использовании журналирования. Подробнее описано в таблице Опции системы квот в файле /etc/fstab сайта IBM.
Перемонтируем наши разделы:
mount -o remount /
mount -o remount /var
Проверим, что нужные нам разделы теперь смонтированы с опциями квотирования:
mount | grep quota
Мы увидим, примерно, следующее:
/dev/sda on / type ext4 (rw,relatime, quota,usrquota,grpquota ,data=ordered)
/dev/sdb on /var type xfs (rw,relatime,attr2,inode64, usrquota,grpquota )
Квоты включены для разделов.
Корневая директория (/) + XFS
При попытке включить квоту для корневой директории XFS с помощью файла fstab, результат будет нулевым — в опциях монтирования мы будем наблюдать noquota, например:
/dev/sda on / type xfs (rw,relatime,attr2,inode64, noquota )
Для включения опции квотирования необходимо отредактировать загрузчик. Для этого открываем файл:
Находим строку GRUB_CMDLINE_LINUX и дописываем в нее rootflags=uquota,gquota — в моем случае получилось так:
.
GRUB_CMDLINE_LINUX=»crashkernel=auto rd.lvm.lv=vg/root rd.lvm.lv=vg/swap rhgb quiet floppy.allowed_drive_mask=0 rootflags=uquota,gquota »
.
На всякий случай, сохраним конфигурационный файл загрузчика:
cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.backup
. и применим настройки grub:
grub2-mkconfig -o /boot/grub2/grub.cfg
После перезагрузки мы должны наблюдать такую картину:
mount | grep quota
/dev/mapper/vg-root on / type xfs (rw,relatime,attr2,inode64, usrquota,grpquota )
Квоты включены для корневого раздела с файловой системой XFS.
Включение квот
И так, мы разрешили квоты для разделов. Теперь включаем квоты. Процессы для XFS и остальных файловых систем немного различаются. Мы рассмотрим оба варианта. Так как в нашем примере есть разделы для XFS и Ext, то мы выполним все варианты настроек.
После монтирования раздела с файловой системой XFS автоматически включается квотирование (если была задана соответствующая опция). Проверить состояние можно, войдя в режим экспертного управления квотами:
. и выполнив команду для получения статуса:
Ext и другие
Выполним проверку наличия служебных файлов aquota.user и aquota.group — если их нет, команда их создаст автоматически:
. при наличии разделов с включенной квотой на XFS мы можем увидеть:
quotacheck: Skipping /dev/sdb [/var]
* это нам говорит о том, что команда quotacheck пропускаем раздел с xfs.
Включаем квоту для разделов:
Установка квот
Пришло время задать квоты. Они устанавливаются с помощью команды edquota.
Квоты пользователей
Для пользователя, вводим команду:
edquota -u dmosk
* где dmosk — имя пользователя, для которого будет задана квота.
В открывшемся редакторе можно задать ограничение на использование разделов, для которых включена квота:
Disk quotas for user dmosk (uid 1001):
Filesystem blocks soft hard inodes soft hard
/dev/sda 20 0 10M 8 0 0
/dev/sdb 0 0 20M 0 0 0
- Filesystem — дисковое устройство, для которого устанавливается квота.
- blocks — текущее количество используемых пользователем блоков.
- первый soft — мягкая квота на объем данных (при ее превышении отправляется уведомление по почте, а после периода отсрочки, который по умолчанию составляет 7 дней, мягкая квота становится жесткой).
- первый hard — жесткая квота на объем данных (при ее превышении дальнейшая запись будет запрещена).
- inodes — текущее количество файлов, используемых пользователем.
- второй soft — мягкая квота на количество файлов (при ее превышении отправляется уведомление по почте).
- второй hard — жесткая квота на количество файлов (при ее превышении дальнейшая запись будет запрещена).
* в данном примере мы задали жесткую квоту для пользователя dmosk в 10 Мб на /dev/sda (корневой раздел) и 20 Мб на /dev/sdb (/var).
Квоты для групп
Для группы, задаем квоту так:
Как и в случае с пользователем, откроется редактор, с помощью которого можно задать квоту:
Disk quotas for group mail (gid 12):
Filesystem blocks soft hard inodes soft hard
/dev/sda 0 0 30M 6 0 0
/dev/sdb 0 0 40M 0 0 0
* в данном примере мы зададим квоту для группы в 30 Мб на /dev/sda (корневой раздел) и 40 Мб на /dev/sdb (/var).
Копирование квот
Мы также можем копировать квоты для пользователей. Для этого используется та же команда edquota с ключом -p:
edquota -p dmosk ivanov
* в данном примере мы скопируем настройку квотирования, которая применяется к dmosk на другого пользователя ivanov.
Настройка периода отсрочки
Как было упомянуто выше, мягкие ссылки являются мягкими только в течение периода отсрочки. Данный период по умолчанию равен 7 дням. Его можно задать командой edquota с ключом -t:
В открывшемся окне задаем новые значения:
Grace period before enforcing soft limits for users:
Time units may be: days, hours, minutes, or seconds
Filesystem Block grace period Inode grace period
/dev/mapper/vg-root 8days 9days
/dev/sdb 8days 9days
* в данном примере мы задали 8 дней для квот на дисковое пространство и 9 дней — на количество файлов.
Просмотр и проверка квот
Ограничения настроены. Проверим.
Отчет по квотам
Чтобы посмотреть отчет об используемом пространстве и установленных квотах, вводим команду:
* для отчета корневого раздела только по пользовательским (u) квотам в режиме удобного чтения (s).
* для отчета по разделу /var для групп.
Мы увидим что-то на подобие:
*** Report for user quotas on device /dev/sda
Block grace time: 7days; Inode grace time: 7days
Block limits File limits
User used soft hard grace used soft hard grace
———————————————————————-
root — 2862M 0K 0K 115k 0 0
polkitd — 0K 0K 0K 2 0 0
tss — 8K 0K 0K 2 0 0
postfix — 4K 0K 0K 38 0 0
chrony — 4K 0K 0K 3 0 0
dmosk — 20K 0K 10240K 8 0 0
rpc — 0K 0K 0K 2 0 0
ntp — 4K 0K 0K 3 0 0
.
* как видим, это отчет по использованию раздела /. Мы видим, каким пользователем сколько занято дискового пространства и видим, что для нашего пользователя dmosk установлена квота в 10 Мб (10240 Кб).
Проверка
И так, мы настроили для пользователя dmosk ограничение на использование дискового пространства. Попробуем превысить данный лимит. Заходим в консоль под нужным пользователем:
dd if=/dev/zero of=/tmp/tmp_dmosk_file bs=1024000 count=100
* команда должна создать файл на 100 Мб в каталоге tmp.
Однако, система вернет сообщение:
dd: ошибка записи «/tmp/tmp_dmosk_file»: Превышена дисковая квота
11+0 записей получено
10+0 записей отправлено
скопировано 10240000 байт (10 MB), 0,223768 c, 45,8 MB/c
Другие квоты
Иногда, необходимо установить квоту в рамках определенной программы или каталога.
Однако, квоты так не работают и нет возможности задать их для определенного каталога или программы. Но это не означает, что выхода нет.
Квота на директорию
Чаще всего, нет необходимости задавать квоту на всю систему — нужно только ограничение размера директории. В данной ситуации нам нужно примонтировать диск к нужной директории и задать квоту на примонтированный раздел.
Квоты в samba
Как правило, речь в контексте samba идет о ограничения на использование шары. Для этого необходимо каждую шару поместить на отдельный раздел, каждый со своей квотой.
Также в файловом сервере samba есть возможность настройки квотирования на уровне программного обеспечения. В конфигурационном файле при настройке шары добавим:
[share]
.
vfs objects = default_quota
default_quota:uid = 1022
default_quota:uid nolimit = no
.
* в данном примере мы задаем квоту на каталог share. Данная квота должна быть такой же, как у системного пользователя с uid 1022. Таким образом, системные квоты должны быть настроены.
Для samba есть также параметр max disk size, который не является ограничением, а просто показывает для других программ максимальный объем доступного пространства.
Квоты в vsftpd
Настраивая vsftpd, мы также должны позаботиться о том, чтобы каталоги с FTP были на разделах с установленными квотами. Другими словами — вопрос также решается с применением пакета quota.
Источник
What is quotas in linux
Implementing Disk Quotas on Linux
This tutorial walks you through implementing disk quotas for both users and groups on Linux, using a virtual filesystem, which is a filesystem created from a disk file. Since quotas work on a per-filesystem basis, this is a way to implement quotas on a sub-section, or even multiple subsections of your drive, without reformatting. This tutorial also covers quotactl, or quota’s C interface, by way of an example program that can store disk usage in a SQLite database for monitoring data usage over time.
This tutorial was tested on Fedora Core 2, 3, and 4. I’m assuming you have the quota tools installed. If you’re not sure, try the following test, which will return 3.12-6 or 3.12-5 depending on which version of Fedora Core you are using.
The following steps walk you through creating a ext3 virtual filesystem mounted on «/quota» with a size of 20 MB. Again, since quotas are installed on a filesystem, we’re going to create an isolated filesystem.
The mount point for this filesystem will be «quota». As root, first create the mount point quota, which at this point is just a directory.
Next, create a 20M file (disk image) in a suitable location. What I did below is create the file disk-quota.ext3 in the directory /usr/disk-img.
The dd command above created a 20MB file because, by default, dd uses a block size of 512 bytes. That makes this size: 40960*512=20971520. For kicks, we’ll confirm this size.
Next, format this as an ext3 filesystem.
The «-t» gives it the type. You’re not limited to ext3. In fact, you could use ext2 or other filesystems installed on your system. The «-q» is for the device, and «-F» is to force the creation without warning us that this is a file and not a block device.
Add the following line to «/etc/fstab». This will make the filesystem always available on reboot, plus it’s easier to mount and unmout when testing.
Now, mount this filesystem.
Now take a look at /quota. You should see the «lost+found» directory. Plus, you can take a look at /proc/mounts to see that you have an «ext3» type filesystem. At this point you can create and add files if you want.
This step creates a group and implements group rights on a directory within the quota filesystem. Specifically, this step creates the group, «quotagrp» and adds the two existing users «chirico» and «sporkey» into this group. The direcory «/quota/share» is setup so that any files created in this directory by these two users will be sharable by default for members of this group. This is done by setting the setgid bit on the directory.
First create the group and add any existing users.
Create the directory /quota/share and set the access rights so that files created in this directory can be edited by any group members.
Above the command «2755» sets the «setgid» bit. You can see this with the «ls» command below.
An important note here. If the users above «chirico» and «sporkey» are currently logged in when they were added to the group, they will not get access to the group. These users need to login again. Having these users run «newgrp» or even «newgrp -» (Fedora core 4) will give them access to the group; however, this will not correctly set group file permissions. To avoid trouble in a production environment have users login again or execute «su — » to corrently initilize their environment.
Run quotecheck. The first time you run this command, use the «-c» option to create the necessary database files. The following should be run as root.
Note that two files have been created «aquota.group» and «aquota.user».
Use «edquota» to grant the user «chirico» the desired quota.
Executing the command above brings up a text file in your default editor. You will change entries in this file.
Above for user chirico there have been no blocks or inodes used on this filesystem. Note that an inode is used for each file and directory. We’ll change the settings as follows:
Note that the numbers under «blocks» and «inodes» indicated the current blocks and inodes in use by this user. Those values should not be edited, since they are only used for reference.
setquota — command line quota editor
You can also use the setquota command, which has the advantage of not using an editor making it ideal for implementing in a script. For example, to set the soft block limit to 100, a hard block limit of 200, a soft inode to 10 and a hard inode to 15 as we did above, execute the following command.
Turn quotas on with the following command.
From the root user you can «su» into the chirico account to see the changes.
As an interesting test, still under this user, create a hard link as follows with the ln command. Then execute the quota command to see how many inodes are taken.
Note that the number of files has not changed. However, if you create a symbolic link, sometimes called a soft link, with the «ln -s» command, the number will increse to 2, because an additional inode is created with a soft link.
To set quotas for the group «quotagrp», use the following command.
Now make the following changes.
Or, use the «setquota» command as follows:
Now run the following command under the user account that has group access, which will attempt to create 15 files.
The «repquota» command prints a summarized report. It should be run with root.
To get a report by group, use the -g option as follows.
Note the «++» above for quotagrp indicating that both the block limit and inode limits have been exceeded.
Or to get everything, run repquota with the -a option as follows.
Running warnquota without any options will email users that go over the limit.
However in this case no mail message will be sent, because the group limit was exceeded. The file «/etc/quotagrpadmins» needs to contain a username responsible for the group. Here will put in the user «sporkey», so that the file looks as follows:
Now if warnquota is execute with the -g option, mail will be send to user «sporkey».
Messages can be customized by editing the «/etc/warnquota.conf» file.
You may want to create your own quota tools, especially if you forsee a need to monitor quota data over time, across multiple computers. My database tool of choice for this is SQLite because it is very fast, the complete database fits into one file, there is no setup or administration needed, and databases can be combine. For detailed information on using SQLite take a look at the («SQLite Tutorial»).
Goal — Create quotadb
The goal is to create the program «quotadb» that will automatically create the necessary database ( a default database quota_database) and tables, for all filesystems and all users on the system. There will also be a «-f » option to place the database file in a particular location, or just place it in the default directory as «quota_database», if no options are specified.
Now, after the initial commad is run, quotadb can be run on a peridoic basis to update the entries in the table. Update is specified with the -u option.
After the tables are created by running «quotadb -f /root/quota_database», quotadb is placed in a cron job and run nightly. To get into the cron editor as root type «cronjob -e».
Running this once a day, over a period of time, will populate the database table history, defined below.
The trigger definition above updates the timeEnter field with the current date and time. By the way this is localtime, hence the option ‘localtime’. The default would give you UTC time.
Structure — if_dqblk
One important structure that gets passed to quotactl is if_dqblk. This is defined in the file «quota.h», included in the quota_examples.tar.gz. You will not find this structure in #include or «/usr/include/linux/quota.h» on the Fedora distros. Instead, there is a copy of this structure in the «quota-3.12-5.src.rpm». You can get this source rpm as follows:
If you’re curious, the «rpm -K» command above checks the signature on the package.
After this installation, the source can be found under «/usr/src/redhat/SOURCES».
If you «tar -xzf» this source, you’ll see «quota.h», which contains the if_dqblk structure shown below. Note the block hard limit «dqb_bhardlimit», block soft limit «dqb_bsoftlimit», current space taken «dqb_curspace», and similar all 64 bit values for the inode variables as well.
By the way, the Linux kernel source contains a quota.h file as well «/lib/modules/2.6.11-1.35_FC3smp/build/include/linux/quota.h», which has an identical structure. It cannot be used in a user-land program. Kernel values for 64 bits are defined as __u65 and not u_int64_t; but, you can certainly see these values get passed directly to the kernel.
Example Call to quotactl
Below is an example call to quotactl for getting quota spaced used for uid. The variable dq is defined as type struct if_dqblk and it’s passed as the last parameter to quotactl. Note the macro QCMD(Q_GETQUOTA, USRQUOTA), passed as the first parameter. Q_GETQUOT, USRQUOTA are defined in «quota.h». The block device, as defined by block_device is the second parameter. And the user id value is defined in uid. The function quotactl returns 0 on success and -1 on failure.
Set Quota Options
The section above was an example of getting the quota settings. Let’s move on to changing or setting the quota options for the user defined in pwd->pw_uid. It helps to have a specific example. Below we will set a block soft limit of 78, block hard limit of 96, inode soft limit of 50, and an inode hard limit of 100. This program starts with a call to getpwname which takes the user name as a string and passes back a passwd structure. The passwd structure contains the user name, password, user id, group id, real name, home directory and shell program for that particular user.
Again, the full examples can be downloaded from quota_examples.tar.gz
Other Tutorials
Linux System Admin Tips: There are over 190 linux tips and tricks in this article. This article is updated weekly.
Breaking Firewalls with OpenSSH and PuTTY: If the system administrator deliberately filters out all traffic except port 22 (ssh), to a single server, it is very likely that you can still gain access other computers behind the firewall. This article shows how remote Linux and Windows users can gain access to firewalled samba, mail, and http servers. In essence, it shows how openSSH and Putty can be used as a VPN solution for your home or workplace.
SQLite Tutorial : This article explores the power and simplicity of sqlite3, first by starting with common commands and triggers, then the attach statement with the union operation is introduced in a way that allows multiple tables, in separate databases, to be combined as one virtual table, without the overhead of copying or moving data. Next, the simple sign function and the amazingly powerful trick of using this function in SQL select statements to solve complex queries with a single pass through the data is demonstrated, after making a brief mathematical case for how the sign function defines the absolute value and IF conditions.
Create a Live Linux CD — BusyBox and OpenSSH Included: These steps will show you how to create a functioning Linux system, with the latest 2.6 kernel compiled from source, and how to integrate the BusyBox utilities including the installation of DHCP. Plus, how to compile in the OpenSSH package on this CD based system. On system boot-up a filesystem will be created and the contents from the CD will be uncompressed and completely loaded into RAM — the CD could be removed at this point for boot-up on a second computer. The remaining functioning system will have full ssh capabilities. You can take over any PC assuming, of course, you have configured the kernel with the appropriate drivers and the PC can boot from a CD. This tutorial steps you through the whole processes.
Virtual Filesystem: Building A Linux Filesystem From An Ordinary File. You can take a disk file, format it as ext2, ext3, or reiser filesystem and then mount it, just like a physical drive. Yes, it then possible to read and write files to this newly mounted device. You can also copy the complete filesystem, sinc\ e it is just a file, to another computer. If security is an issue, read on. This article will show you how to encrypt the filesystem, and mount it with ACL (Access Control Lists), which give you rights beyond the traditional read (r) write (w) and execute (x) for the 3 user groups file, owner and other.
The Lemon Parser Tutorial: This article explains how to build grammars and programs using the lemon parser, which is faster than yacc. And, unlike yacc, it is thread safe.
How to Compile the 2.6 kernel for Red Hat 9 and 8.0 and get Fedora Updates: This is a step by step tutorial on how to compile the 2.6 kernel from source.
Working With Time: What? There are 61 seconds in a minute? We can go back in time? We still tell time by the sun?
Mike Chirico, a father of triplets (all girls) lives outside of Philadelphia, PA, USA. He has worked with Linux since 1996, has a Masters in Computer Science and Mathematics from Villanova University, and has worked in computer-related jobs from Wall Street to the University of Pennsylvania. His hero is Paul Erdos, a brilliant number theorist who was known for his open collaboration with others.
Mike’s notes page is souptonuts. For open source consulting needs, please send an email to mchirico@comcast.net. All consulting work must include a donation to SourceForge.net.
Источник