Давно не трогал инструменты для секурити.
Оказывается OWASP ZAP научился в Docker и его можно в разных режимах запустить (CLI, web и прочее) + есть Github Actions
https://www.zaproxy.org/docs/docker/about/
https://www.zaproxy.org/docs/docker/webswing/
Оказывается OWASP ZAP научился в Docker и его можно в разных режимах запустить (CLI, web и прочее) + есть Github Actions
https://www.zaproxy.org/docs/docker/about/
https://www.zaproxy.org/docs/docker/webswing/
www.zaproxy.org
ZAP – ZAP Docker User Guide
The world’s most widely used web app scanner. Free and open source. ZAP is a community project actively maintained by a dedicated international team, and a GitHub Top 1000 project.
container-commandos.pdf
26.1 MB
Раскраска Container Commandos 😎
Смотрим список процессов и аптайм в PM2
https://futurestud.io/tutorials/pm2-list-processes-and-show-process-details
https://futurestud.io/tutorials/pm2-list-processes-and-show-process-details
futurestud.io
PM2 — List Processes and Show Process Details
Future Studio provides on-demand learning & wants you to become a better Android (Retrofit, Gson, Glide, Picasso) and Node.js/hapi developer!
https://about.gitlab.com/releases/2020/12/22/gitlab-13-7-released/
Из интересного -
То есть теперь при ручном запуске пайплайна будет предварительный список переменных со стандартными значениями.
Из интересного -
Pre-filled variables when running pipelines manuallyТо есть теперь при ручном запуске пайплайна будет предварительный список переменных со стандартными значениями.
GitLab
GitLab 13.7 released with merge request reviewers and automatic rollback upon failure
GitLab 13.7 released with merge request reviewers, automatic rollback in case of failure, quick action to clone issues, GitLab Runner container on OpenShift, and much more!
На протяжении нескольких недель пришлось плотно поработать с redis.
В результате скопилось несколько заметок, которые могут быть полезными.
Часть 0. Основы работы с Redis
Подключение (в случае с локальным Redis)
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
В результате скопилось несколько заметок, которые могут быть полезными.
Часть 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
Проблемы с производительностью можно определить с помощью команды
Периодически может ещё проявляться такая проблема, но с ней может справиться сам 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:Как видно из проблем выше, Redis сам предлагает решение проблемы.
* 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.
Часть 1. Диагностика Redis
Проблемы с задержкой (latency) можно определить с помощью команды
ВНИМАНИЕ! В некоторых случаях запуск этой команды сам может вызвать задержку.
Перед этим нужно включить latency monitoring. Например, мы хотим видеть запросы, которые блокируют сервер на время 100 и более миллисекунд.
3 поле показывает время выполнения команды в микросекундах.
4 поле показывает саму команду.
В нашем случае это Celery выполняет операцию
Полезные ссылки:
https://redis.io/commands/memory-doctor
https://redis.io/commands/latency-doctor
https://redis.io/topics/latency-monitor
https://redis.io/commands/slowlog
Проблемы с задержкой (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 get2 поле показывает время в формате Unix Epoch (конвертацию времени можно сделать на этом сайте)
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) ""
.......
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
Epochconverter
Epoch Converter
Convert Unix Timestamps (and many other date formats) to regular dates.
Примеры алертов для Prometheus
https://awesome-prometheus-alerts.grep.to/rules
https://awesome-prometheus-alerts.grep.to/rules
Поздравляю всех с наступающим (для кого-то, возможно, уже наступившим) Новым годом!
Пусть все ваши начинания обязательно заканчиваются успехом. Счастья и здоровья вам и вашим семьям.
Пусть Новый год для вас станет годом, в котором вы сможете реализовать все ваши мечты и воплотить в жизнь то, что раньше считали невозможным. Всем добра! Увидимся в следующем году! 💥💥💥
Пусть все ваши начинания обязательно заканчиваются успехом. Счастья и здоровья вам и вашим семьям.
Пусть Новый год для вас станет годом, в котором вы сможете реализовать все ваши мечты и воплотить в жизнь то, что раньше считали невозможным. Всем добра! Увидимся в следующем году! 💥💥💥
https://zelark.github.io/exploring-query-locks-in-postgres/
Десерт в конце - запрос для создания view
Десерт в конце - запрос для создания view
lock_monitor, что позволяет в удобном виде смотреть блокировки и видеть, какой запрос все поломал.Блог Александра Журавлёва
Исследуем блокировки в PostgreSQL
Файл конфигурации Docker-демона со всеми возможными параметрами.
Чтобы не гуглить и не искать ответы на других сайтах, а сразу смотреть в официальной документации.
https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
Чтобы не гуглить и не искать ответы на других сайтах, а сразу смотреть в официальной документации.
https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
Docker Documentation
dockerd
The daemon command description and usage
Вжух, и часть тарифов пропали
https://habr.com/ru/news/t/539498/
https://habr.com/ru/news/t/539498/
Хабр
GitLab изменила тарифы платной подписки и убрала Bronze/Starter
GitLab объявила о крупном обновлении своей модели подписки. Компания отказывается от пакета Bronze/Starter за $4 в месяц. Текущие пользователи смогут продлить действие пакета один раз по существующей...
Большая карта навыков и компетенций для тимлидов. С подробным объяснением и дополнительными ссылками для изучения.
Пригодится не только тимлидам.
https://tlroadmap.io/
Пригодится не только тимлидам.
https://tlroadmap.io/
tlroadmap.io
Teamlead Roadmap
👩🏼💻👨🏻💻Карта навыков и модель развития тимлидов
Дампим все чувствительные данные из Jenkins
https://www.codurance.com/publications/2019/05/30/accessing-and-dumping-jenkins-credentials
https://www.codurance.com/publications/2019/05/30/accessing-and-dumping-jenkins-credentials
Codurance
Accessing and dumping Jenkins credentials | Codurance
Jenkins offers a credentials store where we can keep our secrets. Of someone stole your source code and dumped your databases, you might think it's game over, but that's not always true...
Часть 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
Концепция 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