Linux systemd private tmp

Arch Linux

You are not logged in.

#1 2013-03-17 10:33:35

/var/tmp full with systemd-private* directories

Hi,
I’m running a fully updated Arch_64/KDE with a separate 6.2 GB /var partition.
Recently, I’ve noticed my /vat almost full, and it’s not the pacman cache!
Searching (look below) I’ve found /var/tmp to be filled with many directories, all of them with names beginning with «systemd-private».

1. is this OK?
2. Can I (as root) safely delete all those folders (inc. contents) to regain my /var space?

Best regards,
Michael Badt

#2 2013-03-17 10:58:40

Re: /var/tmp full with systemd-private* directories

yes, they are part of systemds’ PrivateTmp feature.

2. Can I (as root) safely delete all those folders (inc. contents) to regain my /var space?

no, these are not supposed to be deleted. Are you sure these directories actually waste space? On my systems all of them are empty.

#3 2013-03-17 11:01:27

Re: /var/tmp full with systemd-private* directories

#4 2013-03-17 12:28:42

Re: /var/tmp full with systemd-private* directories

Thanks all!
One more question:
df -h reports that of the 6.8 available for /var, 6.2 GB is used (see below).
Yet the largest (/var) sub-directory is the tmp which uses only 1.8GB which is WAY SMALLER than the 6.2GB reported above.
Can somebody explain me what’s «eating» my /var space?

Best regards,
Michael Badt

#5 2013-03-17 12:52:00

Re: /var/tmp full with systemd-private* directories

Thanks all!
One more question:
df -h reports that of the 6.8 available for /var, 6.2 GB is used (see below).
Yet the largest (/var) sub-directory is the tmp which uses only 1.8GB which is WAY SMALLER than the 6.2GB reported above.
Can somebody explain me what’s «eating» my /var space?

the number you see is in bytes, meaning that /var/tmp is actually 1,8MB, not GB. This number does not represent the size of the actual directory including its content. It’s only the number of bytes the directory itself uses on the filesystem (or something like that, I’m not sure how exactly this value is calculated, I think this depends on the filesystem as well).
If you want to know what actually uses all that space, you better use something like «du»:

Источник

Php has its own /tmp in /tmp/systemd-private-nABCDE/tmp when accessed through nginx

I found strange behaviour concerning php and /tmp folder. Php uses another folder when it works with /tmp . Php 5.6.7, nginx, php-fpm.

I execute the same script in two ways: via browser and via shell. But when it is launched via browser, file is not in real /tmp folder:

Читайте также:  Активация windows 10 kms activator 2020

php -f script.php

Where is the file? In /tmp

If access it via http://myserver.ru/script.php I get

But where is the file?

Why does php thinks that /tmp should be in /tmp/systemd-private-nABCDE/tmp ?

3 Answers 3

Because systemd is configured to give nginx a private /tmp. If you must use the system /tmp instead for some reason then you will need to modify the .service file to read «PrivateTmp=no».

If you are running multiple sites on the server then I think you’ll want to leave PrivateTmp=yes so that each site remains segregated even in it’s use of temp files. Could be a security issue otherwise, I’d imagine.

Ignacio Vazquez-Abrams have the correct answer, but let me add my functional solution.

I’ve try «multi-user.target.wants» solution, it have worked but after restart, but at some point, PrivateTmp go back to true. Like my principal use of Apache2 is PHP, I finally edited php.ini and I’ve uncomment line sys_temp_dir.

By default system use temp dir assigned by function sys_get_temp_dir. Function sys_get_temp_dir will return «/tmp» but the truth is that your tmp files are storing at some path like /tmp/systemd-private-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-apache2.service-YYYYYY//tmp/*. So, what work for me was:

Источник

Как отключить очистку tmp в Linux

Доброго дня дорогие читатели. Часто бывает что при создании скриптов (иногда и не только для этого) складирую файлы в папку tmp. И как водится после написания кода успешно забываешь в программе поменять пути. Потом пускаешь это в продакшен и все. В общем нужны мне оказались фалы в каталоге tmp, а их там уже не оказалось. Вот метод как отключить очистку tmp в Linux.

В Ubuntu (и прочих Debian-ах)

Чистка директории tmp происходит при загрузке, настройки определены в /etc/default/rcS

В Centos (он же RHEL)

Очистка директории происходит по времени, т.е. зависит от возраста файлов и папок. В RHEL6 за это отвечает /etc/cron.daily/tmpwatch, а в RHEL7 и прочие с systemd используется конфиг /usr/lib/tmpfiles.d/tmp.conf вызываемый сервисом systemd-tmpfiles-clean.service

Пример моего файла tmp.conf в Centos 8

Соответственно в конце строки записи 10d и 30d меняем на нужное количество дней, например 1000d — 1000 дней.

В Gentoo

Параметры очистки содержатся в /etc/conf.d/bootmisc

Конечно можно написать собственный скрипт, который будет запускать по крону и чистить папку. Однако как мне кажется лучше воспользоваться службой встроенной в систему. Дабы не загромождать ОС лишними скриптами

Интересная статья про очистку в Ubuntu, подойдет и для других дистрибутивов Linux.

В данной статье мы рассмотрели как отключить очистку tmp в Linux. Спасибо за внимание.

Источник

tmpfs (Русский)

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

Contents

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

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

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

Читайте также:  Windows server time server sync

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

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

Примеры

По умолчанию раздел TMPFS имеет максимальный размер устанавленный от половины всей вашей оперативной памяти, но это можно настроить. Обратите внимание, что фактическое потребление памяти/подкачки зависит от того, на сколько вы заполните её, так как разделы TMPFS не потребляют память до тех пор, пока это будет на самом деле необходимо.

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

Вот более сложный пример, показывающий, как добавить монтирование TMPFS для пользователей. Это полезно для веб-сайтов, MySQL TMP файлов,

/.vim/ , и многое другое. Очень важно, попытаться получить идеальные параметры монтирования для того, что вы пытаетесь достичь. Цель состоит в том, чтобы получить безопасные параметры, насколько это возможно, чтобы предотвратить повышенное использование. Будет безопасным ограничить размер, указать Uid и GID + mode. Для получения дополнительной информации по этому вопросу, пройдите по ссылкам перечисленным в секции #Смотрите также.

Смотрите справочную страницу mount для получения дополнительной информации. Полезная опция монтирования из справочной страницы является опция default . По крайней мере понятная.

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

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

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

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

Systemd, может автоматически устанавливать /tmp как tmpfs, даже если у вас нет записи в вашем /etc/fstab .

Для отключения автоматического монтирования, выполните следующую команду:

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

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

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

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

Читайте также:  Как полностью русифицировать linux mint 19

Источник

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.

Contents

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 folder 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 folder. 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.

Examples

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:

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

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 :

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:

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 folder automatically when restarting, consider using tmpfiles.d(5) :

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.

Источник

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