Записки молодого девопсера
153 subscribers
94 photos
7 files
623 links
Здесь выкладываются различные команды и решения проблем, с которыми приходится сталкиваться, а также интересные статьи и видео из мира IT.
Download Telegram
Давно не трогал инструменты для секурити.
Оказывается 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, что позволяет в удобном виде смотреть блокировки и видеть, какой запрос все поломал.
Файл конфигурации Docker-демона со всеми возможными параметрами.
Чтобы не гуглить и не искать ответы на других сайтах, а сразу смотреть в официальной документации.
https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
Большая карта навыков и компетенций для тимлидов. С подробным объяснением и дополнительными ссылками для изучения.
Пригодится не только тимлидам.
https://tlroadmap.io/
Часть 2. TTL vs Persistent/Eviction policies (maxmemory-policy)

Концепция Redis предполагает, что данные в нем с течением временем могут становиться неактуальными (устаревать), а потом удаляться. Для указания времени жизни ключа в Redis используется команда EXPIRE, который задает интервал времени, после которого ключ будет не будет доступен (удаление происходит не сразу, так как Redis использует механизм отложенного удаления данных. Подробнее). Время жизни ключа можно узнать командой TTL или PTTL.

Также в Redis можно хранить данные без указания TTL - такие данные считаются persistent и удаляются самим Redis только при установке нужной Eviction Policy (об этом позже). Для подобных случаев Redis рекомендует использовать отдельный инстанс для постоянных данных и инстанс для данных с TTL.

При использовании Redis в качестве кэша, рекомендуется дать ему возможность самостоятельно заниматься вытеснять (удалять) старые данные при добавлении новых. До Redis 4.0 LRU (Least Recently Used) являлся единственным поддерживаемым методом вытеснение (eviction). После версии 4.0 появился механизм LFU (Least Frequently Used).

Корректное вытеснение данных возможно только при указании корректных значений директивы maxmemory, которая максимальное количество памяти для хранимых данных. Для 64-битных версий Redis нет ограничений по количеству памяти (maxmemory 0), для 32-битных версий - 3 ГБ. При достижении лимита по памяти срабатывает указанная политика вытеснения (Eviction Policy или директива maxmemory-policy в конфигурации).

Существует следующий набор политик (не перевожу на русский, чтобы не менять смысл):

* noeviction: return errors when the memory limit was reached and the client is trying to execute commands that could result in more memory to be used (most write commands, but DEL and a few more exceptions).

* allkeys-lru: evict keys by trying to remove the less recently used (LRU) keys first, in order to make space for the new data added.

* volatile-lru: evict keys by trying to remove the less recently used (LRU) keys first, but only among keys that have an expire set, in order to make space for the new data added.

* allkeys-random: evict keys randomly in order to make space for the new data added.

* volatile-random: evict keys randomly in order to make space for the new data added, but only evict keys with an expire set.

* volatile-ttl: evict keys with an expire set, and try to evict keys with a shorter time to live (TTL) first, in order to make space for the new data added.

The policies volatile-lru, volatile-random and volatile-ttl behave like noeviction if there are no keys to evict matching the prerequisites.

Соответственно, каждая политика подходит под свою ситуацию и её всегда можно поменять на уже запущенном инстансе. Рекомендации от Redis Labs:
Соответственно, каждая политика подходит под свою ситуацию и её всегда можно поменять на уже запущенном инстансе. Рекомендации от Redis Labs:

* Use the allkeys-lru policy when you expect a power-law distribution in the popularity of your requests, that is, you expect that a subset of elements will be accessed far more often than the rest. This is a good pick if you are unsure.

* Use the allkeys-random if you have a cyclic access where all the keys are scanned continuously, or when you expect the distribution to be uniform (all elements likely accessed with the same probability).

* Use the volatile-ttl if you want to be able to provide hints to Redis about what are good candidate for expiration by using different TTL values when you create your cache objects.

The volatile-lru and volatile-random policies are mainly useful when you want to use a single instance for both caching and to have a set of persistent keys. However it is usually a better idea to run two Redis instances to solve such a problem.

It is also worth noting that setting an expire to a key costs memory, so using a policy like allkeys-lru is more memory efficient since there is no need to set an expire for the key to be evicted under memory pressure.

Полезные ссылки:
EXPIRE
Using Redis as an LRU cache