MySQL memory usage

Script to get information about used memory by a MySQL server

ubuntu@localhost:~$ ./mysql-memusage.sh
+------------------------------------------+--------------------+
|                          key_buffer_size |           8.000 MB |
|                         query_cache_size |           0.000 MB |
|                  innodb_buffer_pool_size |       65536.000 MB |
|          innodb_additional_mem_pool_size |           0.000 MB |
|                   innodb_log_buffer_size |        2048.000 MB |
+------------------------------------------+--------------------+
|                              BASE MEMORY |       67592.000 MB |
+------------------------------------------+--------------------+
|                         sort_buffer_size |           0.250 MB |
|                         read_buffer_size |           0.125 MB |
|                     read_rnd_buffer_size |           0.250 MB |
|                         join_buffer_size |           0.250 MB |
|                             thread_stack |           1.000 MB |
|                        binlog_cache_size |           0.031 MB |
|                           tmp_table_size |          16.000 MB |
+------------------------------------------+--------------------+
|                    MEMORY PER CONNECTION |          17.906 MB |
+------------------------------------------+--------------------+
|                     Max_used_connections |                 51 |
|                          max_connections |                256 |
+------------------------------------------+--------------------+
|                              TOTAL (MIN) |       68505.219 MB |
|                              TOTAL (MAX) |       72176.000 MB |
+------------------------------------------+--------------------+

Далее

3D Printed Jaw

pcs:

base_a x 1
base_b x 1
clip x 7
main_gear x 2
jaw_plate x 1
jaw_plate_2 x 1
jaw_sliding x 1
handle or handle_xl x 1 (differ in size)

Archive with STL files (GDrive)

It’s not an original project this is only modification, Source project here

Installing MinIO to the budget model Synology NAS

Problem

For the budget models, Synology NAS (DS218j, etc.) is absent official/unofficial packages for installing MinIO service, and one option for installing MinIO on these devices is hand installing across SSH connection.

After upgrading firmware, need reinstallation.

1. Enabling SSH

Control Panel -> Terminal & SNMP -> checked “Enable SSH service” -> Apply

Далее

Pulumi Helm chart execution error

Pulumi error during execute Helm chart:

File "../pulumi_kubernetes/apiextensions/v1/CustomResourceDefinition.py", line 126, in __init__
        __self__._internal_init(resource_name, *args, **kwargs)
    TypeError: _internal_init() got an unexpected keyword argument 'status'

Solution for Python:
Add function:

# Remove the .status field from CRDs
def remove_status(obj, opts):
    if obj["kind"] == "CustomResourceDefinition":
        del obj["status"]

and transformation parametr to function

Chart(
        "chart",
        ChartOpts(
            transformations=[remove_status],
            ...,
            ...,
        )

Kubernetes PostStart and PreStop hooks

PreStart

На данный момент (v1.20) такого хука не существует и единственным способом гарантированного запуска чего-либо перед запуском основного контейнера - init containers

PostStart

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

PreStop

Данный хук вызывается непосредственно перед остановкой контейнера и является “блокирующим” - контейнер не будет удалён до момента окончания выполнения задачи определённой в хуке. На мой взгляд один из самых полезных хуков (исключая PreStart которого не существует) - в рамках данного хука очень удобно выполнять такие задачи как выгрузка каких либо артефактов, перед завершением работы контейнера (дампы, логи и т.д.). Но необходимо учитывать то, что у Kubernetes есть своеобразный механизм защиты от “вечно живущих” мёртвых контейнеров - terminationGracePeriodSeconds, который по умолчанию равен 60сек. (может быть изменён конфигурацией кластера, уточняйте по месту). Если вы не уверены что задача в PreStop будет завершена примерно за 50-55сек. то обязательно переназначьте данное значение в манифесте.

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
spec:
  containers:
  - name: myapp-container
    image: busybox
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart"]
      preStop:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the preSop"]
  terminationGracePeriodSeconds: 600 #<-- ten minutes delay before send a forced SIGTERM signal
  1. Container Lifecycle Hooks
  2. Init Containers

SLQ query order of execution

Query order of execution

1. FROM and JOINs

The FROM clause, and subsequent JOINs are first executed to determine the total working set of data that is being queried. This includes subqueries in this clause, and can cause temporary tables to be created under the hood containing all the columns and rows of the tables being joined.

2. WHERE

Once we have the total working set of data, the first-pass WHERE constraints are applied to the individual rows, and rows that do not satisfy the constraint are discarded. Each of the constraints can only access columns directly from the tables requested in the FROM clause. Aliases in the SELECT part of the query are not accessible in most databases since they may include expressions dependent on parts of the query that have not yet executed.

3. GROUP BY

The remaining rows after the WHERE constraints are applied are then grouped based on common values in the column specified in the GROUP BY clause. As a result of the grouping, there will only be as many rows as there are unique values in that column. Implicitly, this means that you should only need to use this when you have aggregate functions in your query.

4. HAVING

If the query has a GROUP BY clause, then the constraints in the HAVING clause are then applied to the grouped rows, discard the grouped rows that don’t satisfy the constraint. Like the WHERE clause, aliases are also not accessible from this step in most databases.

5. SELECT

Any expressions in the SELECT part of the query are finally computed.

6. DISTINCT

Of the remaining rows, rows with duplicate values in the column marked as DISTINCT will be discarded.

7. ORDER BY

If an order is specified by the ORDER BY clause, the rows are then sorted by the specified data in either ascending or descending order. Since all the expressions in the SELECT part of the query have been computed, you can reference aliases in this clause.

8. LIMIT / OFFSET

Finally, the rows that fall outside the range specified by the LIMIT and OFFSET are discarded, leaving the final set of rows to be returned from the query.

19V Модификация лабораторного БП HY1505D

Модификация лабораторного блока питания HY1505D - для работы в диапазоне напряжения 0-19В.

Далее

Using metasploit with postgres from an unprivileged user

The msfdb init databse in the ~/.msf4/db directory, the default postgres config create a socket file in the /run/postgesql or /var/run/postgresql directory, an unprivilegied user does not have wtite to this location.

Solution 0:

Uncomment the line unix_socket_directories = '/tmp' in the configuration file template /usr/share/postgresql/ postgresql.conf.sample and run msfdb init again

sudo sed -ei "s/^#unix_socket_directories.*/unix_socket_directories = '\/tmp'/g" /usr/share/postgresql/postgresql.conf.sample 
PGHOST="/tmp" msfdb init --component=database2

and create alias for the run msfconsole

alias msfstart='PGHOST="/tmp" msfdb start --component=database && msfconsole'
alias msfstop='msfdb stop'

After update PostgreSQL package, may have to be repeated.

Далее

gxkb и час потраченного времени

Час времени потрачено на разборки с настройками раскладок клавиатуры в Arch Linux + i3-gaps.
Есть конечно много способов как настроить клавиатуру в Linux, но с i3 DM чаще поступают так:

# .config/i3/config
...
exec --no-startup-id "setxkbmap -layout us,ru -option 'grp:win_space_toggle'"
exec --no-startup-id "gxkb"
...

И что-бы иметь хоть какой-то индикатор “раскладки”, сверху запускают gxkb, он маленький и отлично выполняет свою работу.
Но как оказалось, у этого мальца есть одна вредная особенность - при первом запуске считывает текущие настройки клавиатуры и сохраняет в свой конфиг .config/gxkb/gxkb.cfg и больше никогда, НИКОГДА, их не перезаписывает и продолжает подменять системные настройки (.xinitrc, .Xkbmap, /etc/X11/, /etc/X11/xorg.conf.d/00-keyboard.conf да и вообще любые попытки).
Если вдруг вы используете эту связку, поменяли настройки но ничего не работает как ожидалось — просто rm ~/.config/gxkb/gxkb.cfg

Сборка дистрибутива Arch Linux ARMx64 для RaspberryPi 4

Существует множество причин по которым необходимо собрать свой дистрибутив Linux и столько же причин этого не делать, но зачастую перед вами будет стоять выбор - собирать или искать дистрибутив подходящий под ваши нужды и наплевать на оптимальность.
С выходом RaspberryPI 3 а теперь ещё и RaspberryPI 4 с ARM x64 процессорами, люди столкнулись с тем что отсутствуют x64 дистрибутивы под новую платформу, в свою очередь RPI зарекомендовал себя как вполне стабильная система для применения в ответсвеных конструкциях и учитывая цену он очень вкусно выглядит на фоне различных специализированных платформ.
На сколько оправдано использование x64 на RaspberryPi и остальных, вопрос открытый и каждый решает сам.
В моём случае, необходимо перетащить софт скомпилированный под aarch64, на базе очень специфической железки, за которую хотят очень много денег, а выходит из строя она до безобразия часто :)

Далее