Ceph - from "on the knee" to "production"

Choice of CEPH. Part 1

We had five racks, ten optical switches, configured BGP, a couple of dozen SSDs and a bunch of SAS drives of all colors and sizes, as well as proxmox and the desire to put all the static in our own S3 storage. Not that all this was necessary for virtualization, but once you started using opensource, then go in your hobby to the end. The only thing that bothered me was BGP. There is nothing in the world more helpless, irresponsible and immoral than BGP internal routing. And I knew that pretty soon we would plunge into it.

Ceph - from "on the knee" to "production"

The task was banal - there was CEPH, it did not work very well. It had to be done well.
The cluster that I got was heterogeneous, tuned in a hurry and practically not tuned. It consisted of two groups of different nodes, with one common grid acting as both a cluster and a public network. The nodes were filled with four types of disks - two types of SSDs, collected in two separate placement rules, and two types of HDDs of different sizes, collected in a third group. The problem with different sizes was solved by different OSD weights.

The setup itself is divided into two parts - operating system tuning и tuning the CEPH itself and its settings.

OS upgrade

Network

High latency affected both recording and balancing. When writing, because the client will not receive a response about a successful write until data replicas in other placement groups confirm success. Since the rules for distributing replicas in the CRUSH map were one replica per host, the network was always used.

Therefore, the first thing I decided to do was to slightly adjust the current network, in parallel trying to convince me to move to separate networks.

To begin with, I twisted the network card settings. Started by setting up queues:

what happened:

ethtool -l ens1f1

root@ceph01:~# ethtool -l ens1f1
Channel parameters for ens1f1:
Pre-set maximums:
RX:     0
TX:     0
Other:      1
Combined:   63
Current hardware settings:
RX:     0
TX:     0
Other:      1
Combined:   1
root@ceph01:~# ethtool -g ens1f1
Ring parameters for ens1f1:
Pre-set maximums:
RX:     4096
RX Mini:    0
RX Jumbo:   0
TX:     4096
Current hardware settings:
RX:     256
RX Mini:    0
RX Jumbo:   0
TX:     256
root@ceph01:~# ethtool -l ens1f1
Channel parameters for ens1f1:
Pre-set maximums:
RX:     0
TX:     0
Other:      1
Combined:   63
Current hardware settings:
RX:     0
TX:     0
Other:      1
Combined:   1

It can be seen that the current parameters are far from the maximums. Increased:

root@ceph01:~#ethtool -G ens1f0 rx 4096
root@ceph01:~#ethtool -G ens1f0 tx 4096
root@ceph01:~#ethtool -L ens1f0 combined 63

Guided by an excellent article

https://blog.packagecloud.io/eng/2017/02/06/monitoring-tuning-linux-networking-stack-sending-data/

increased the length of the send queue txqueuelen from 1000 to 10 000

root@ceph01:~#ip link set ens1f0  txqueuelen 10000

Well, following the documentation of ceph itself

https://ceph.com/geen-categorie/ceph-loves-jumbo-frames/

increased MTU to 9000.

root@ceph01:~#ip link set dev ens1f0  mtu 9000

Added to /etc/network/interfaces so that all of the above is loaded at startup

cat / etc / network / interfaces

root@ceph01:~# cat /etc/network/interfaces
auto lo
iface lo inet loopback

auto ens1f0
iface ens1f0 inet manual
post-up /sbin/ethtool -G ens1f0 rx 4096
post-up /sbin/ethtool -G ens1f0 tx 4096
post-up /sbin/ethtool -L ens1f0 combined 63
post-up /sbin/ip link set ens1f0  txqueuelen 10000
mtu 9000

auto ens1f1
iface ens1f1 inet manual
post-up /sbin/ethtool -G ens1f1 rx 4096
post-up /sbin/ethtool -G ens1f1 tx 4096
post-up /sbin/ethtool -L ens1f1 combined 63
post-up /sbin/ip link set ens1f1  txqueuelen 10000
mtu 9000

After that, following the same article, I began to thoughtfully twist the handles of the 4.15 kernel. Given that the nodes have 128G RAM, we got a certain configuration file for sysctl

cat /etc/sysctl.d/50-ceph.conf

net.core.rmem_max = 56623104  
#Максимальный размер буфера приема данных для всех соединений  54M
net.core.wmem_max = 56623104
#Максимальный размер буфера передачи данных для всех соединений 54M
net.core.rmem_default = 56623104
#Размер буфера приема данных по умолчанию для всех соединений. 54M
net.core.wmem_default = 56623104
#Размер буфера передачи данных по умолчанию для всех соединений 54M  
# на каждый сокет
net.ipv4.tcp_rmem = 4096 87380 56623104
#Векторная (минимум, по умолчанию, максимум) переменная в файле tcp_rmem
# содержит 3 целых числа, определяющих размер приемного буфера сокетов TCP.
# Минимум: каждый сокет TCP имеет право использовать эту память по 
# факту своего создания. Возможность использования такого буфера 
# гарантируется даже при достижении порога ограничения (moderate memory pressure).
# Размер минимального буфера по умолчанию составляет 8 Кбайт (8192).
#Значение по умолчанию: количество памяти, допустимое для буфера 
# передачи сокета TCP по умолчанию. Это значение применяется взамен
# параметра /proc/sys/net/core/rmem_default, используемого другими протоколами.
# Значение используемого по умолчанию буфера обычно (по умолчанию) 
# составляет 87830 байт. Это определяет размер окна 65535 с 
# заданным по умолчанию значением tcp_adv_win_scale и tcp_app_win = 0, 
# несколько меньший, нежели определяет принятое по умолчанию значение tcp_app_win.
# Максимум: максимальный размер буфера, который может быть автоматически
# выделен для приема сокету TCP. Это значение не отменяет максимума, 
# заданного в файле /proc/sys/net/core/rmem_max. При «статическом»
# выделении памяти с помощью SO_RCVBUF этот параметр не имеет значения.
net.ipv4.tcp_wmem = 4096 65536 56623104
net.core.somaxconn = 5000    
# Максимальное число открытых сокетов, ждущих соединения.
net.ipv4.tcp_timestamps=1
# Разрешает использование временных меток (timestamps), в соответствии с RFC 1323.
net.ipv4.tcp_sack=1
# Разрешить выборочные подтверждения протокола TCP
net.core.netdev_max_backlog=5000 (дефолт 1000)
# максимальное количество пакетов в очереди на обработку, если 
# интерфейс получает пакеты быстрее, чем ядро может их обработать.
net.ipv4.tcp_max_tw_buckets=262144
# Максимальное число сокетов, находящихся в состоянии TIME-WAIT одновременно.
# При превышении этого порога – «лишний» сокет разрушается и пишется
# сообщение в системный журнал.
net.ipv4.tcp_tw_reuse=1
#Разрешаем повторное использование TIME-WAIT сокетов в случаях,
# если протокол считает это безопасным.
net.core.optmem_max=4194304
#Увеличить максимальный общий буфер-космической ALLOCATABLE
#измеряется в единицах страниц (4096 байт)
net.ipv4.tcp_low_latency=1
#Разрешает стеку TCP/IP отдавать предпочтение низкому времени ожидания
# перед более высокой пропускной способностью.
net.ipv4.tcp_adv_win_scale=1
# Эта переменная влияет на вычисление объема памяти в буфере сокета,
# выделяемой под размер TCP-окна и под буфер приложения.
# Если величина tcp_adv_win_scale отрицательная, то для вычисления размера
# используется следующее выражение:
# Bytes- bytes2в степени -tcp_adv_win_scale
# Где bytes – это размер окна в байтах. Если величина tcp_adv_win_scale
# положительная, то для определения размера используется следующее выражение:
# Bytes- bytes2в степени tcp_adv_win_scale
# Переменная принимает целое значение. Значение по-умолчанию – 2, 
# т.е. под буфер приложения отводится ¼ часть объема, определяемого переменной
# tcp_rmem.
net.ipv4.tcp_slow_start_after_idle=0
# механизм перезапуска медленного старта, который сбрасывает значение окна 
# перегрузки, если соединение не использовалось заданный период времени.
# Лучше отключить SSR на сервере, чтобы улучшить производительность 
# долгоживущих соединений.
net.ipv4.tcp_no_metrics_save=1
#Не сохранять результаты измерений TCP соединения в кеше при его закрытии.
net.ipv4.tcp_syncookies=0
#Отключить механизм отправки syncookie
net.ipv4.tcp_ecn=0
#Explicit Congestion Notification (Явное Уведомление о Перегруженности) в 
# TCP-соединениях. Используется для уведомления о возникновении «затора» 
# на маршруте к заданному хосту или сети. Может использоваться для извещения
# хоста-отправителя о необходимости снизить скорость передачи пакетов через
# конкретный маршрутизатор или брандмауэр.
net.ipv4.conf.all.send_redirects=0
# выключает выдачу ICMP Redirect … другим хостам. Эта опция обязательно
# должна быть включена, если хост выступает в роли маршрутизатора любого рода.
# У нас нет маршрутизации.
net.ipv4.ip_forward=0
#Сопсно отключение форвардинга. Мы не шлюз, докер на машинах не поднят,
# нам это не нужно.
net.ipv4.icmp_echo_ignore_broadcasts=1
#Не отвечаем на ICMP ECHO запросы, переданные широковещательными пакетами
net.ipv4.tcp_fin_timeout=10
#определяет время сохранения сокета в состоянии FIN-WAIT-2 после его
# закрытия локальной стороной. Дефолт 60
net.core.netdev_budget=600 # (дефолт 300)
# Если выполнение программных прерываний не выполняются достаточно долго,
# то темп роста входящих данных может превысить возможность ядра 
# опустошить буфер. В результате буферы NIC переполнятся, и трафик будет потерян.
# Иногда, необходимо увеличить длительность работы SoftIRQs
# (программных прерываний) с CPU. За это отвечает netdev_budget. 
# Значение по умолчанию 300. Параметр заставит процесс SoftIRQ обработать
# 300 пакетов от NIC перед тем как отпустить CPU
net.ipv4.tcp_fastopen=3
# TFO TCP Fast Open
# если и клиент и сервер имеют поддержку TFO, о которой сообщают за счет
# специального флага в TCP пакете. В нашем случае является плацебо, просто
# выглядит красиво)

Сluster network was allocated on separate 10Gbps network interfaces into a separate flat network. Each machine was supplied with two-port network cards melanox 10/25 Gbps plugged into two separate 10Gbps switches. Aggregation was carried out using OSPF, since bonding with lacp for some reason showed a total throughput of a maximum of 16 Gbps, while ospf successfully utilized both dozens completely on each machine. Further plans were to use ROCE on these melanoxes to reduce latency. How this part of the network was configured:

  1. Since the machines themselves have external IPs on BGP, we need software - (or rather, at the time of writing, it was frr=6.0-1 ) was already standing.
  2. In total, the machines had two network interfaces, two interfaces each - a total of 4 ports. One network card looked at the factory with two ports and BGP was configured on it, the second looked at two different switches with two ports and OSPF was set on it

More on setting up OSPF: The main task is to aggregate two links and have fault tolerance.
two network interfaces configured in two simple flat networks - 10.10.10.0/24 and 10.10.20.0/24

1: ens1f0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc mq state UP group default qlen 1000
inet 10.10.10.2/24 brd 10.10.10.255 scope global ens1f0
2: ens1f1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9000 qdisc mq state UP group default qlen 1000
inet 10.10.20.2/24 brd 10.10.20.255 scope global ens1f1

by which cars see each other.

DISK

The next step was to optimize disk performance. For SSD, I changed the scheduler to noop, for HDD — deadline. If it’s rough, then NOOP works on the principle of “who gets up first - that’s the slippers”, which in English sounds like “FIFO (First In, First Out)”. Requests are queued as they arrive. DEADLINE is more read-friendly, plus the process from the queue gets almost exclusive access to the disk at the time of the operation. For our system, this is great - after all, only one process works with each disk - the OSD daemon.
(Those who want to dive into the I / O scheduler can read about it here:
http://www.admin-magazine.com/HPC/Articles/Linux-I-O-Schedulers

Those who prefer to read in Russian: https://www.opennet.ru/base/sys/linux_shedulers.txt.html)

In the recommendations for tuning Linux, it is also advised to increase nr_request

nr_requests
The value of nr_requests determines the amount of I/O requests that get buffered before the I/O scheduler sends / receives data to the block device, if you are using a RAID card / Block Device that can handle a larger queue than what the I /O scheduler is set to, raising the value of nr_requests may help to improve throughout and reduce server load when large amounts of I/O occur on the server. If you are using Deadline or CFQ as the scheduler, it is suggested that you should set the nr_request value to 2 times the value of queue depth.

BUT! Citizens themselves, the developers of CEPH, convince us that their system of priorities works better.

Ceph - from "on the knee" to "production"

WBTrottle and/or nr_requests

WBTrottle and/or nr_requests
File storage uses buffered I/O for writing; this brings a number of benefits if the file storage log is on faster media. Client requests are notified as soon as the data is written to the log, and then flushed to the data disk itself at a later time using standard Linux functionality. This makes it possible for OSD spindle drives to provide write latency similar to SSDs when writing in small bursts. This delayed write-back also allows the kernel itself to rearrange I/O requests to disk, with the hope of either merging them together or letting existing disk heads take some better path over their platters. The end effect is that you may be able to squeeze slightly more I/O out of each disk than would be possible with direct or synchronous I/O.

However, a certain problem arises if the volume of incoming writes to a given Ceph cluster outstrips all the capabilities of the underlying disks. In such a scenario, the total number of pending I/Os waiting to be written to disk can grow uncontrollably and result in an I/O queue that fills the entire disk and Ceph queues. Read requests are particularly bad because they get stuck between write requests, which can take several seconds to flush to the primary drive.

To overcome this problem, Ceph has a writeback throttling mechanism built into file storage called WBThrottle. It is designed to limit the total amount of lazy write I/O that can queue up and start their flush process sooner than would normally be enabled by the kernel itself. Unfortunately, testing shows that the defaults may still not cut the behavior to a level that can reduce this impact on read latency. Tweaking can change this behavior and reduce overall write queue lengths and make it possible for the impact to be less severe. However, there is a trade-off: by reducing the total maximum number of entries allowed to be queued, you can reduce the ability of the kernel itself to maximize its efficiency in ordering incoming requests. It's worth thinking a bit about what you need more for your specific application, workloads, and adjust to match.

To control the depth of such a write-back queue, you can either decrease the total maximum backlog of I/Os by applying the WBThrottle setting, or decrease the maximum value for backlogs at the most block level of your kernel. Both can effectively control the same behavior, and it is your preferences that will be the basis for implementing this setting.
It should also be noted that Ceph's operation precedence system is more efficient for shorter disk-level queries. When reducing the overall queue to a given disk, the main queue location is moved to Ceph, where it has more control over what priority an I/O operation has. Consider the following example:

echo 8 > /sys/block/sda/queue/nr_requests

http://onreader.mdl.ru/MasteringCeph/content/Ch09.html#030202

Common

And a few more kernel tweaks to make your car soft and silky to squeeze some more performance out of iron

cat /etc/sysctl.d/60-ceph2.conf

 kernel.pid_max = 4194303
#Дисков в каждой машине по 25, потому рассчитывали что процессов будет много
kernel.threads-max=2097152
# Тредов, естессно, тоже.
vm.max_map_count=524288
# Увеличили количество областей карты памяти процесса. 
# Как следует из документации по ядерным переменным 
# Области карты памяти используется как побочный эффект вызова
# malloc, напрямую с помощью mmap, mprotect и madvise, а также при загрузке
# общих библиотек.
fs.aio-max-nr=50000000
# Подтюним параметры input-output
# Ядро Linux предоставляет функцию асинхронного неблокирующего ввода-вывода (AIO),
# которая позволяет процессу инициировать несколько операций ввода-вывода
# одновременно, не дожидаясь завершения какой-либо из них. 
# Это помогает повысить производительность приложений, 
# которые могут перекрывать обработку и ввод-вывод.
# Параметр aio-max-nr определяет максимальное количество допустимых 
# одновременных запросов.
vm.min_free_kbytes=1048576
# минимальный размер свободной памяти который необходимо поддерживать.
# Выставлен 1Gb, чего вполне достаточно для работы операционной системы, 
# и позволяет избегать OOM Killer для процессов OSD. Хотя памяти и так
# как у дурака фантиков, но запас карман не тянет
vm.swappiness=10
# Говорим использовать своп если осталось свободным 10% памяти.
# На машинах 128G оперативы, и 10% это 12 Гигов. Более чем достаточно для работы.
# Штатный параметр в 60% заставлял тормозить систему, залезая в своп,
# когда есть еще куча свободной памяти
vm.vfs_cache_pressure=1000
# Увеличиваем со штатных 100. Заставляем ядро активнее выгружать
# неиспользуемые страницы памяти из кеша.
vm.zone_reclaim_mode=0
# Позволяет  устанавливать более или менее агрессивные подходы к
# восстановлению памяти, когда в зоне заканчивается память. 
# Если он установлен на ноль, то не происходит восстановление зоны.
# Для файловых серверов или рабочих нагрузок
# выгодно, если их данные кэшированы, zone_reclaim_mode
# оставить отключенным, поскольку эффект кэширования, 
# вероятно, будет более важным, чем местонахождение данных.
vm.dirty_ratio=20
# Процент оперативной памяти, который можно выделить под "грязные" страницы
# Вычисляли из примерного расчета: 
# В система 128 гигов памяти.
# Примерно по 20 дисков SSD, у которых в настройках CEPH указано 
# выделять под кэширование по 3G оперативы.
# Примерно по 40 дисков HDD, для которых этот параметр равен 1G
# 20% от 128 это 25.6 гигов. Итого, в случае максимальной утилизации памяти,
# для системы останется 2.4G памяти. Чего ей должно хватить чтоб выжить и дождаться
# стука копыт кавалерии - то есть пришествия DevOps который все починит.
vm.dirty_background_ratio=3
# процент системной памяти, который можно заполнить dirty pages до того,
# как фоновые процессы pdflush/flush/kdmflush запишут их на диск
fs.file-max=524288
# Ну и открытых файлов у нас,вероятно, будет сильно больше, чем указано по дефолту. 

Immersion in CEPH

Settings that I would like to dwell on in more detail:

cat /etc/ceph/ceph.conf

osd:
journal_aio: true               # Три параметра, включающие 
journal_block_align: true       # прямой i/o
journal_dio: true               # на журнал
journal_max_write_bytes: 1073714824 # Немного растянем максимальный размер
# разово записываемой операции в журнал
journal_max_write_entries: 10000    # Ну и количество одновременных записей
journal_queue_max_bytes: 10485760000 
journal_queue_max_ops: 50000
rocksdb_separate_wal_dir: true      # Решили делать отдельный wal                                                                            
# Даже попытались выбить под это дело                                                                                                                                                                                     
# NVMe
bluestore_block_db_create: true     # Ну и под журнал отдельное устройство
bluestore_block_db_size: '5368709120 #5G'
bluestore_block_wal_create: true
bluestore_block_wal_size: '1073741824   #1G' 
bluestore_cache_size_hdd: '3221225472   # 3G' 
# большой объем оперативы позволяет 
# хранить достаточно большие объемы
bluestore_cache_size_ssd: '9663676416   # 9G' 
keyring: /var/lib/ceph/osd/ceph-$id/keyring
osd_client_message_size_cap: '1073741824 #1G'
osd_disk_thread_ioprio_class: idle
osd_disk_thread_ioprio_priority: 7
osd_disk_threads: 2 # количество тредов у демона на один диск
osd_failsafe_full_ratio: 0.95
osd_heartbeat_grace: 5
osd_heartbeat_interval: 3
osd_map_dedup: true
osd_max_backfills: 2 # количество одновременных операций заполнения на один ОСД.
osd_max_write_size: 256
osd_mon_heartbeat_interval: 5
osd_op_threads: 16
osd_op_num_threads_per_shard: 1
osd_op_num_threads_per_shard_hdd: 2
osd_op_num_threads_per_shard_ssd: 2
osd_pool_default_min_size: 1     # Особенности жадности. Очень быстро стало
osd_pool_default_size: 2         # нехватать места, потому как временное                                                                                                                                                      
# решение приняли уменьшение количество 
# реплик данных
osd_recovery_delay_start: 10.000000
osd_recovery_max_active: 2
osd_recovery_max_chunk: 1048576
osd_recovery_max_single_start: 3
osd_recovery_op_priority: 1
osd_recovery_priority: 1            # параметр регулируем по необходимости на ходу
osd_recovery_sleep: 2
osd_scrub_chunk_max: 4

Some of the parameters that were tested on QA on version 12.2.12 are missing in version ceph 12.2.2, for example osd_recovery_threads. Therefore, the plans included an update on the prod to 12.2.12. Practice has shown compatibility in one cluster of versions 12.2.2 and 12.2.12, which allows you to make a rolling update.

Test cluster

Naturally, for testing it was necessary to have the same version as in the battle, but at the time I started working with the cluster, the repository had only a newer one. After looking at what you can see in the minor version, it’s not very big (1393 lines in configs against 1436 in the new version), we decided to start testing the new one (update anyway, why go on the old stuff)

The only thing that they tried to leave the old version is the package ceph-deploy because some of the utilities (and some of the employees) were tailored to its syntax. The new version was quite different, but it did not affect the operation of the cluster itself, and it was left by the versions 1.5.39

Since the ceph-disk command clearly says that it is deprecated and use the ceph-volume command, dear ones - we started creating OSD with this command, without wasting time on the outdated one.

The plan was as follows - to create a mirror of two SSD disks, on which we will place OSD logs, which, in turn, are located on spindle SASs. So we will insure against data problems when the journal disk crashes.

Create a steel cluster according to the documentation

cat /etc/ceph/ceph.conf

root@ceph01-qa:~# cat /etc/ceph/ceph.conf # положили заранее подготовленный конфиг
[client]
rbd_cache = true
rbd_cache_max_dirty = 50331648
rbd_cache_max_dirty_age = 2
rbd_cache_size = 67108864
rbd_cache_target_dirty = 33554432
rbd_cache_writethrough_until_flush = true
rbd_concurrent_management_ops = 10
rbd_default_format = 2
[global]
auth_client_required = cephx
auth_cluster_required = cephx
auth_service_required = cephx
cluster network = 10.10.10.0/24
debug_asok = 0/0
debug_auth = 0/0
debug_buffer = 0/0
debug_client = 0/0
debug_context = 0/0
debug_crush = 0/0
debug_filer = 0/0
debug_filestore = 0/0
debug_finisher = 0/0
debug_heartbeatmap = 0/0
debug_journal = 0/0
debug_journaler = 0/0
debug_lockdep = 0/0
debug_mon = 0/0
debug_monc = 0/0
debug_ms = 0/0
debug_objclass = 0/0
debug_objectcatcher = 0/0
debug_objecter = 0/0
debug_optracker = 0/0
debug_osd = 0/0
debug_paxos = 0/0
debug_perfcounter = 0/0
debug_rados = 0/0
debug_rbd = 0/0
debug_rgw = 0/0
debug_throttle = 0/0
debug_timer = 0/0
debug_tp = 0/0
fsid = d0000000d-4000-4b00-b00b-0123qwe123qwf9
mon_host = ceph01-q, ceph02-q, ceph03-q
mon_initial_members = ceph01-q, ceph02-q, ceph03-q
public network = 8.8.8.8/28 # адрес изменен, естественно ))
rgw_dns_name = s3-qa.mycompany.ru # и этот адрес измен
rgw_host = s3-qa.mycompany.ru # и этот тоже
[mon]
mon allow pool delete = true
mon_max_pg_per_osd = 300 # больше трехсот плейсмент групп
# на диск не решились
# хотя параметр, естественно, зависит от количества пулов,
# их размеров и количества OSD. Иметь мало но здоровых PG
# тоже не лучший выбор - страдает точность балансировки
mon_osd_backfillfull_ratio = 0.9
mon_osd_down_out_interval = 5
mon_osd_full_ratio = 0.95 # пока для SSD дисков местом для их
# журнала является тот-же девайс что и для ОСД
# решили что 5% от диска (который сам размером 1.2Tb)
#  должно вполне хватить, и коррелирует с параметром
# bluestore_block_db_size плюс вариативность на большие 
# плейсмент группы
mon_osd_nearfull_ratio = 0.9
mon_pg_warn_max_per_osd = 520
[osd]
bluestore_block_db_create = true
bluestore_block_db_size = 5368709120 #5G
bluestore_block_wal_create = true
bluestore_block_wal_size = 1073741824 #1G
bluestore_cache_size_hdd = 3221225472 # 3G
bluestore_cache_size_ssd = 9663676416 # 9G
journal_aio = true
journal_block_align = true
journal_dio = true
journal_max_write_bytes = 1073714824
journal_max_write_entries = 10000
journal_queue_max_bytes = 10485760000
journal_queue_max_ops = 50000
keyring = /var/lib/ceph/osd/ceph-$id/keyring
osd_client_message_size_cap = 1073741824 #1G
osd_disk_thread_ioprio_class = idle
osd_disk_thread_ioprio_priority = 7
osd_disk_threads = 2
osd_failsafe_full_ratio = 0.95
osd_heartbeat_grace = 5
osd_heartbeat_interval = 3
osd_map_dedup = true
osd_max_backfills = 4
osd_max_write_size = 256
osd_mon_heartbeat_interval = 5
osd_op_num_threads_per_shard = 1
osd_op_num_threads_per_shard_hdd = 2
osd_op_num_threads_per_shard_ssd = 2
osd_op_threads = 16
osd_pool_default_min_size = 1
osd_pool_default_size = 2
osd_recovery_delay_start = 10.0
osd_recovery_max_active = 1
osd_recovery_max_chunk = 1048576
osd_recovery_max_single_start = 3
osd_recovery_op_priority = 1
osd_recovery_priority = 1
osd_recovery_sleep = 2
osd_scrub_chunk_max = 4
osd_scrub_chunk_min = 2
osd_scrub_sleep = 0.1
rocksdb_separate_wal_dir = true

# создаем мониторы
root@ceph01-qa:~#ceph-deploy mon create ceph01-q
# генерируем ключи для аутентификации нод в кластере
root@ceph01-qa:~#ceph-deploy gatherkeys ceph01-q
# Это если поштучно. Если у нас несколько машин доступны - те, которые описаны в конфиге в секции 
# mon_initial_members = ceph01-q, ceph02-q, ceph03-q
# можно запустить эти две команды в виде одной
root@ceph01-qa:~#ceph-deploy mon create-initial
# Положим ключи в указанные в конфиге места
root@ceph01-qa:~#cat ceph.bootstrap-osd.keyring > /var/lib/ceph/bootstrap-osd/ceph.keyring 
root@ceph01-qa:~#cat ceph.bootstrap-mgr.keyring > /var/lib/ceph/bootstrap-mgr/ceph.keyring 
root@ceph01-qa:~#cat ceph.bootstrap-rgw.keyring > /var/lib/ceph/bootstrap-rgw/ceph.keyring
# создадим ключ для управления кластером
root@ceph01-qa:~#ceph-deploy admin ceph01-q
# и менеджер, плагинами управлять
root@ceph01-qa:~#ceph-deploy mgr create ceph01-q

The first thing I stumbled about in the work of this version of ceph-deploy with a cluster of version 12.2.12 is an error when trying to create an OSD with db on a software raid -

root@ceph01-qa:~#ceph-volume lvm create --bluestore --data /dev/sde --block.db /dev/md0
blkid could not detect a PARTUUID for device: /dev/md1

Indeed, blkid does not show PARTUUID, I had to create partitions manually:

root@ceph01-qa:~#parted /dev/md0 mklabel GPT 
# разделов будет много, 
# без GPT их создать не получится
# размер раздела мы указали в конфиге выше = bluestore_block_db_size: '5368709120 #5G'
# Дисков у меня 20 под OSD, руками создавать разделы лень
# потому сделал цикл
root@ceph01-qa:~#for i in {1..20}; do echo -e "nnnn+5Gnw" | fdisk /dev/md0; done

It seems that everything is ready, we try to create the OSD again and get the following error (which, by the way, was not reproduced in battle)

when creating a bluestore OSD without specifying the path to WAL, but specifying db

root@ceph01-qa:~#ceph-volume lvm create --bluestore --data /dev/sde --block.db /dev/md0
stderr: 2019-04-12 10:39:27.211242 7eff461b6e00 -1 bluestore(/var/lib/ceph/osd/ceph-0/) _read_fsid unparsable uuid
stderr: 2019-04-12 10:39:27.213185 7eff461b6e00 -1 bdev(0x55824c273680 /var/lib/ceph/osd/ceph-0//block.wal) open open got: (22) Invalid argument
stderr: 2019-04-12 10:39:27.213201 7eff461b6e00 -1 bluestore(/var/lib/ceph/osd/ceph-0/) _open_db add block device(/var/lib/ceph/osd/ceph-0//block.wal) returned: (22) Invalid argument
stderr: 2019-04-12 10:39:27.999039 7eff461b6e00 -1 bluestore(/var/lib/ceph/osd/ceph-0/) mkfs failed, (22) Invalid argument
stderr: 2019-04-12 10:39:27.999057 7eff461b6e00 -1 OSD::mkfs: ObjectStore::mkfs failed with error (22) Invalid argument
stderr: 2019-04-12 10:39:27.999141 7eff461b6e00 -1  ** ERROR: error creating empty object store in /var/lib/ceph/osd/ceph-0/: (22) Invalid argumen

Moreover, if on the same mirror (or in another place, to choose from) create another partition for WAL and specify it when creating the OSD, then everything will go smoothly (except for the appearance of a separate WAL, which you may not have wanted) .

But, since it was still in the distant plans to bring WAL to NVMe, the practice was not superfluous.

root@ceph01-qa:~#ceph-volume lvm create --bluestore --data /dev/sdf --block.wal  /dev/md0p2 --block.db /dev/md1p2

Created monitors, managers and OSD. Now I want to group them in different ways, because I plan to have different types of disks - fast pools on SSD and large, but slow on SAS pancakes.

We will assume that there are 20 disks on the servers, the first ten is one type, the second is another.
The default map looks like this:

ceph osd tree

root@ceph01-q:~# ceph osd tree
ID CLASS WEIGHT TYPE NAME STATUS REWEIGHT PRI-AFF
-1 14.54799 root default
-3 9.09200 host ceph01-q
0 ssd 1.00000 osd.0 up 1.00000 1.00000
1 ssd 1.00000 osd.1 up 1.00000 1.00000
2 ssd 1.00000 osd.2 up 1.00000 1.00000
3 ssd 1.00000 osd.3 up 1.00000 1.00000
4 hdd 1.00000 osd.4 up 1.00000 1.00000
5 hdd 0.27299 osd.5 up 1.00000 1.00000
6 hdd 0.27299 osd.6 up 1.00000 1.00000
7 hdd 0.27299 osd.7 up 1.00000 1.00000
8 hdd 0.27299 osd.8 up 1.00000 1.00000
9 hdd 0.27299 osd.9 up 1.00000 1.00000
10 hdd 0.27299 osd.10 up 1.00000 1.00000
11 hdd 0.27299 osd.11 up 1.00000 1.00000
12 hdd 0.27299 osd.12 up 1.00000 1.00000
13 hdd 0.27299 osd.13 up 1.00000 1.00000
14 hdd 0.27299 osd.14 up 1.00000 1.00000
15 hdd 0.27299 osd.15 up 1.00000 1.00000
16 hdd 0.27299 osd.16 up 1.00000 1.00000
17 hdd 0.27299 osd.17 up 1.00000 1.00000
18 hdd 0.27299 osd.18 up 1.00000 1.00000
19 hdd 0.27299 osd.19 up 1.00000 1.00000
-5 5.45599 host ceph02-q
20 ssd 0.27299 osd.20 up 1.00000 1.00000
21 ssd 0.27299 osd.21 up 1.00000 1.00000
22 ssd 0.27299 osd.22 up 1.00000 1.00000
23 ssd 0.27299 osd.23 up 1.00000 1.00000
24 hdd 0.27299 osd.24 up 1.00000 1.00000
25 hdd 0.27299 osd.25 up 1.00000 1.00000
26 hdd 0.27299 osd.26 up 1.00000 1.00000
27 hdd 0.27299 osd.27 up 1.00000 1.00000
28 hdd 0.27299 osd.28 up 1.00000 1.00000
29 hdd 0.27299 osd.29 up 1.00000 1.00000
30 hdd 0.27299 osd.30 up 1.00000 1.00000
31 hdd 0.27299 osd.31 up 1.00000 1.00000
32 hdd 0.27299 osd.32 up 1.00000 1.00000
33 hdd 0.27299 osd.33 up 1.00000 1.00000
34 hdd 0.27299 osd.34 up 1.00000 1.00000
35 hdd 0.27299 osd.35 up 1.00000 1.00000
36 hdd 0.27299 osd.36 up 1.00000 1.00000
37 hdd 0.27299 osd.37 up 1.00000 1.00000
38 hdd 0.27299 osd.38 up 1.00000 1.00000
39 hdd 0.27299 osd.39 up 1.00000 1.00000
-7 6.08690 host ceph03-q
40 ssd 0.27299 osd.40 up 1.00000 1.00000
41 ssd 0.27299 osd.41 up 1.00000 1.00000
42 ssd 0.27299 osd.42 up 1.00000 1.00000
43 ssd 0.27299 osd.43 up 1.00000 1.00000
44 hdd 0.27299 osd.44 up 1.00000 1.00000
45 hdd 0.27299 osd.45 up 1.00000 1.00000
46 hdd 0.27299 osd.46 up 1.00000 1.00000
47 hdd 0.27299 osd.47 up 1.00000 1.00000
48 hdd 0.27299 osd.48 up 1.00000 1.00000
49 hdd 0.27299 osd.49 up 1.00000 1.00000
50 hdd 0.27299 osd.50 up 1.00000 1.00000
51 hdd 0.27299 osd.51 up 1.00000 1.00000
52 hdd 0.27299 osd.52 up 1.00000 1.00000
53 hdd 0.27299 osd.53 up 1.00000 1.00000
54 hdd 0.27299 osd.54 up 1.00000 1.00000
55 hdd 0.27299 osd.55 up 1.00000 1.00000
56 hdd 0.27299 osd.56 up 1.00000 1.00000
57 hdd 0.27299 osd.57 up 1.00000 1.00000
58 hdd 0.27299 osd.58 up 1.00000 1.00000
59 hdd 0.89999 osd.59 up 1.00000 1.00000

Let's create our own virtual racks and servers with blackjack and other things:

root@ceph01-q:~#ceph osd crush add-bucket rack01 root #создали новый root
root@ceph01-q:~#ceph osd crush add-bucket ceph01-q host #создали новый хост
root@ceph01-q:~#ceph osd crush move ceph01-q root=rack01 #переставили сервер в другую стойку
root@ceph01-q:~#osd crush add 28 1.0 host=ceph02-q # Добавили ОСД в сервер
# Если криво создали то можно удалить
root@ceph01-q:~# ceph osd crush remove osd.4
root@ceph01-q:~# ceph osd crush remove rack01

The problems we encountered in combat cluster, when trying to create a new host and move it to an existing rack - the command ceph osd crush move ceph01-host root=rack01 hung, and the monitors began to fall one by one. Interrupting the command with a simple CTRL+C returned the cluster to the world of the living.

The search turned up the following problem: https://tracker.ceph.com/issues/23386

The solution was to dump the crushmap and remove the section from there rule replicated_ruleset

root@ceph01-prod:~#ceph osd getcrushmap -o crushmap.row #Дампим карту в сыром виде
root@ceph01-prod:~#crushtool -d crushmap.row -o crushmap.txt #переводим в читаемый
root@ceph01-prod:~#vim  crushmap.txt #редактируем, удаляя rule replicated_ruleset
root@ceph01-prod:~#crushtool -c crushmap.txt  -o new_crushmap.row #компилируем обратно
root@ceph01-prod:~#ceph osd setcrushmap -i  new_crushmap.row #загружаем в кластер

Achtung: this operation may cause a placement group rebalance between OSDs. We have it caused, but very small.

And the oddity that we encountered in the test cluster is that after rebooting the OSD server, they forgot that they were moved to new servers and racks, and returned to root default.
As a result, having assembled the final scheme, in which we created a separate root for ssd disks and separately for spindle ones, we pulled all the OSDs along the racks and simply deleted the default root. After the reboot, the OSDs began to stay in their places.
Rummaging later in the documentation found a parameter that is responsible for this behavior. About him in the second part

How we did different groups by types of discs.

To begin with, we created two roots - for ssd and for hdd

root@ceph01-q:~#ceph osd crush add-bucket ssd-root root
root@ceph01-q:~#ceph osd crush add-bucket hdd-root root

Since the servers are physically located in different racks, for convenience, we created racks and there are already servers in them

# Стойки:
root@ceph01-q:~#ceph osd crush add-bucket ssd-rack01 rack
root@ceph01-q:~#ceph osd crush add-bucket ssd-rack02 rack
root@ceph01-q:~#ceph osd crush add-bucket ssd-rack03 rack
root@ceph01-q:~#ceph osd crush add-bucket hdd-rack01 rack
root@ceph01-q:~#ceph osd crush add-bucket hdd-rack01 rack
root@ceph01-q:~#ceph osd crush add-bucket hdd-rack01 rack
# Сервера
root@ceph01-q:~#ceph osd crush add-bucket ssd-ceph01-q host
root@ceph01-q:~#ceph osd crush add-bucket ssd-ceph02-q host
root@ceph01-q:~#ceph osd crush add-bucket ssd-ceph03-q host
root@ceph01-q:~#ceph osd crush add-bucket hdd-ceph01-q host
root@ceph01-q:~#ceph osd crush add-bucket hdd-ceph02-q host
root@ceph01-q:~#ceph osd crush add-bucket hdd-ceph02-q host

and scattered disks according to their types in different servers

root@ceph01-q:~# Диски с 0 по 3 это SSD, находятся в ceph01-q, ставим их в сервер 
root@ceph01-q:~#  ssd-ceph01-q
root@ceph01-q:~#ceph osd crush add 0 1 host=ssd-ceph01-q
root@ceph01-q:~#ceph osd crush add 1 1 host=ssd-ceph01-q
root@ceph01-q:~#ceph osd crush add 2 1 host=ssd-ceph01-q
root@ceph01-q:~#ceph osd crush add 3 1 host=ssd-ceph01-q
root-ceph01-q:~# аналогично с другими серверами

Having scattered the disks over the ssd-root and hdd-root roots, we left the root-default empty, so we can delete it

root-ceph01-q:~#ceph osd crush remove default

Next, we need to create distribution rules that we will bind to the created pools - in the rules we will specify in which root we can put our pool data and the uniqueness level of the replica - for example, replicas must be on different servers, or in different racks (you can even in different root, if we have such a distribution)

Before choosing a type, it is better to read the documentation:
http://docs.ceph.com/docs/jewel/rados/operations/crush-map/#crushmaprules

root-ceph01-q:~#ceph osd crush rule create-simple rule-ssd ssd-root host firstn
root-ceph01-q:~#ceph osd crush rule create-simple rule-hdd hdd-root host firstn
root-ceph01-q:~# Мы указали два правила, в которых данные реплицируются 
root-ceph01-q:~# между хостами - то есть реплика должна лежать на другом хосте,
root-ceph01-q:~# даже если они в одной стойке
root-ceph01-q:~# В продакшене, если есть возможность, лучше распределить хосты
root-ceph01-q:~# по стойкам и указать распределять реплики по стойкам:
root-ceph01-q:~# ##ceph osd crush rule create-simple rule-ssd ssd-root rack firstn

Well, we create pools in which we want to store disk images of our virtualization in the future - PROXMOX:

    root-ceph01-q:~# #ceph osd pool create {NAME} {pg_num}  {pgp_num}
root-ceph01-q:~# ceph osd pool create ssd_pool 1024 1024 
root-ceph01-q:~# ceph osd pool create hdd_pool 1024 1024

And we tell these pools what placement rules to use

 root-ceph01-q:~#ceph osd crush rule ls # смотрим список правил
root-ceph01-q:~#ceph osd crush rule dump rule-ssd | grep rule_id #выбираем ID нужного
root-ceph01-q:~#ceph osd pool set ssd_pool crush_rule 2

The choice of the number of placement groups should be approached with a pre-existing vision for your cluster - how much OSD will be there, how much data (as a percentage of the total) will be in the pool, how much data in total.

In total, it is desirable not to have more than 300 placement groups per disk, and it will be easier to balance with small placement groups - that is, if your entire pool occupies 10 Tb and 10 PG in it - then it will be problematic to balance by throwing terabyte bricks (pg) - pouring sand with a small size grains of sand in buckets are simpler and smoother).

But we must remember that the greater the number of PGs - the more resources are spent on calculating their location - the memory and CPU begin to be utilized.

Approximate understanding can give calculator, provided by the developers of the CEPH documentation.

List of materials:

https://blog.packagecloud.io/eng/2017/02/06/monitoring-tuning-linux-networking-stack-sending-data
http://www.admin-magazine.com/HPC/Articles/Linux-I-O-Schedulers
http://onreader.mdl.ru/MasteringCeph/content/Ch09.html#030202
https://tracker.ceph.com/issues/23386
https://ceph.com/pgcalc/

Source: habr.com

Add a comment