Max locked memory linux

limits.conf и лимиты потребления ресурсов для пользователей в Linux

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

Для текущего момента посмотреть процессы можно при помощи утилиты ps

ps aux —sort=%cpu | grep -v ‘root’ | head -n 35

ps aux —sort=%mem | grep -v ‘root’ | head -n 35

Команды выведут сортированные списки процессов в одной из колонок каждого списка будет указано имя пользователя. Процессы, запущенные от имени root показываться не будут и выведутся только 35 самых активных процессов.

Подобным образом статистику посмотреть не удасться, например, для веб-сервера с mod_php, однаако в большинстве случаев это как раз та информация, которая нужна для того чтобы выбрать пользователей для которых нужно предусмотреть ограничения.

Ограничения нужны на нагруженных серверах, они существует у каждого хостинг провайдера.

Лимитировать количество процессов можно используя механизм ядра cgroups — на практике проще всего установить ограничения отредактировав файл /etc/security/limits.conf и перезагрузив сервер.

Изменять /etc/security/limits.conf может только пользователь root или другой пользователь работающий из под sudo.

Файл хорошо задокументирован, вся необходимая информация находится в нем в комментариях

В общем виде любое правило выглядит так:

domain — это пользователь или группа, для которых лимитируем ресурсы

type — тип ограничения: soft или hard, ограничение soft может быть переопределено пользователем.

item — ресурс, который ограничиваем — обычно это cpu (в минутах) или as — максимальное количество оперативной памяти (в Кб); также можно задать nice level, который не сможет быть превышен процессами пользователя/группы (минимум 20, максимум -19); здесь же можно задать chroot (только для debian)

item — само численное значение

Как уже упоминалось — для того чтобы изменения вступили в силу нужна перезагрузка.

ulimit в Linux и ограничение ресурсов для пользователя

Soft лимиты пользователь может переопределить используя ulimit

Выполнение команды с аргументом -a выведет актуальные ограничения

ulimit -as 1500000
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 14685
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 14685
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited

Ключи из вывода можно брать и использовать в командах, которые будут задавать ограничения для текущей терминальной сессии.

Дополнительно следует указывать тип ограничения:

-H — hard

-S — soft

Если не указывать ничего лимиты будут заданы жестко. hard здесь можно задать для текущего пользователя даже без прав root, но изменения не сохранятся после перезагрузки и чтобы ограничения были установлены постоянно нужно редактировать файл, который был рассмотрен ранее.

Создадим ограничение по оперативной памяти в 1500 Мб для пользователя

Выполнив ulimit -Hm сейчас можно увидеть, что ограничение установлено. Получить ту же информацию можно просмотрев лимиты для процесса

Можно указывать идентификатор любого процесса, запущенного от имени пользователя, для которого задали ограничение по памяти

Источник

ulimit настройка частых проблем в Linux

ulimit — ограничения текущего процесса, например количество одновременно открытых файлов. Справка man limits.conf. Конфигурационный файл находится /etc/security/limits.conf.

Установка лимитов с помощью ulimit может предотвратить катастрофу в ваших системах Linux, но вам нужно предвидеть, где ограничения будут иметь смысл, а где они вызовут проблемы.

Чтобы увидеть ограничения, связанные с вашим логином, используйте команду ulimit -a. Если вы используете учетную запись обычного пользователя, вы, скорее всего, увидите что-то вроде этого:

Изменять лимиты вы можете в конфигурационном файле, обычно /etc/security/limits.conf, или при помощи командной строки. Помните что при изменении лимитов через командную строку, ваши изменения не сохранятся после перезагрузки ОС. Например для изменения максимального количества пользовательских процессов (max user processes) используйте ключ u (из листинга вывода команды ulimit -a):

В limits.conf для каждого пользователя или группы можно задать ограничения. Каждое ограничение задается в отдельной строке. Например для группы developers настроим ограничения пределов открытия файлов, где hard жестко задали количество, а при достижении нижнего предела значения soft пользователи будут получать предупреждения):

Too many open files

Нужно увеличить ограничение на количество одновременно открытых файлов в файле limits.conf.

ulimit размеры файлов

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

Некоторые параметры «зашиты» в ядро системы при ее генерации. Одним из таких значений является максимальный размер файла. Он определяет наибольшее число блоков, которые может занимать файл. Этот параметр тесно связан с принятым в UNIX методом использования индексных дескрипторов файла (inodes). Это наборы указателей, среди которых первые десять указывают на блоки данных, следующий указывает на другую таблицу, следующий — на таблицу, указывающую на таблицу и т.д.

Имеется еще одно ограничение размера файла, которое определено для каждого пользователя во время работы в системе — число ulimit (user limit — пользовательский предел). Это значение устанавливается в момент вашей регистрации в системе и представляет собой число блоков по 512 байт, которые вы можете записать в любой заданный файл. В shell’е имеется команда ulimit, которая при ее вызове без аргументов выводит это число. Эта же команда позволяет вам уменьшить ваше значение ulimit. Только суперпользователь (root) может УВЕЛИЧИТЬ значения ulimit.

Побочным эффектом уменьшения значения ulimit является то, что вы не можете снова увеличить его до регистрационного значения. Значение ulimit остается таким же на все время работы вашего shell, поэтому для восстановления регистрационного значения вам необходимо выйти из системы, а затем снова зарегистрироваться.

Читайте также:  Windows media centre вирус

Еще одним интересным моментом является то, что если вы установите ваше значение ulimit равным 0, вы не сможете создать никакие файлы! Максимально допустимым размером файла в данном случае является нулевой, поэтому никакой файл не может быть создан. Это представляется достаточно резонным, однако существуют такие ситуации, когда файл нулевого размера МОЖЕТ существовать. Опять же, для восстановления вашего обычного значения ulimit необходимо выйти из системы, а затем снова зарегистрироваться.

Как отмечалось ранее, увеличить значение ulimit может только суперпользователь. Эта процедура довольно проста. Сначала нужно увеличить значение ulimit командой ulimit, а затем запустить shell. Этот новый shell имеет новое значение ulimit. Если мы хотим, чтобы система загружалась с shell, имеющим большее значение ulimit, мы можем установить программу в inittab (таблице инициализации системы), чтобы эта операция выполнялась автоматически.

ulimit количество открытых сокетов

Ограничение на количество одновременно открытых сокетов. Обычно, большая часть nix систем ограничивает количество сокетов до 1024. Эти настройки можно изменить добавив в /etc/security/limits.conf следующие строчки:

Также можно установить лимит вручную, через:

Источник

системные настройки высоконагруженного сервера

Настройки Linux по-умолчанию не годятся для высоких нагрузок. Под высокими нагрузками я понимаю от 10000 запросов в секунду. В данной статье рассмотрим два «переключателя», покрутив которые мы добьемся от сервера устойчивости и отзывчивости при высоких нагрузках. Эти переключатели: limits.conf и sysctl.conf

limits.conf

Это конфигурационный файл для pam_limits.so модуля. Он определяет ulimit лимиты для пользователей и групп. В Linux есть системные вызовы: getrlimit() и setrlimit() для получения и установления лимитов на системные ресурсы. Конфигурация по-умолчанию лежит в /etc/security/limits.conf. Также присутствует возможность добавлять отдельные конфиги для приложений в /etc/security/limits.d. Для того, чтобы сервер держал большую нагрузку, нужно увеличить некоторые лимиты. Посмотрим, какие лимиты у нас стоят по-умолчанию. Запустим под рутом.

Обратим внимание на open files, max user processes и max locked memory. Это стандартные ограничения, которые нужно убрать, если хотим держаться под нагрузкой. Перед изменениями хочу предупредить, что если железо недостаточно мощное, то ваш сервер может подвергнуться атаке типа fork bomb, так что аккуратно раздавайте права на сервере.

Приведем /etc/security/limits.conf к такому виду.

В файле мы устанавливаем мягкий и жесткий лимиты на количество запущенных процессов, открытых файлов (читай портов) для всех пользователей и неограниченный лок памяти для рута.

Хочу поподробнее рассказать, почему для открытых файлов было выбрано ограничение в 1048576. Это волшебное число захардкожено в ядре, чтоб поставить больше, нужно пересобирать ядро. Более развернуто на эту тему отвечают на stackoverflow и вот здесь.

Изменения вступят в силу или после перезагрузки или после нового логина или создания сессии ssh. Проверить, включается ли модуль pam_limits можно в файлах /etc/pam.d Для Debian есть статья в wiki на эту тему: https://wiki.debian.org/Limits

sysctl.conf

В /etc/sysctl.conf настраиваются параметры ядра, модулей и других подсистем. По сути, можно вручную менять значения псевдо-фс /proc, но такие изменения не сохранятся после перезагрузки, поэтому будем сразу вносить изменения в этот конфиг файл.

Для пользователей systemd этот файл уже не играет роли. Если вы вдруг используете systemd, вам нужно править файлы в /etc/sysctl.d/. Подробнее читайте на http://www.freedesktop.org/software/systemd/man/sysctl.d.html

Вот пример моего sysctl.conf для высоконагруженной системы.

Подробно про все опции, можно прочитать в

Или, например, здесь. А тут написано как люди выдерживают миллион pps в секунду и приведены примеры используемых sysctl.conf

После изменения sysctl.conf применим наши правки.

После перезагрузки все изменения будут применяться автоматически.

Заключение

Все вышеописанное применялось мной на работе для высоконагруженного сервера, который перед выкаткой в прод тестировался замечательным Yandex танком и держал нагрузку порядка 20000 rps. Стоит учесть, что сам по себе Linux не обеспечит вам стойкости под нагрузкой, если ваш софт ломается при 100 rps. Тут уже вас может спасти балансировка нагрузки. Смотрите в сторону HAProxy, LVS, Keepalived. Удачного прохождения высоких нагрузок!

Источник

G Very Large Memory and HugePages

This chapter guides Linux system administrators to configure very large memory configurations and HugePages on Linux systems.

This chapter contains the following sections:

G.1 Very Large Memory on Linux x86

Very Large Memory (VLM) configurations allow a 32-bit Oracle Database to access more than 4GB RAM that is traditionally available to Linux applications. The Oracle VLM option for 32-bit creates a large database buffer cache using an in-memory file system ( /dev/shm ). Other parts of the SGA are allocated from regular memory. VLM configurations improve database performance by caching more database buffers in memory, which significantly reduces the disk I/O compared to configurations without VLM. This chapter shows how to increase the SGA memory using VLM on a 32-bit computer.

The contents documented in this section apply only to 32-bit Linux operating system. With a 64-bit architecture, VLM support is available natively. All 64-bit Linux operating systems use the physical memory directly, as the maximum available virtual address space is 16 EB (exabyte = 2^60 bytes.)

This section includes the following topics:

G.1.1 Implementing VLM on 32-bit Linux

With 32-bit architectures, VLM is accessed through a VLM window of a specific size. The VLM window is a data structure in the process address space that provides access to the whole virtual address space from a window of a specific size. On 32-bit Linux, you must set the parameter USE_INDIRECT_DATA_BUFFERS=TRUE , and mount a shmfs or tmpfs or ramfs type of in-memory filesystem over /dev/shm to increase the usable address space.

G.1.2 Prerequisites for Implementing VLM

The following are some of the prerequisites for implementing VLM on a 32-bit operating system:

The computer on which Oracle Database is installed must have more than 4GB of memory.

The computer must be configured to use a kernel with PAE support upon startup.

The USE_INDIRECT_DATA_BUFFERS=TRUE must be present in the initialization parameter file for the database instance that uses VLM support.

Initialization parameters DB_BLOCK_BUFFERS and DB_BLOCK_SIZE must be set to values you have chosen for the Oracle Database.

G.1.3 Methods To Increase SGA Limits

In a typical 32-bit Linux kernel, one can create an SGA of up to 2.4GB size. Using a Linux Hugemem kernel enables the creation of an SGA of upto 3.2GB size. To go beyond 3.2GB on a 32-bit kernel, you must use the VLM feature.

The following are the methods to increase SGA limits on a 32-bit computer:

G.1.3.1 Hugemem Kernel

Red Hat Enterprise Linux 4 and Oracle Linux 4 include a new kernel known as the Hugemem kernel. The Hugemem kernel feature is also called a 4GB-4GB Split Kernel as it supports a 4GB per process user space (versus 3GB for the other kernels), and a 4GB direct kernel space. Using this kernel enables RHEL 4/Oracle Linux 4 to run on systems with up to 64GB of main memory. The Hugemem kernel is required to use all the memory in system configurations containing more than 16GB of memory. The Hugemem kernel can run configurations with less memory.

Читайте также:  Nvidia gf117 windows 10

A classic 32-bit 4GB virtual address space is split 3GB for user processes and 1GB for the kernel. The new scheme (4GB/4GB) permits 4GB of virtual address space for the kernel and almost 4GB for each user process. Due to this scheme with hugemem kernel, 3.2GB of SGA can be created without using the indirect data buffer method.

Red Hat Enterprise Linux 5/ Oracle Linux 5 and Red Hat Enterprise Linux 6/ Oracle Linux 6 on 32-bit does not have the hugemem kernel. It supports only the 3GB user process/ 1GB kernel split. It has a PAE kernel that supports systems with more than 4GB of RAM and reliably upto 16GB. Since this has a 3GB/1GB kernel split, the system may run out of lowmem if the system’s load consumes lots of lowmem. There is no equivalent kernel for hugemem in Enterprise Linux 5 and one is recommended to either use Enterprise Linux 4 with hugemem or go for 64-bit.

The Hugemem kernel on large computers ensures better stability as compared to the performance overhead of address space switching.

Run the following command to determine if you are using the Hugemem kernel:

G.1.3.2 Hugemem Kernel with Very Large Memory

If you use only Hugemem kernels on 32-bit systems, then the SGA size can be increased but not significantly. Refer to section «Hugemem Kernel», for more information.

Red Hat Enterprise Linux 5/ Oracle Linux 5 and Red Hat Enterprise Linux 6/ Oracle Linux 6 does not support the hugemem kernel. It supports a PAE kernel that can be used to implement Very Large Memory (VLM) as long as the physical memory does not exceed 16GB.

This section shows how the SGA can be significantly increased by using Hugemem kernel with VLM on 32-bit systems.

The SGA can be increased to about 62GB (depending on block size) on a 32-bit system with 64GB RAM. A processor feature called Page Address Extension (PAE) permits you to physically address 64GB of RAM. Since PAE does not enable a process or program to either address more than 4GB directly, or have a virtual address space larger than 4GB, a process cannot attach to shared memory directly. To address this issue, a shared memory filesystem (memory-based filesystem) must be created which can be as large as the maximum allowable virtual memory supported by the kernel. With a shared memory filesystem processes can dynamically attach to regions of the filesystem allowing applications like Oracle to have virtually a much larger shared memory on 32-bit operating systems. This is not an issue on 64-bit operating systems.

VLM moves the database buffer cache part of the SGA from the System V shared memory to the shared memory filesystem. It is still considered one large SGA but it consists now of two different operating system shared memory entities. VLM uses 512MB of the non-buffer cache SGA to manage VLM. This memory area is needed for mapping the indirect data buffers (shared memory filesystem buffers) into the process address space since a process cannot attach to more than 4GB directly on a 32-bit system.

USE_INDIRECT_DATA_BUFFERS = TRUE must be present in the initialization parameter file for the database instance that use Very Large Memory support. If this parameter is not set, then Oracle Database 11 g Release 2 (11.2) or later behaves in the same way as previous releases.

You must also manually set the initialization parameters DB_BLOCK_BUFFERS and SHARED_POOL_SIZE to values you have chosen for an Oracle Database. Automatic Memory Management (AMM) cannot be used. The initialization parameter DB_BLOCK_SIZE sets the block size and in combination with DB_BLOCK_BUFFERS determines the buffer cache size for an instance

For example, if the non-buffer cache SGA is 2.5GB, then you will only have 2GB of non-buffer cache SGA for shared pool, large pool, and redo log buffer since 512MB is used for managing VLM. It is not recommended to use VLM if buffer cache size is less than 512MB.

In RHEL 4/ Oracle Linux 4 there are two different memory file systems that can be used for VLM:

tmpfs or shmfs : mount a shmfs with a certain size to /dev/shm , and set the correct permissions. For tmpfs you do not need to specify a size. Tmpfs or shmfs allocated memory is pageable.

ramfs : ramfs is similar to shmfs , except that pages are not pageable or swappable. This approach provides the commonly desired effect. ramfs is created by:

G.1.4 Configuring Very Large Memory for Oracle Database

Complete the following procedure to configure Very Large Memory on Red Hat Enterprise Linux 4/ Oracle Linux 4 using ramfs :

Log in as a root user:

Edit the /etc/rc.local file and add the following entries to it to configure the computer to mount ramfs over the /dev/shm directory, whenever you start the computer:

In the preceding commands, oracle is the owner of Oracle software files and oinstall is the group for Oracle owner account. If the new configuration disables /etc/rc.local file or you start an instance of Oracle database using a Linux service script present under the /etc/init.d file, then you can add those entries in the service script too.

Note, this configuration will make ramfs ready even before your system autostarts crucial Oracle Database instances. The commands can also be included in your startup scripts. It is important that you test the commands extensively by repeated restart action, after you complete configuring the computer using the following steps:

Restart the server.

Log in as a root user.

Run the following command to check if the /dev/shm directory is mounted with the ramfs type:

Run the following command to check the permissions on the /dev/shm directory:

Edit the /etc/security/limits.conf file and add the following entries to it to increase the max locked memory limit:

Switch to the oracle user:

Читайте также:  Stream with vlc linux

Run the following command to check the max locked memory limit:

Complete the following procedure to configure instance parameters for Very Large Memory:

Replace the DB_CACHE_SIZE , DB_xK_CACHE_SIZE , sga_target , and memory_target parameters with DB_BLOCK_BUFFERS parameter.

Add the USE_INDIRECT_DATA_BUFFERS=TRUE parameter.

Configure SGA size according to the SGA requirements.

Remove SGA_TARGET , MEMORY_TARGET , or MEMORY_MAX_TARGET parameters, if set.

Start the database instance.

Run the following commands to check the memory allocation:

«Configuring HugePages on Linux» section for more information about HugePages.

G.1.5 Restrictions Involved in Implementing Very Large Memory

Following are the limitations of running a computer in the Very Large Memory mode:

You cannot use Automatic Memory Management (AMM) while implementing VLM using ramfs , because AMM works on dynamic SGA tuning. With AMM swapping is possible. For example, you can unmap the unused SGA space and map it to PGA. Dynamic SGA and multiple block size are not supported with Very Large Memory because ramfs is not swappable. To enable Very Large Memory, you must ensure that you set the value of MEMORY_TARGET to zero.

VLM can be implemented only if Database Buffer Cache size is greater than 512MB.

G.2 Overview of HugePages

HugePages is a feature integrated into the Linux kernel 2.6. Enabling HugePages makes it possible for the operating system to support memory pages greater than the default (usually 4KB). Using very large page sizes can improve system performance by reducing the amount of system resources required to access page table entries. HugePages is useful for both 32-bit and 64-bit configurations. HugePage sizes vary from 2MB to 256MB, depending on the kernel version and the hardware architecture. For Oracle Databases, using HugePages reduces the operating system maintenance of page states, and increases Translation Lookaside Buffer (TLB) hit ratio.

This section includes the following topics:

G.2.1 Tuning SGA With HugePages

Without HugePages, the operating system keeps each 4KB of memory as a page, and when it is allocated to the SGA, then the lifecycle of that page (dirty, free, mapped to a process, and so on) is kept up to date by the operating system kernel.

With HugePages, the operating system page table (virtual memory to physical memory mapping) is smaller, since each page table entry is pointing to pages from 2MB to 256MB. Also, the kernel has fewer pages whose lifecyle must be monitored.

2MB size of HugePages is available with Linux x86-64, Linux x86, and IBM: Linux on System z.

The following are the advantages of using HugePages:

Increased performance through increased TLB hits.

Pages are locked in memory and are never swapped out which guarantees that shared memory like SGA remains in RAM.

Contiguous pages are preallocated and cannot be used for anything else but for System V shared memory (for example, SGA)

Less bookkeeping work for the kernel for that part of virtual memory due to larger page sizes

G.2.2 Configuring HugePages on Linux

Complete the following steps to configure HugePages on the computer:

Edit the memlock setting in the /etc/security/limits.conf file. The memlock setting is specified in KB and set slightly lesser than the installed RAM. For example, if you have 64GB RAM installed, add the following entries to increase the max locked memory limit:

You can also set the memlock value higher than your SGA requirements.

Login as the oracle user again and run the ulimit -l command to verify the new memlock setting:

Run the following command to display the value of Hugepagesize variable:

Complete the following procedure to create a script that computes recommended values for hugepages configuration for the current shared memory segments:

Following is an example that may require modifications.

Create a text file named hugepages_settings.sh .

Add the following content in the file:

Run the following command to change the permission of the file:

Run the hugepages_settings.sh script to compute the values for hugepages configuration:

Set the following kernel parameter:

To make the value of the parameter available for every time you restart the computer, edit the /etc/sysctl.conf file and add the following entry:

Restart the server.

To check the available hugepages , run the following command:

G.2.3 Restrictions for HugePages Configurations

Following are the limitations of using HugePages:

Automatic Memory Management (AMM) and HugePages are not compatible. When you use AMM, the entire SGA memory is allocated by creating files under /dev/shm . When Oracle Database allocates SGA with AMM, HugePages are not reserved. To use HugePages on Oracle Database 12 c , You must disable AMM.

If you are using VLM in a 32-bit environment, then you cannot use HugePages for the Database Buffer cache. You can use HugePages for other parts of the SGA, such as shared_pool , large_pool , and so on. Memory allocation for VLM (buffer cache) is done using shared memory file systems ( ramfs/tmpfs/shmfs ). Memory file systems do not reserve or use HugePages.

HugePages are not subject to allocation or release after system startup, unless a system administrator changes the HugePages configuration, either by modifying the number of pages available, or by modifying the pool size. If the space required is not reserved in memory during system startup, then HugePages allocation fails.

G.2.4 Disabling Transparent HugePages

Transparent HugePages memory is enabled by default with Red Hat Enterprise Linux 6, SUSE 11, and Oracle Linux 6 with earlier releases of Oracle Linux Unbreakable Enterprise Kernel 2 (UEK2) kernels. Transparent HugePages memory is disabled by default in later releases of UEK2 kernels.

Transparent HugePages can cause memory allocation delays at runtime. To avoid performance issues, Oracle recommends that you disable Transparent HugePages on all Oracle Database servers. Oracle recommends that you instead use standard HugePages for enhanced performance.

Transparent HugePages memory differs from standard HugePages memory because the kernel khugepaged thread allocates memory dynamically during runtime. Standard HugePages memory is pre-allocated at startup, and does not change during runtime.

To check if Transparent HugePages is enabled run one of the following commands as the root user:

Red Hat Enterprise Linux kernels:

The following is a sample output that shows Transparent HugePages is being used as the [always] flag is enabled.

If Transparent HugePages is removed from the kernel then the /sys/kernel/mm/transparent_hugepage or /sys/kernel/mm/redhat_transparent_hugepage files do not exist.

To disable Transparent HugePages perform the following steps:

Источник

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