Записки молодого девопсера
153 subscribers
94 photos
7 files
623 links
Здесь выкладываются различные команды и решения проблем, с которыми приходится сталкиваться, а также интересные статьи и видео из мира IT.
Download Telegram
Рекурсивная замена текста с использованием grep и sed
grep 'your_pattern' .* -rl | xargs sed -i 's/old_pattern/new_pattern/g'
Давно не трогал инструменты для секурити.
Оказывается OWASP ZAP научился в Docker и его можно в разных режимах запустить (CLI, web и прочее) + есть Github Actions
https://www.zaproxy.org/docs/docker/about/
https://www.zaproxy.org/docs/docker/webswing/
https://about.gitlab.com/releases/2020/12/22/gitlab-13-7-released/
Из интересного - Pre-filled variables when running pipelines manually
То есть теперь при ручном запуске пайплайна будет предварительный список переменных со стандартными значениями.
На протяжении нескольких недель пришлось плотно поработать с redis.
В результате скопилось несколько заметок, которые могут быть полезными.

Часть 0. Основы работы с Redis


Подключение (в случае с локальным Redis)
redis-cli

Подключение к удаленному Redis
redis-cli -h hostname/ip -p port

По умолчанию redis-cli работает с БД с индексом 0. Подключиться к другому индексу можно с помощью команды
redis-cli -n index

либо если вы уже вошли в CLI Redis
SELECT index

Получение информации о всех индексах в БД и количестве ключей:
INFO keyspace

Получение значения всех ключей в БД (АХТУНГ!!! НИКОГДА НЕ ИСПОЛЬЗОВАТЬ ЭТО В ПРОДЕ. При выводе большого количества ключей в Redis может значительно упасть производительность).
KEYS *

# ИЛИ
KEYS key:*

Вместо KEYS лучше использовать SCAN
SCAN 0 MATCH *pattern*

Узнать тип ключа
TYPE key

Получить значение ключа типа string
GET key

Получить значение ключа типа set
SMEMBERS key

Получить все поля и их значения для ключа типа hash
HGETALL key

Получить значение ключа типа list (start - номер первого элемента, stop - последнего)
LRANGE key start stop

Удалить ключ
DEL key

Узнать срок жизни ключа в секундах
TTL key

Полезные ссылки:
https://redis.io/commands/select
https://redis.io/commands/info
https://redis.io/commands/keys
https://redis.io/commands/scan
https://redis.io/commands/type
https://redis.io/commands/get
https://redis.io/commands/smembers
https://redis.io/commands/hgetall
https://redis.io/commands/lrange
https://redis.io/commands/del
https://redis.io/commands/ttl
Часть 1. Диагностика Redis

Проблемы
с производительностью можно определить с помощью команды MEMORY DOCTOR (команда вводится в Redis CLI).
MEMORY DOCTOR

Если нет проблем с памятью, то получим следующее сообщение:
Hi Sam, I can't find any memory issue in your instance. I can only account for what occurs on this base.

Проблемы, с которыми пришлось столкнуться ранее:
Sam, I detected a few issues in this Redis instance memory implants:
* High total RSS: This instance has a memory fragmentation and RSS overhead greater than 1.4 (this means that the Resident Set Size of the Redis process is much larger than the sum of the logical allocations Redis performed). This problem is usually due either to a large peak memory (check if there is a peak memory entry above in the report) or may result from a workload that causes the allocator to fragment memory a lot. If the problem is a large peak memory, then there is no issue. Otherwise, make sure you are using the Jemalloc allocator and not the default libc malloc. Note: The currently used allocator is "jemalloc-5.1.0".
* High allocator fragmentation: This instance has an allocator external fragmentation greater than 1.1. This problem is usually due either to a large peak memory (check if there is a peak memory entry above in the report) or may result from a workload that causes the allocator to fragment memory a lot. You can try enabling 'activedefrag' config option.
I'm here to keep you safe, Sam. I want to help you.

Первая проблема решается включением аллокатора памяти jemalloc-5.1.0 (у нас он уже включен). Вторая - включением опции activedefrag.

Периодически может ещё проявляться такая проблема, но с ней может справиться сам Redis
Sam, I detected a few issues in this Redis instance memory implants:

* Peak memory: In the past this instance used more than 150% the memory that is currently using. The allocator is normally not able to release memory after a peak, so you can expect to see a big fragmentation ratio, however this is actually harmless and is only due to the memory peak, and if the Redis instance Resident Set Size (RSS) is currently bigger than expected, the memory will be used as soon as you fill the Redis instance with more data. If the memory peak was only occasional and you want to try to reclaim memory, please try the MEMORY PURGE command, otherwise the only other option is to shutdown and restart the instance.

I'm here to keep you safe, Sam. I want to help you.

Как видно из проблем выше, Redis сам предлагает решение проблемы.
Часть 1. Диагностика Redis

Проблемы с задержкой (latency) можно определить с помощью команды LATENCY DOCTOR.
ВНИМАНИЕ! В некоторых случаях запуск этой команды сам может вызвать задержку.
Перед этим нужно включить latency monitoring. Например, мы хотим видеть запросы, которые блокируют сервер на время 100 и более миллисекунд.
CONFIG SET latency-monitor-threshold 100

Теперь можно запускать команду LATENCY DOCTOR
LATENCY DOCTOR
Dave, I have observed latency spikes in this Redis instance. You don't mind talking about it, do you Dave?

1. command: 19 latency spikes (average 479ms, mean deviation 413ms, period 22234.68 sec). Worst all time event 1287ms.
2. fork: 160 latency spikes (average 107ms, mean deviation 5ms, period 897.12 sec). Worst all time event 172ms. Fork rate is 19.42 GB/sec (poor).

I have a few advices for you:

- If you are using a virtual machine, consider upgrading it with a faster one using an hypervisior that provides less latency during fork() calls. Xen is known to have poor fork() performance. Even in the context of the same VM provider, certain kinds of instances can execute fork faster than others.
- Check your Slow Log to understand what are the commands you are running which are too slow to execute. Please check https://redis.io/commands/slowlog for more information.
- Deleting, expiring or evicting (because of maxmemory policy) large objects is a blocking operation. If you have very large objects that are often deleted, expired, or evicted, try to fragment those objects into multiple smaller objects.

Здесь видно, что есть проблемы с задержкой. Чтобы узнать, какие команды вызывают такую задержку, можно воспользоваться командой slowlog.
slowlog get
1) 1) (integer) 158269
2) (integer) 1609151143
3) (integer) 37189
4) 1) "SUBSCRIBE"
2) "celery-task-meta-f7ccfa18-00c9-4d98-8cca-6ef8a349c8fc"
3) "celery-task-meta-cb3767d0-8e0a-4c71-a26e-0f8496559dc5"
4) "celery-task-meta-4e980170-6abc-4e8f-9f3a-05a0d6add20f"
5) "celery-task-meta-d7a52c77-29af-49ef-8558-a1c8c25bf2ff"
6) "celery-task-meta-73d49c1a-aacc-490e-afc2-c54a383b31b5"
7) "celery-task-meta-b6c1237a-6b7e-427f-9e3e-66bb38438345"
8) "celery-task-meta-22b1f386-462b-4ddf-b8b3-a6f0d7a77732"
...
32) "... (9170 more arguments)"
5) "127.0.0.1:36986"
6) ""
.......

2 поле показывает время в формате Unix Epoch (конвертацию времени можно сделать на этом сайте)
3 поле показывает время выполнения команды в микросекундах.
4 поле показывает саму команду.

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

Полезные ссылки:
https://redis.io/commands/memory-doctor
https://redis.io/commands/latency-doctor
https://redis.io/topics/latency-monitor
https://redis.io/commands/slowlog
Примеры алертов для Prometheus
https://awesome-prometheus-alerts.grep.to/rules
Поздравляю всех с наступающим (для кого-то, возможно, уже наступившим) Новым годом!

Пусть все ваши начинания обязательно заканчиваются успехом. Счастья и здоровья вам и вашим семьям.
Пусть Новый год для вас станет годом, в котором вы сможете реализовать все ваши мечты и воплотить в жизнь то, что раньше считали невозможным. Всем добра! Увидимся в следующем году! 💥💥💥
https://zelark.github.io/exploring-query-locks-in-postgres/
Десерт в конце - запрос для создания view lock_monitor, что позволяет в удобном виде смотреть блокировки и видеть, какой запрос все поломал.