Linux var in tmpfs

mount /var/log as tmpfs in Linux

My current laptop hard drive (Seagate ST940818SM) is slow (max 42MB/s R/W speed) and out of space. Mounting /tmp and /var/tmp as tmpfs does a lot of performance improvement. So is it safe to mount /var/log as tmpfs? I don’t care about logs on my laptop. Will it improve battery backup time somewhat? As log files are on RAM, this allows complete hard drive spin down during no activity period.

Do you write much to /var/log anyway? Also, some programs write to subdirectories under /var/log and may be upset when these suddenly disappear after a reboot.

1 Answer 1

Technically, you can mount /var/log as tmpfs. You’d need to be sure that /var/log is mounted before syslogd starts, but that’s the case by default on most distributions since they support /var on a separate partition.

You’ll obviously lose all logs, which I guarantee will be a problem one day. Logs are there for a purpose — there’re rarely needed, but they’re there when they’re needed. For example, if your system crashes, what was it doing before the crash? Since when has this package been incstalled? When did I print this document? etc.

You won’t gain much disk space: logs don’t take much space relative to a hard disk. Check how much space they use on your system; I’d expect something like 0.1% of the disk size.

You won’t gain any performance. Logs amount to a negligible part of disk bandwidth on a normal desktop-type configuration.

The only gain would be to allow the disk to stay down, rather than spin up all the time to write new log entries. Spinning the disk down doesn’t save much electricity if any: the hard disk is only a small part of a laptop power consumption, and spinning up requires a power surge. Furthermore spin cycles wear down the disk, so don’t spin down too often. The main reason to spin down is the noise.

Rather than putting logs on tmpfs, arrange for your disk not to spin up when a file is written. Install Laptop Mode, which causes writes to disk to be suspended while the disk is spun down — only a full write buffer, an explicit sync or a disk read will spin the disk back up.

Depending on your configuration, you may need to instruct the syslog daemon not to call sync after each write. With the traditional syslog daemon, make sure that all file names in /etc/syslog.conf have — before them, e.g.

auth,authpriv.* -/var/log/auth.log 

With rsyslog, also make sure that log file names have — before them; the log files are configured in /etc/rsyslog.conf and /etc/rsyslog.d/* .

Читайте также:  Запустить openvpn server linux

Источник

tmpfs (Русский)

Состояние перевода: На этой странице представлен перевод статьи tmpfs. Дата последней синхронизации: 6 мая 2022. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

tmpfs — это временная файловая система, которая находится в памяти и/или вашем разделе(ах) подкачки, в зависимости от того, насколько вы её заполнили. Монтирование каталогов как TMPFS — это эффективный способ ускорения доступа к своим файлам. Также это полезно, если вам нужно, чтобы содержимое каталогов автоматически удалялось при перезагрузке.

Совет: Можно создавать временные файлы в каталогах tmpfs при загрузке системы с помощью systemd-tmpfiles.

Использование

Некоторые каталоги, где обычно используется tmpfs(5) : /tmp, /var/lock и /var/run. Не используйте его на /var/tmp, так как этот каталог предназначен для временных файлов, которые сохраняются после перезагрузки.

Arch использует tmpfs в каталоге /run , с симлинками для совместимости /var/run и /var/lock . Он также используется для /tmp в настройках по умолчанию systemd и не требует записи в fstab, если не требуется конкрентная настройка.

glibc 2.2 и выше ожидает что /dev/shm будет смонтирован tmpfs для POSIX разделяемой памяти. Монтирование /dev/shm в tmpfs выполняется автоматически systemd, поэтому ручная настройка в fstab больше не требуется.

Как правило, задачи и программы, которые выполняют частые операции чтения/записи, могут выиграть от использования каталога tmpfs. Некоторые приложения могут даже получить существенную выгоду при переносе некоторых (или всех) их данных на общую память. Например, перемещение профиля Firefox в оперативную память показывает значительное улучшение производительности.

Примеры

Примечание: Фактическое потребление памяти/подкачки зависит от того, насколько вы заполните разделы tmpfs, поскольку они не потребляют память до тех пор, пока она действительно не понадобится.

По умолчанию раздел tmpfs имеет максимальный размер в половину от всей оперативной памяти, но это можно настроить. Чтобы точно установить максимальный размер, в данном примере, чтобы переопределить значение по умолчанию для монтирования /tmp , используем опцию монтирования size :

tmpfs /tmp tmpfs rw,nodev,nosuid,size=2G 0 0

Пример с опциями монтирования для большей безопасности:

tmpfs /www/cache tmpfs rw,size=1G,nr_inodes=5k,noexec,nodev,nosuid,uid=пользователь,gid=группа,mode=1700 0 0

Смотрите tmpfs(5) и Безопасность#Файловые системы для более подробной информации.

Перезагрузитесь, для того чтобы изменения вступили в силу. Обратите внимание, что может быть заманчивым, выполнить mount -a , чтобы сделанные изменения вступили в силу немедленно, это сделает недоступными какие-либо файлы, которые в настоящее время находятся в этих каталогах (например, особенно проблематично для запуска программ с файлами блокировки). Тем не менее, если все они пусты, она должна быть безопасной для запуска mount -a , вместо перезагрузки (или смонтируйте их в индивидуальном порядке).

После применения изменений, вы можете убедиться в том, что они вступили в силу, посмотрев в /proc/mounts и используя findmnt :

TARGET SOURCE FSTYPE OPTIONS /tmp tmpfs tmpfs rw,nosuid,nodev,relatime

TMPFS также может быть временно изменен, без необходимости в перезагрузке, например, когда в ближайшее время необходимо выполнить большую работу компиляции. В этом случае вы можете запустить:

# mount -o remount,size=4G /tmp

Отключить автоматическое монтирование

systemd автоматически монтирует /tmp как tmpfs, даже если нет записи в /etc/fstab . Для отключения автоматического монтирования замаскируйте юнит tmp.mount .

Читайте также:  Папка cache в линукс

После этого файлы в /tmp станут храниться не в памяти, а на блочном устройстве. Содержимое /tmp теперь будет сохраняться между перезагрузками, что может быть нежелательно. Чтобы вернуть прежнее поведение и очищать каталог /tmp автоматически при перезагрузке, можно использовать tmpfiles.d(5) :

# смотрите tmpfiles.d(5) # очистка каталога /tmp всегда включена D! /tmp 1777 root root 0 # удалить файлы в каталоге /var/tmp старше 10 дней D /var/tmp 1777 root root 10d # namespace mountpoints (PrivateTmp=yes) are excluded from removal x /tmp/systemd-private-* x /var/tmp/systemd-private-* X /tmp/systemd-private-*/tmp X /var/tmp/systemd-private-*/tmp

Решение проблем

Не получается открытие символьных ссылок в tmpfs от root

Предполагая, что /tmp использует tmpfs, измените текущий каталог на /tmp , а затем создайте файл и создайте символическую ссылку на этот файл в том же каталоге /tmp . При попытке прочитать файл по символической ссылке иногда может возникать ошибка «Отказано в доступе». Это ожидаемое поведение, так как /tmp имеет установленный sticky bit.

Поведение можно настроить через /proc/sys/fs/protected_symlinks или просто с помощью sysctl: sysctl -w fs.protected_symlinks=0 . Чтобы сделать изменение постоянным, смотрите sysctl (Русский)#Настройка.

Важно: Изменение этого поведения может привести к проблемам безопасности! Отключите это, только если вы знаете что делаете.

Смотрите также

Источник

tmpfs

tmpfs is a temporary filesystem that resides in memory and/or swap partition(s). Mounting directories as tmpfs can be an effective way of speeding up accesses to their files, or to ensure that their contents are automatically cleared upon reboot.

Usage

Some directories where tmpfs(5) is commonly used are /tmp, /var/lock and /var/run. Do not use it on /var/tmp, because that directory is meant for temporary files that are preserved across reboots.

Arch uses a tmpfs /run directory, with /var/run and /var/lock simply existing as symlinks for compatibility. It is also used for /tmp by the default systemd setup and does not require an entry in fstab unless a specific configuration is needed.

glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for POSIX shared memory. Mounting tmpfs at /dev/shm is handled automatically by systemd and manual configuration in fstab is not necessary.

Generally, tasks and programs that run frequent read/write operations can benefit from using a tmpfs directory. Some applications can even receive a substantial gain by offloading some (or all) of their data onto the shared memory. For example, relocating the Firefox profile into RAM shows a significant improvement in performance.

Читайте также:  Криптопро серверная лицензия linux

Examples

Note: The actual memory/swap consumption depends on how much is used, as tmpfs partitions do not consume any memory until it is actually needed.

By default, a tmpfs partition has its maximum size set to half of the available RAM, however it is possible to overrule this value. To explicitly set a maximum size, in this example to override the default /tmp mount, use the size mount option:

tmpfs /tmp tmpfs rw,nodev,nosuid,size=2G 0 0

To specify a more secure mounting, specify the following mount option:

tmpfs /www/cache tmpfs rw,size=1G,nr_inodes=5k,noexec,nodev,nosuid,uid=user,gid=group,mode=1700 0 0

See the tmpfs(5) man page and Security#File systems for more information.

Reboot for the changes to take effect. Note that although it may be tempting to simply run mount -a to make the changes effective immediately, this will make any files currently residing in these directories inaccessible (this is especially problematic for running programs with lockfiles, for example). However, if all of them are empty, it should be safe to run mount -a instead of rebooting (or mount them individually).

After applying changes, verify that they took effect by looking at /proc/mounts and using findmnt :

TARGET SOURCE FSTYPE OPTIONS /tmp tmpfs tmpfs rw,nosuid,nodev,relatime

The tmpfs can also be temporarily resized without the need to reboot, for example when a large compile job needs to run soon. In this case, run:

# mount -o remount,size=4G /tmp

Disable automatic mount

Under systemd, /tmp is automatically mounted as a tmpfs, if it is not already a dedicated mountpoint (either tmpfs or on-disk) in /etc/fstab . To disable the automatic mount, mask the tmp.mount systemd unit.

Files will no longer be stored in a tmpfs, but on the block device instead. The /tmp contents will now be preserved between reboots, which might not be the desired behavior. To regain the previous behavior and clean the /tmp directory automatically when restarting, consider using tmpfiles.d(5) :

# see tmpfiles.d(5) # always enable /tmp directory cleaning D! /tmp 1777 root root 0 # remove files in /var/tmp older than 10 days D /var/tmp 1777 root root 10d # namespace mountpoints (PrivateTmp=yes) are excluded from removal x /tmp/systemd-private-* x /var/tmp/systemd-private-* X /tmp/systemd-private-*/tmp X /var/tmp/systemd-private-*/tmp

Troubleshooting

Considering /tmp is using tmpfs, change the current directory to /tmp , then create a file and create a symlink to that file in the same /tmp directory. Permission denied errors are to be expected when attempting to read the symlink due to /tmp having the sticky bit set.

This behavior can be controlled via /proc/sys/fs/protected_symlinks or simply via sysctl: sysctl -w fs.protected_symlinks=0 . See Sysctl#Configuration to make this permanent.

See also

Источник

Оцените статью
Adblock
detector