<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by DerNitro и все что с ним связано on Medium]]></title>
        <description><![CDATA[Stories by DerNitro и все что с ним связано on Medium]]></description>
        <link>https://medium.com/@dernitro?source=rss-5d74053052b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TFwdISYt4eYMrwY1YjJnxw.jpeg</url>
            <title>Stories by DerNitro и все что с ним связано on Medium</title>
            <link>https://medium.com/@dernitro?source=rss-5d74053052b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:03:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dernitro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testinfra or how to automate infrastructure health checks after failur]]></title>
            <link>https://dernitro.medium.com/testinfra-or-how-to-automate-infrastructure-health-checks-after-failur-d8e940c36923?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e940c36923</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[testinfra]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 02:52:44 GMT</pubDate>
            <atom:updated>2026-11-14T03:59:02.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gt-iMbiGK-EfvHt-6NnNGQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dernitro?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sergey Utkin</a> on <a href="https://unsplash.com/photos/-er_XtTx85s?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>After an outage, planned maintenance, or server reboot, an engineer always faces a classic task: ensuring that everything is running correctly. Usually, this process comes down to manually executing a checklist of commands:</p><ul><li>Checking the status of systemd services ( nginx, postgresql, uwsgi, etc.).</li><li>Ensuring necessary ports are open and listening.</li><li>Verifying the presence of configuration files, logs, and correct permissions.</li><li>Performing basic HTTP requests or pings.</li></ul><p>Manual checks using notepads or memory are slow, tedious, and prone to human error. In this article, we will look at how to apply the <strong>Infrastructure as Tests</strong> approach using the <strong>Testinfra</strong> library, turning routine checks into a fast, reliable, and repeatable suite of pytest tests.</p><h3>What is Testinfra?</h3><p><strong>Testinfra</strong> is a Python library that allows you to write unit tests to check the actual state of servers, containers, or hosts. Essentially, it is pytest for infrastructure. You can find detailed official documentation on the <a href="https://testinfra.readthedocs.io/">Testinfra documentation website</a>.</p><p>Key benefits:</p><ol><li><strong>Familiar pytest syntax:</strong> If you know Python and pytest, mastering it takes minutes.</li><li><strong>Agentless operation:</strong> Testinfra connects via SSH, Docker, WinRM, LXC, or runs locally. No additional software needs to be installed on target servers.</li><li><strong>Rich set of modules:</strong> Out-of-the-box checks for packages ( package), services ( service), files ( file), users, sockets, commands, and more.</li></ol><h3>Running the tests</h3><p>Tests can be run locally on the server or remotely via SSH:</p><pre># Local run pytesttest_infra.py # Run via SSH on a remote server pytest--connection=ssh--hosts=root@my-server.example.comtest_infra.py # Check a group of servers from a list pytest--connection=ssh--hosts=root@server1.example.com,root@server2.example.comtest_infra.py</pre><h3>Ansible Integration</h3><p>If your infrastructure is managed with Ansible, Testinfra has a built-in backend for Ansible inventory. This allows you to run tests directly by host or group names from your inventory.yml:</p><pre># Run tests for the entire webservers group from ansible inventory pytest--connection=ansible--ansible-inventory=inventory.yml--hosts=webservers</pre><p>Testinfra automatically reads connection settings (SSH keys, ports, users) from your Ansible inventory, eliminating the need to duplicate connection parameters.</p><h3>Integrating into the Recovery Process</h3><p>Such tests can be:</p><ul><li>Added to post-outage recovery runbooks.</li><li>Automatically executed via CI/CD after deployment or infrastructure restart in Docker/Ansible.</li><li>Integrated into monitoring or orchestration systems.</li></ul><h3>Conclusion</h3><p>Using Testinfra allows you to formalize infrastructure state requirements and automate health checks after failures. Instead of manual command execution, we get a green or red pytest report that immediately shows which component failed to start.</p><p><em>Originally published at </em><a href="https://su-blog.ru/en/posts/2026/11/03/testinfra-ili-kak-avtomatizirovat-proverku-infrastruktury-posle-sboia/"><em>https://su-blog.ru</em></a><em> on November 3, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e940c36923" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strace as a Linux Engineer’s Tool]]></title>
            <link>https://dernitro.medium.com/strace-as-a-linux-engineers-tool-674b8f6566e5?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/674b8f6566e5</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[strace]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 04:00:45 GMT</pubDate>
            <atom:updated>2025-12-19T14:47:38.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PgBo4DKbDFgehx1B.jpg" /></figure><p>Photo by <a href="https://unsplash.com/@umbra_media?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Christopher Bill</a> on <a href="https://unsplash.com/photos/brown-cardboard-box-on-white-surface-3l19r5EOZaw?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p><p>The idea for this article came after a technical interview at a large Russian company. The interview was practical: you log into a virtual machine and have to explain why certain applications aren’t starting. You run strace… 10–15 minutes later, the tasks are done, and you’ve saved each other time.</p><p>In my own practice, I’ve long used strace to understand the behavior of an application when logs are insufficient, and the application just won’t work.</p><p>In this article, we’ll look at the capabilities of strace from a Linux administrator’s perspective. Let’s get started…</p><h3>Introduction</h3><p>Linux engineers often encounter situations where an application won’t start or behaves incorrectly, and standard logs don’t answer the question “why?”. In such cases, an indispensable tool is strace — a utility for tracing system calls and signals, allowing you to see exactly how an application interacts with the operating system.</p><p>This article covers practical scenarios for using strace to diagnose file access problems, analyze multithreading, debug bash scripts, and network applications. The material is aimed at system administrators, DevOps engineers, and anyone who deals with Linux support and debugging. The examples are based on real cases and will help you quickly master the basics of the tool.</p><blockquote>Note</blockquote><blockquote>strace — trace system calls and signals</blockquote><blockquote>A useful diagnostic, educational, and debugging tool. System administrators, diagnosticians, and troubleshooters will find it invaluable for solving problems with programs whose source code is unavailable, since you don’t need to recompile them for tracing.</blockquote><p>As mentioned above, strace allows you to trace system calls and signals in Linux. You start tracing like this: strace &lt;command&gt;.</p><p>For example, the output of the date command looks like this:</p><pre>$&gt; strace -z date <br>execve(&quot;/usr/bin/date&quot;, [&quot;date&quot;], 0x7ffdd7a8c9c8 /* 75 vars */) = 0 <br>brk(NULL) = 0x587a7e7bf000 <br>mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7c97fd31c000 <br>openat(AT_FDCWD, &quot;/etc/ld.so.cache&quot;, O_RDONLY|O_CLOEXEC) = 3 <br>fstat(3, {st_mode=S_IFREG|0644, st_size=115355, ...}) = 0 <br>mmap(NULL, 115355, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7c97fd2ff000 <br>close(3) = 0 <br>openat(AT_FDCWD, &quot;/lib/x86_64-linux-gnu/libc.so.6&quot;, O_RDONLY|O_CLOEXEC) = 3 <br>read(3, &quot;\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0&gt;\0\1\0\0\0\220\243\2\0\0\0\0\0&quot;..., 832) = 832 <br>pread64(3, &quot;\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0&quot;..., 784, 64) = 784 <br>fstat(3, {st_mode=S_IFREG|0755, st_size=2125328, ...}) = 0 <br>pread64(3, &quot;\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0&quot;..., 784, 64) = 784 <br>mmap(NULL, 2170256, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7c97fd000000 <br>mmap(0x7c97fd028000, 1605632, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x28000) = 0x7c97fd028000 <br>mmap(0x7c97fd1b0000, 323584, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b0000) = 0x7c97fd1b0000 <br>mmap(0x7c97fd1ff000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1fe000) = 0x7c97fd1ff000 <br>mmap(0x7c97fd205000, 52624, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7c97fd205000 close(3) = 0 <br>mmap(NULL, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7c97fd2fc000 arch_prctl(ARCH_SET_FS, 0x7c97fd2fc740) = 0 <br>set_tid_address(0x7c97fd2fca10) = 30773 <br>set_robust_list(0x7c97fd2fca20, 24) = 0 <br>rseq(0x7c97fd2fd060, 0x20, 0, 0x53053053) = 0 <br>mprotect(0x7c97fd1ff000, 16384, PROT_READ) = 0 <br>mprotect(0x587a79412000, 8192, PROT_READ) = 0 <br>mprotect(0x7c97fd354000, 8192, PROT_READ) = 0 <br>prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0 <br>munmap(0x7c97fd2ff000, 115355) = 0 <br>getrandom(&quot;\xd9\xf1\xf0\xc3\xcb\x19\x41\xc4&quot;, 8, GRND_NONBLOCK) = 8 <br>brk(NULL) = 0x587a7e7bf000 brk(0x587a7e7e0000) = 0x587a7e7e0000 <br>openat(AT_FDCWD, &quot;/usr/lib/locale/locale-archive&quot;, O_RDONLY|O_CLOEXEC) = 3 <br>fstat(3, {st_mode=S_IFREG|0644, st_size=5728464, ...}) = 0 <br>mmap(NULL, 5728464, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7c97fca00000 <br>close(3) = 0 openat(AT_FDCWD, &quot;/etc/localtime&quot;, O_RDONLY|O_CLOEXEC) = 3 <br>fstat(3, {st_mode=S_IFREG|0644, st_size=1535, ...}) = 0 <br>fstat(3, {st_mode=S_IFREG|0644, st_size=1535, ...}) = 0 <br>read(3, &quot;TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\21\0\0\0\21\0\0\0\0&quot;..., 4096) = 1535 <br>lseek(3, -927, SEEK_CUR) = 608 <br>read(3, &quot;TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\21\0\0\0\21\0\0\0\0&quot;..., 4096) = 927 <br>close(3) = 0 <br>fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0), ...}) = 0 <br>write(1, &quot;\320\222\321\201 20 \320\260\320\277\321\200 2025 08:56:05 MSK&quot;..., 33) = 33 <br>close(1) = 0 <br>close(2) = 0 <br>+++ exited with 0 +++</pre><p>Each trace line contains the system call name, followed by its arguments in parentheses and the return value. A more detailed description can be found on the <a href="https://man7.org/linux/man-pages/man1/strace.1.html">man strace</a> page. The full list of system calls is available at <a href="https://man7.org/linux/man-pages/man2/syscalls.2.html">man syscalls</a></p><h3>File Access</h3><p>In my experience, most application malfunctions are due to lack of access to file resources, and as we know, in Linux everything is a file.</p><p>Let’s take the previous example with the date command and see which files it needs access to. We’ll use the — trace=%file filter.</p><pre>$&gt; strace --trace=%file date<br>execve(&quot;/usr/bin/date&quot;, [&quot;date&quot;], 0x7fff97977278 /* 36 vars */) = 0<br>access(&quot;/etc/ld.so.preload&quot;, R_OK)      = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/etc/ld.so.cache&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/lib/x86_64-linux-gnu/libc.so.6&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/locale-archive&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/share/locale/locale.alias&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_IDENTIFICATION&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_IDENTIFICATION&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_MEASUREMENT&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_MEASUREMENT&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_TELEPHONE&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_TELEPHONE&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_ADDRESS&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_ADDRESS&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_NAME&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_NAME&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_PAPER&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_PAPER&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_MESSAGES&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_MESSAGES&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_MESSAGES/SYS_LC_MESSAGES&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_MONETARY&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_MONETARY&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_COLLATE&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_COLLATE&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_TIME&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_TIME&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_NUMERIC&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_NUMERIC&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_CTYPE&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.utf8/LC_CTYPE&quot;, O_RDONLY|O_CLOEXEC) = 3<br>openat(AT_FDCWD, &quot;/etc/localtime&quot;, O_RDONLY|O_CLOEXEC) = 3<br>Sun Apr 20 09:10:39 MSK 2025<br>+++ exited with 0 +++</pre><p>Quite a list for such a simple command. As you can see, some files are inaccessible, but this didn’t affect the result. To display only successful or unsuccessful system calls, you can add the -z and -Z flags respectively.</p><p>Let’s look at an example of unsuccessful file access. We have a simple Python script that requires access to /root/test.</p><pre>#!/usr/bin/env python3<br><br>import sys<br><br>try:<br>    with open(&#39;/root/test&#39;) as f:<br>        f.readlines()<br>except:<br>    sys.exit(1)<br><br>sys.exit(0)</pre><p>Running this script will return code 1, which isn’t very informative for diagnostics. Let’s see what strace shows. We’ll run the command with the-Z flag to see only unsuccessful system calls.</p><pre>$&gt; strace -Z python3 main.py<br>access(&quot;/etc/ld.so.preload&quot;, R_OK)      = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/locale-archive&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/share/locale/locale.alias&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/lib/locale/C.UTF-8/LC_CTYPE&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/home/sutkin/.pyenv/plugins/pyenv-virtualenv/shims/python3&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/home/sutkin/.pyenv/shims/python3&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/home/sutkin/.pyenv/bin/python3&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/local/sbin/python3&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/local/bin/python3&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/sbin/python3&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/pyvenv.cfg&quot;, O_RDONLY) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/bin/pyvenv.cfg&quot;, O_RDONLY) = -1 ENOENT (No such file or directory)<br>readlink(&quot;/usr/bin/python3.12&quot;, 0x7ffcce910cd0, 4096) = -1 EINVAL (Invalid argument)<br>openat(AT_FDCWD, &quot;/usr/bin/python3._pth&quot;, O_RDONLY) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/bin/python3.12._pth&quot;, O_RDONLY) = -1 ENOENT (No such file or directory)<br>openat(AT_FDCWD, &quot;/usr/bin/pybuilddir.txt&quot;, O_RDONLY) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/bin/Modules/Setup.local&quot;, 0x7ffcce915cb0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/bin/lib/python312.zip&quot;, 0x7ffcce915a70, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python312.zip&quot;, 0x7ffcce915ad0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/bin/lib/python3.12/os.py&quot;, 0x7ffcce915ad0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/bin/lib/python3.12/os.pyc&quot;, 0x7ffcce915ad0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/bin/lib/python3.12/lib-dynload&quot;, 0x7ffcce915ad0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python312.zip&quot;, 0x7ffcce915500, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python312.zip&quot;, 0x7ffcce915880, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python3.12/encodings/__init__.cpython-312-x86_64-linux-gnu.so&quot;, 0x7ffcce915880, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python3.12/encodings/__init__.abi3.so&quot;, 0x7ffcce915880, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python3.12/encodings/__init__.so&quot;, 0x7ffcce915880, 0) = -1 ENOENT (No such file or directory)<br>ioctl(3, TCGETS, 0x7ffcce9154c0)        = -1 ENOTTY (Inappropriate ioctl for device)<br>ioctl(3, TCGETS, 0x7ffcce914a40)        = -1 ENOTTY (Inappropriate ioctl for device)<br>ioctl(3, TCGETS, 0x7ffcce915550)        = -1 ENOTTY (Inappropriate ioctl for device)<br>lseek(0, 0, SEEK_CUR)                   = -1 ESPIPE (Illegal seek)<br>lseek(1, 0, SEEK_CUR)                   = -1 ESPIPE (Illegal seek)<br>lseek(2, 0, SEEK_CUR)                   = -1 ESPIPE (Illegal seek)<br>newfstatat(AT_FDCWD, &quot;/usr/bin/pyvenv.cfg&quot;, 0x7ffcce9154c0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/pyvenv.cfg&quot;, 0x7ffcce915520, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/home/sutkin/.local/lib/python3.12/site-packages&quot;, 0x7ffcce9156f0, 0) = -1 ENOENT (No such file or directory)<br>newfstatat(AT_FDCWD, &quot;/usr/lib/python3.12/dist-packages&quot;, 0x7ffcce915750, 0) = -1 ENOENT (No such file or directory)<br>ioctl(3, TCGETS, 0x7ffcce915030)        = -1 ENOTTY (Inappropriate ioctl for device)<br>ioctl(3, TCGETS, 0x7ffcce9149c0)        = -1 ENOTTY (Inappropriate ioctl for device)<br>ioctl(3, TCGETS, 0x7ffcce915b90)        = -1 ENOTTY (Inappropriate ioctl for device)<br>readlink(&quot;main.py&quot;, 0x7ffcce905330, 4096) = -1 EINVAL (Invalid argument)<br>readlink(&quot;/home/sutkin/strace/01/main.py&quot;, 0x7ffcce904ed0, 1023) = -1 EINVAL (Invalid argument)<br>ioctl(3, TCGETS, 0x7ffcce9162c0)        = -1 ENOTTY (Inappropriate ioctl for device)<br>openat(AT_FDCWD, &quot;/root/test&quot;, O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied)<br>+++ exited with 1 +++</pre><p>From the last lines, we can assume the application fails due to lack of access to /root/test. If we run the application with sudo, we get the expected result.</p><blockquote>Warning</blockquote><blockquote>Be careful when using sudo to run unfamiliar applications or scripts. Running with elevated privileges can damage your system, cause data loss, or compromise security. Make sure you trust the source code and understand its actions before executing.</blockquote><pre>$&gt; sudo python3 main.py<br>$&gt; echo $?<br>0</pre><h3>Viewing Multithreaded Applications</h3><p>For decades now, multi-core CPUs have been common, and multithreading is used to fully utilize CPU resources.</p><p>Currently, multithreading can be implemented in two ways:</p><ul><li>Launching a child process with a separate memory space.</li><li>Launching a child process that can share virtual address space, file descriptors, and signal handler tables.</li></ul><p>But how do you tell what an application like nginx uses?</p><pre>root        6215  0.0  0.0  11156  1596 ?        Ss   08:20   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;<br>www-data    6216  0.0  0.1  12880  4284 ?        S    08:20   0:00  \_ nginx: worker process<br>www-data    6217  0.0  0.1  12880  4284 ?        S    08:20   0:00  \_ nginx: worker process</pre><p>Let’s model both technologies. We’ll use the %process filter.</p><h4>process</h4><pre>#!/usr/bin/env python3<br><br>&#39;&#39;&#39;<br>    Example #2:<br>    Creating fork<br>&#39;&#39;&#39;<br><br>import sys<br>import subprocess<br>import random<br><br>subprocess.Popen([&quot;sleep&quot;, f&quot;{random.randrange(0,15)}&quot;])<br><br>sys.exit(0)</pre><p>The result shows <a href="https://man7.org/linux/man-pages/man2/vfork.2.html">vfork</a> system calls, where <a href="https://man7.org/linux/man-pages/man2/execve.2.html">execve(“/usr/bin/sleep”…</a> is launched, and the parent waits for completion with <a href="https://man7.org/linux/man-pages/man2/wait4.2.html">wait4(8644,…</a></p><pre>$&gt; strace --trace=%process -f python3 02/main.py<br>execve(&quot;/usr/bin/python3&quot;, [&quot;python3&quot;, &quot;02/main.py&quot;], 0x7ffde05d94f8 /* 36 vars */) = 0<br>vfork(strace: Process 8827 attached<br>&lt;unfinished ...&gt;<br>[pid  8827] execve(&quot;/home/sutkin/.pyenv/plugins/pyenv-virtualenv/shims/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */) = -1 ENOENT (No such file or directory)<br>[pid  8827] execve(&quot;/home/sutkin/.pyenv/shims/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */) = -1 ENOENT (No such file or directory)<br>[pid  8827] execve(&quot;/home/sutkin/.pyenv/bin/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */) = -1 ENOENT (No such file or directory)<br>[pid  8827] execve(&quot;/usr/local/sbin/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */) = -1 ENOENT (No such file or directory)<br>[pid  8827] execve(&quot;/usr/local/bin/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */) = -1 ENOENT (No such file or directory)<br>[pid  8827] execve(&quot;/usr/sbin/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */) = -1 ENOENT (No such file or directory)<br>[pid  8827] execve(&quot;/usr/bin/sleep&quot;, [&quot;sleep&quot;, &quot;6&quot;], 0x7fff752cbdb0 /* 36 vars */ &lt;unfinished ...&gt;<br>[pid  8826] &lt;... vfork resumed&gt;)        = 8827<br>[pid  8827] &lt;... execve resumed&gt;)       = 0<br>[pid  8826] wait4(8827, 0x7fff752cb4fc, WNOHANG, NULL) = 0<br>[pid  8826] exit_group(0)               = ?<br>[pid  8826] +++ exited with 0 +++<br>exit_group(0)                           = ?<br>+++ exited with 0 +++</pre><p>No surprises: as expected, vfork is called, which is more efficient than fork because it doesn’t copy memory pages. Instead, the child and parent share memory until one successfully calls exec() or _exit().</p><h4>thread</h4><pre>#!/usr/bin/env python3<br><br>&#39;&#39;&#39;<br>    Example #3:<br>    Creating thread<br>&#39;&#39;&#39;<br><br>import sys<br>from threading import Thread<br>import random<br>import time<br><br>def foo():<br>    time.sleep(random.randrange(0,15))<br><br><br>t = Thread(target=foo)<br>t.start()<br><br>sys.exit(0)</pre><p>The result is a <a href="https://man7.org/linux/man-pages/man2/clone3.2.html">clone3</a> call, which returns the PID of the new process. The clone3 call is similar to fork, i.e., it creates a separate process, but allows you to control creation stages via flags.</p><p>From the flags, we can immediately see:</p><ul><li>Parent and child share virtual memory (CLONE_VM)</li><li>Parent and child share filesystem attributes (CLONE_FS)</li><li>Parent and child share open file descriptor table (CLONE_FILES)</li><li>Places the child in the same thread group as its parent (CLONE_THREAD)</li></ul><pre>$&gt; strace --trace=%process -f python3 03/main.py<br>execve(&quot;/usr/bin/python3&quot;, [&quot;python3&quot;, &quot;03/main.py&quot;], 0x7fff929b4dc8 /* 36 vars */) = 0<br>clone3({flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, child_tid=0x7101922de990, parent_tid=0x7101922de990, exit_signal=0, stack=0x710191ade000, stack_size=0x7fff80, tls=0x7101922de6c0} =&gt; {parent_tid=[8991]}, 88) = 8991<br>strace: Process 8991 attached<br>[pid  8991] exit(0)                     = ?<br>[pid  8991] +++ exited with 0 +++<br>exit_group(0)                           = ?<br>+++ exited with 0 +++</pre><blockquote>Note</blockquote><blockquote>Using the %process filter, you can determine how multithreading is organized in an application.</blockquote><p>Back to nginx, we see it uses clone without shared memory, which makes sense — no need to fight over shared resources.</p><pre>$&gt; sudo strace --trace=%process -f /usr/sbin/nginx -g &#39;master_process on;&#39;<br>[sudo] password for sutkin:<br>execve(&quot;/usr/sbin/nginx&quot;, [&quot;/usr/sbin/nginx&quot;, &quot;-g&quot;, &quot;master_process on;&quot;], 0x7ffe908b5210 /* 23 vars */) = 0<br>clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLDstrace: Process 9670 attached<br>, child_tidptr=0x7c345a1bea10) = 9670<br>[pid  9670] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD &lt;unfinished ...&gt;<br>[pid  9669] exit_group(0strace: Process 9671 attached<br>)               = ?<br>[pid  9670] &lt;... clone resumed&gt;, child_tidptr=0x7c345a1bea10) = 9671<br>[pid  9670] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD &lt;unfinished ...&gt;<br>[pid  9669] +++ exited with 0 +++<br>strace: Process 9672 attached<br>[pid  9670] &lt;... clone resumed&gt;, child_tidptr=0x7c345a1bea10) = 9672<br>^Cstrace: Process 9670 detached<br>strace: Process 9672 detached<br>strace: Process 9671 detached</pre><h3>Command Line</h3><p>One use case for strace is debugging bash scripts. For example, it’s hard to analyze a 4500-line script by eye or with debug mode, like <a href="https://github.com/nvm-sh/nvm/blob/master/nvm.sh">Node Version Manager</a>.</p><p>Here’s a simple bash script:</p><pre>#!/bin/bash<br><br>eval $(printf &quot;\145\143\150\157\40\42\110\145\154\154\157\42&quot;)<br>eval $(echo &quot;dt&quot; | sed &#39;s/t/ate/&#39;)<br>eval $(echo &quot;bHMK&quot; | base64 -d)</pre><p>It’s hard to tell at a glance what this script does. Let’s run it through strace and see the result.</p><pre>$&gt; strace --trace=execve -f 04/main.sh 2&gt;&amp;1 | grep execve<br>execve(&quot;04/main.sh&quot;, [&quot;04/main.sh&quot;], 0x7ffc0a9ebdc0 /* 39 vars */) = 0<br>[pid  4799] execve(&quot;/usr/bin/date&quot;, [&quot;date&quot;], 0x5e11f9af7120 /* 38 vars */) = 0<br>[pid  4802] execve(&quot;/usr/bin/sed&quot;, [&quot;sed&quot;, &quot;s/t/ate/&quot;], 0x5e11f9af7120 /* 38 vars */) = 0<br>[pid  4803] execve(&quot;/usr/bin/date&quot;, [&quot;date&quot;], 0x5e11f9af7120 /* 38 vars */) = 0<br>[pid  4806] execve(&quot;/usr/bin/base64&quot;, [&quot;base64&quot;, &quot;-d&quot;], 0x5e11f9af7120 /* 38 vars */) = 0<br>[pid  4807] execve(&quot;/usr/bin/date&quot;, [&quot;date&quot;], 0x5e11f9af7120 /* 38 vars */) = 0</pre><p>If you add the -v flag, you’ll also see the arguments passed.</p><h3>Creating Socket and Sending Data</h3><p>To avoid inventing code, let’s use an example from the documentation <a href="https://www.digitalocean.com/community/tutorials/python-socket-programming-server-client">Python Socket Programming: Server and Client Example Guide</a>.</p><p>The application is simple: a server is started, a client connects and sends a message.</p><pre>#!/usr/bin/env python3<br><br>import socket<br><br>def server_program():<br>    host = socket.gethostname()<br>    port = 5000<br><br>    server_socket = socket.socket()<br>    server_socket.bind((host, port))<br><br>    server_socket.listen(2)<br>    conn, address = server_socket.accept()<br>    while True:<br>        data = conn.recv(1024).decode()<br>        if not data:<br>            break<br>    conn.close()<br><br>if __name__ == &#39;__main__&#39;:<br>    server_program()</pre><pre>#!/usr/bin/env python3<br><br>import socket<br><br>def client_program():<br>    host = socket.gethostname()<br>    port = 5000<br><br>    client_socket = socket.socket()<br>    client_socket.connect((host, port))<br><br>    message = &#39;data&#39;<br><br>    client_socket.send(message.encode())<br>    client_socket.close()<br><br>if __name__ == &#39;__main__&#39;:<br>    client_program()</pre><p>Let’s run the server and client and see what useful data we can get by analyzing only system calls.</p><pre>$&gt; strace --trace=socket,bind,recvfrom,sendto,accept4 -z python3 05/server_program.py<br>socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_IP) = 3<br>...<br>bind(3, {sa_family=AF_INET, sin_port=htons(5000), sin_addr=inet_addr(&quot;127.0.1.1&quot;)}, 16) = 0<br>listen(3, 2)                            = 0<br>accept4(3, {sa_family=AF_INET, sin_port=htons(40876), sin_addr=inet_addr(&quot;127.0.0.1&quot;)}, [16], SOCK_CLOEXEC) = 4<br>recvfrom(4, &quot;data&quot;, 1024, 0, NULL, NULL) = 4<br>recvfrom(4, &quot;&quot;, 1024, 0, NULL, NULL)    = 0<br>+++ exited with 0 +++</pre><ul><li>bind — Binds the socket to a specific IP address and port on your machine. This is its “registration”. After this, the socket “knows” which address to accept incoming connections or send outgoing ones. The parameters show which address and port the application will listen on.</li><li>listen — Puts the socket into listening mode.</li><li>accept4 — Extracts the first connection request from the queue for the listening socket and creates a new connected socket. The parameters contain information about the client.</li><li>recvfrom — Received the sent data.</li></ul><pre>$&gt; strace -v --trace=socket,connect,sendto,recvfrom -z python3 05/client_program.py<br>socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_IP) = 3<br>...<br>connect(3, {sa_family=AF_INET, sin_port=htons(5000), sin_addr=inet_addr(&quot;127.0.1.1&quot;)}, 16) = 0<br>sendto(3, &quot;data&quot;, 4, 0, NULL, 0)        = 4<br>+++ exited with 0 +++</pre><p>The client side output is simpler:</p><ul><li>connect — After creating the socket, this system call handles all the work of establishing a TCP connection; the server address is passed as a parameter.</li><li>sendto — Sends data.</li></ul><p>Of course, it’s hard to imagine debugging a high-load network application this way, but without this example, the article would feel incomplete.</p><h3>Getting Syscall Statistics</h3><p>As a bonus, running with the -c flag simply outputs statistics on system call usage.</p><pre>$&gt; strace -c -z date<br>Sun Sep 28 06:51:34 MSK 2025<br>% time     seconds  usecs/call     calls    errors syscall<br>------ ----------- ----------- --------- --------- ----------------<br>28.02    0.000325          15        21           mmap<br>18.97    0.000220          12        17           openat<br>16.03    0.000186           9        19           close<br>14.66    0.000170           8        19           fstat<br>6.72     0.000078          26         3           mprotect<br>2.84     0.000033          11         3           read<br>1.98     0.000023          23         1           write<br>1.98     0.000023           7         3           brk<br>1.38     0.000016           8         2           pread64<br>1.38     0.000016          16         1           getrandom<br>1.03     0.000012          12         1           arch_prctl<br>0.95     0.000011          11         1           set_tid_address<br>0.95     0.000011          11         1           set_robust_list<br>0.95     0.000011          11         1           prlimit64<br>0.86     0.000010          10         1           rseq<br>0.69     0.000008           8         1           futex<br>0.60     0.000007           7         1           lseek<br>0.00     0.000000           0         1           munmap<br>0.00     0.000000           0         1           execve<br>------ ----------- ----------- --------- --------- ----------------<br>100.00    0.001160          11        98           total</pre><h3>Conclusion</h3><p>strace is an indispensable tool for diagnosing and debugging applications in Linux, especially when standard logs don’t answer the question “why doesn’t it work?”. I hope this article is useful and helps someone fix production issues or at least pass an interview in the future. <strong>Good luck to all.</strong></p><p><em>Originally published at </em><a href="https://su-blog.ru/en/posts/2025/09/27/strace-kak-instrument-sistemnogo-administratora/"><em>https://su-blog.ru</em></a><em> on September 28, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674b8f6566e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pyRMA or how I wrote an access system]]></title>
            <link>https://dernitro.medium.com/pyrma-or-how-i-wrote-an-access-system-e653bc9e3543?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e653bc9e3543</guid>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 21:00:04 GMT</pubDate>
            <atom:updated>2025-05-08T04:31:27.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*55cGRbXKfE99Jmzn.jpg" /></figure><p>Photo by <a href="https://unsplash.com/@teapowered?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Patrick Robert Doyle</a> on <a href="https://unsplash.com/photos/a-red-and-white-sign-sitting-on-the-side-of-a-road--XiKxvvFGgU?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p><p>2014. I am a young and promising technical support engineer and I was assigned to assist my senior colleague in creating an access control system for our clients’ hardware and software systems.</p><p>The concept was simple: set up an “SSH jump” node where the desired client node could be selected via the CLI. The system would record who connected, where, and when, and based on this data, it would be possible to reconstruct the picture if something suddenly went wrong on the client systems.</p><p>The solution was ready, on freebsd using native <a href="https://docs.freebsd.org/en/books/handbook/jails/#classic-jail">jail</a> and CLI based on bash script. But when submitting user load — problems arose, and the system became inoperative, I don’t remember the details, but they were related to locks when working with the database, which was on <a href="https://www.sqlite.org/">sqlite</a>.</p><p>While the senior engineer was tweaking the bash scripts, I wrote my own python interpretation of the problem, which worked, and I was given carte blanche to improve it. Development of the freebsd solution was stopped.</p><p>Years passed, the solution worked, but the code written “on the knee” created a huge technical debt, and at some point, the development of the system became impossible. It was time to rewrite and <a href="https://github.com/DerNitro/pyRMA">share the code</a> with the world.</p><p>Well, let’s see what came out of it.</p><blockquote>Note</blockquote><blockquote>I am not a real programmer, so I do not claim that:</blockquote><blockquote>* The system architecture is perfect</blockquote><blockquote>* The code is written professionally</blockquote><blockquote>* The system is secure</blockquote><blockquote>* etc</blockquote><blockquote>But creating this system helped me develop my skills, which helped me in my future work.</blockquote><h3>Requirements</h3><p>Over several years of operation of the first version of the access system, a list of requirements was determined:</p><ol><li>Connect to client systems via SSH and Telnet protocols, including <a href="https://www.ssh.com/academy/ssh/command#ssh-command-line-options">Jump host</a> support</li><li>Restricting access to client systems for a user or group of users</li><li>Ability to request and approve access to user client systems</li><li>Ability to transfer/download files from client systems</li><li>Possibility of TCP/UDP port forwarding to client systems</li><li>Possibility of connection to the client equipment management interface</li><li>Ability to view user session</li><li>Separation of roles [1] of user, operator and administrator of the access system</li></ol><h3>Description of the system</h3><p>As mentioned earlier, the system code is written in <a href="https://www.python.org/"><strong>Python</strong></a> and consists of the following elements:</p><ul><li>Connection console</li><li>Data transfer console</li><li>WEB console</li><li>iptables rules management module</li><li>PostgreSQL Database</li></ul><p>At its core, the system is a “single entry point” that allows the user to select the host of interest and connect to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rmDr6oOF-92IX--S.png" /></figure><p>The user scenario looks like this:</p><ol><li>The user connects to the access system via the SSH protocol.</li><li>The user attribute based access system determines whether a user can have access; if the user is connecting for the first time, an access request is generated and sent to the system administrator for approval.</li><li>After successfully connecting to the system, the console interface will be launched, which will display a list of all registered nodes.</li><li>The user selects the desired node and can choose several types of actions:<br>- Connect to the node using SSH or Telnet protocol<br>- Connect to the node in file transfer mode<br>- Connect only Services to node [2]</li><li>If the user is not allowed to connect, an access request will be created and sent to the operator for approval.</li><li>After the user’s connection to the node is complete, session information, TTY console recording, and network traffic dumps will be saved in the access system and available for viewing by the administrator and system operator.</li></ol><h3>System pyRMA</h3><h3>Connecting to pyRMA</h3><p>Connection to the system is carried out via the SSH protocol, and it was necessary to resolve several issues at once</p><ol><li>Authentication of users who should get directly into the access system, and who into the command interpreter of the operating system.</li><li>Launching the console interface of the access system</li><li>Recording a TTY session</li></ol><p>The first attempt to organize user authentication was based on the <a href="https://github.com/pam-pgsql/pam-pgsql">pam-pgsql</a> project, which allows storing user data in the PostgreSQL DBMS, but this solution had to be abandoned, as it required large investments, such as:</p><ul><li>Ensuring information security when storing user data in a DBMS</li><li>Development of a mechanism for synchronization with corporate systems Directory Services</li><li>pam-pgsql is a half-dead project, there are unresolved tickets with problems from 2016, there is a big risk of rewriting part of the authentication in the system.</li></ul><p>The solution was to leave authorization on <a href="https://www.man7.org/linux/man-pages/man8/pam.8.html">Linux PAM</a>, when connecting via SSH PAM is enabled by the parameter UsePAM yes, and for the web interface the module <a href="https://pypi.org/project/python-pam/">python-pam</a> is used, which allowed leaving the source of data for authentication at the discretion of the system administrator.</p><p>For further work with user data, we obtain information about the user and his groups through the capabilities of the standard library <a href="https://www.python.org/"><strong>Python</strong></a> <a href="https://docs.python.org/3.8/library/pwd.html">pwd — Password database</a> and <a href="https://docs.python.org/3.8/library/grp.html">grp — Group database</a>, based on the user’s groups, the system determines access rights and display of information.</p><p>After passing authentication and authorization, we need to launch the access system interface, for this we will replace the command interpreter with launching our console.</p><p><a href="https://man7.org/linux/man-pages/man5/sshd_config.5.html">SSHD</a> allows users to override the startup command on connection.</p><blockquote>ForceCommand</blockquote><blockquote>Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user’s login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.</blockquote><p>Let’s override this setting for all users except system administrators.</p><pre>Match User *,!acs,!root<br>    ForceCommand /srv/acs/bin/pyrma.sh<br>    AllowTcpForwarding no<br>    X11Forwarding no</pre><p>and add the redefined interpreter to the trusted /etc/shells list. Now all users connecting via SSH will get into our script, which will launch the console interface of the access system and record the TTY session.</p><p>As a utility for capturing the user’s terminal, the choice fell on <a href="https://docs.asciinema.org/">asciinema</a>. At the time of development, it had a number of advantages:</p><ul><li>Active development of the project</li><li>The repository contains an APT package for Linux Ubuntu 20.04 OS</li><li>There is an embedded HTML player, which is successfully integrated into the WEB interface.</li><li>Recording the stdin channel allowed us to analyze the input commands</li><li>Passing a shell command to write</li></ul><p>Thanks to the last point we launch the access system interface.</p><h3>Connection interface</h3><p>Immediately after connecting to the access system, the console interface is launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KAugs5IQ78XJNuk8.gif" /></figure><p>The <a href="https://github.com/npcole/npyscreen">npyscreen</a> library was used to create the interface. At the time of writing, the <a href="https://github.com/DerNitro/pyRMA"><strong>pyRMA</strong></a> project was more active than it is now.</p><p>The library has great capabilities for creating a multi-window application, a huge number of widgets, as well as the ability to create your own, allows you to create an interface for any taste.</p><p>Implemented functionality:</p><ul><li>List of nodes with the ability to search and filter elements</li><li>Displaying node information</li><li>Request access to connect to a node</li></ul><h3>File Transfer Interface</h3><p>Clicking the “File Transfer” button in the console application launches the file transfer interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*02qcrbwMHtF_NQ7P.gif" /></figure><p>The display interface is also written in <a href="https://github.com/npcole/npyscreen">npyscreen</a>. To list and transfer files I used <a href="https://pypi.org/project/pysftp/">pysftp</a>.</p><blockquote>Note</blockquote><blockquote>To start data transfer, the user needs to upload the file to the access system via the SFTP protocol, after which it will become available in the interface.</blockquote><p>One of the tasks was to store information about transferred files, both to the destination node and in the opposite direction.</p><p>This is implemented as follows:</p><ol><li>The transferred file or directory is archived in tar.gz</li><li>From the received archive we get the hash sum md5</li><li>The presence of a given hash sum in the database is checked.</li><li>If the database contains a hash, a hard link to the found archive is created</li><li>If it is missing, the archive is transferred to the storage directory, and the corresponding entry is entered into the database.</li></ol><p>By using hardlink and tar.gz we save space and do not duplicate data.</p><p>All transferred files are available in the “operator” interface and can be downloaded for analysis.</p><h3>Connections</h3><p>Connection interface returns a connection object (SSH, FTP, TELNET, etc.) on which the run(), connection(), and close() functions are run.</p><ul><li>run() - starts the services required for the connection, enters connection information into the database, generates iptables rules.</li><li>connection() - starts a connection directly, this can be either a child process or a separate console interface.</li><li>close() - Closes all previously created services, connections and deletes iptables rules, updates connection information in the database.</li></ul><p>When the connection is terminated, the TTY session record is also closed and is also available for viewing in the operator web interface.</p><h4>SSH/TELNET</h4><p>Popular protocols for connection are implemented. Connection is performed by starting a child process, and if necessary, a chain of Jump hosts is started.</p><h4>SFTP</h4><p>A separate file transfer interface is launched and, if necessary, a connection chain is formed if the node is not directly accessible.</p><h4>IPMI/iLo</h4><p>At the moment, viewing the recording is not available, but this type of connection is regulated by a separate set of user rights. For the current connection, a recording of the user’s network traffic will be launched, this dump will be available for downloading through the operator interface.</p><h4>Services</h4><p>Sometimes just connecting to the destination node is not enough, for example you need to connect to the database on the node using locally installed software (e.g. <a href="https://www.pgadmin.org/">pgadmin</a>). The access system allows you to create and connect these services to nodes.</p><p>After connecting the service, the access system begins to register user traffic and becomes accessible from the operator’s interface.</p><h3>Database</h3><p>The database is used not only to store data but also to store the current state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*gQ2qQ14eeMFcd3ht.png" /></figure><p>To work with the database and access it, the ORM <a href="https://www.sqlalchemy.org/">SQLAlchemy</a> library is used.</p><blockquote>Note</blockquote><blockquote>Object-relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between a relational database and the memory (usually the heap) of an object-oriented programming language. This creates, in effect, a virtual object database that can be used from within the programming language.</blockquote><p>What I liked:</p><ul><li>Working with records/tables as objects</li><li>Description of tables in code</li><li>Integration with <a href="https://alembic.sqlalchemy.org/en/latest/tutorial.html">alembic</a></li></ul><p>The only thing I didn’t like was the high entry threshold.</p><p>For the initial filling of the database and update management, <a href="https://alembic.sqlalchemy.org/en/latest/tutorial.html">alembic</a> is used, this is not a simple tool and also requires learning, but it is worth it, the tool allows you to store the state of the database and when calling the update <a href="https://alembic.sqlalchemy.org/en/latest/tutorial.html">alembic</a> will automatically transfer the database to the current state.</p><h3>Firewall</h3><p>One of the modules <a href="https://github.com/DerNitro/pyRMA"><strong>pyRMA</strong></a> is a network traffic management subsystem named after the <a href="https://linux.die.net/man/8/iptables">iptables</a> rules management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N911aqheDctJOpxD.png" /></figure><p>This module runs as a system service. There is a separate table in the database where the current rules are entered, the service collects these rules and updates the iptables rules.</p><p>This service also manages the recording of network traffic and the storage of information about it in the user session.</p><h3>Web interface</h3><p>Administration and viewing of the user session is carried out via the web interface. The web service is written in <a href="https://flask.palletsprojects.com/en/stable/">Flask</a>, the CSRF token mechanism is additionally integrated via <a href="https://pypi.org/project/Flask-WTF/">Flask-WTF</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ckO7aqc_vz8xlcLE.png" /></figure><p>The web interface is available to all users, however access to information is only possible in accordance with the granted rights.</p><p>Since our system does not store authentication data and is completely tied to <a href="https://www.man7.org/linux/man-pages/man8/pam.8.html">Linux PAM</a>, we also use this authentication mechanism here. The <a href="https://pypi.org/project/python-pam/">python-pam</a> module makes it easy to check authentication data</p><pre>&gt;&gt;&gt; import pam<br>&gt;&gt;&gt; p = pam.authenticate()<br>&gt;&gt;&gt; p.authenticate(&#39;user&#39;, &#39;correctpassword&#39;)<br>True<br>&gt;&gt;&gt; p.authenticate(&#39;user&#39;, &#39;badpassword&#39;)<br>False</pre><p>The functions were also implemented through a web interface:</p><p><strong>monitoring</strong></p><p>Allows you to track the number of active connections, new users and pending connection requests.</p><pre>in  &gt; curl -u username:password -X GET http://pyrma:8080/api/monitor<br>out &gt; {<br>out &gt;     &quot;active_connection&quot;: 0,<br>out &gt;     &quot;new_user&quot;: 0,<br>out &gt;     &quot;access_request&quot;: 0<br>out &gt; }</pre><p><strong>Loading node data</strong></p><p>Creating nodes manually is fine, but if you have a lot of them, you can use upload, which requires a CSV file.</p><pre>in  &gt; curl -u username:password -X POST -H &quot;Content-Type: multipart/form-data&quot; -F &#39;file=@tests/eggs.csv&#39; http://pyrma:8080/api/host/upload<br>out &gt; {<br>out &gt;     &quot;status&quot;: &quot;success&quot;,<br>out &gt;     &quot;created host&quot;: 0,<br>out &gt;     &quot;updated host&quot;: 1000,<br>out &gt;     &quot;skipped host&quot;: 0<br>out &gt; }</pre><h3>User access rights</h3><p>User rights are divided into 2 groups:</p><p><strong>connection:</strong></p><ul><li>Connecting to a node</li><li>File transfer</li><li>Connecting services together with connecting to a node</li><li>Connecting services only</li><li>Connecting to the server management interface</li></ul><p><strong>Custom Actions:</strong></p><ul><li>View node information</li><li>Editing node information</li><li>Create/Edit Directories</li><li>Moving nodes between directories</li><li>Display login</li><li>Display password</li><li>View user session</li><li>Access coordination</li><li>Editing connection credentials</li></ul><p>Rights are stored in the database as a single integer.</p><pre>11100 = 28<br>││││└── Connecting to the server management interface<br>│││└── Connecting services only<br>││└── Connecting services together with connecting to a node<br>│└── File transfer<br>└── Connecting to a node</pre><p>This approach seemed more manageable to me, using logical addition for nested directories we get the final result of user rights</p><pre>ROOT                                        00000<br>└── Level1                                + 10000<br>    └── Level2                            + 01101<br>        └── Host1                         = 11101</pre><p>In order for a user to be able to use the access system, a group to which the user belongs must be registered in the system. For a registered group, you can set rights and grant access to all nodes or a group of nodes.</p><p>If the user does not have access to connect to the node, he can use the access system to generate an access request, which the “operator” can accept or reject.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*yv-miyxdAPrYosHr.png" /></figure><h3>Install</h3><p>For installation, an Ansible script was prepared, which completely performs the installation and startup of the access system.</p><h3>Afterword</h3><p>The development of the current project lasted an indecently long time — 6 years, from 2016 to 2022. Combining work for hire, family and solving everyday problems leaves no time for development.</p><p>That’s why I decided to put the code on GitHub, maybe someone will be interested in these developments and start contributing to the project or fork the repository.</p><p><strong>[</strong><a href="https://su-blog.ru/en/posts/2025/01/07/pyrma-ili-kak-ia-pisal-sistemu-dostupa/#footnote-reference-1"><strong>1</strong></a><strong>] </strong>The system itself does not have the entities “user”, “operator” and “administrator”, the division is carried out on the basis of the issued rights.</p><p><strong>[</strong><a href="https://su-blog.ru/en/posts/2025/01/07/pyrma-ili-kak-ia-pisal-sistemu-dostupa/#footnote-reference-2"><strong>2</strong></a><strong>] </strong>Services in the access system are system software on the destination node that has a socket for connection via the TCP or UDP protocols.</p><p><em>Originally published at </em><a href="https://su-blog.ru/en/posts/2025/01/07/pyrma-ili-kak-ia-pisal-sistemu-dostupa/"><em>https://su-blog.ru</em></a><em> on January 30, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e653bc9e3543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Small CI for a small blog]]></title>
            <link>https://dernitro.medium.com/small-ci-for-a-small-blog-21b2d2145483?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/21b2d2145483</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 21:00:53 GMT</pubDate>
            <atom:updated>2024-12-30T05:28:27.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y00Poplv7sRhHQiB.jpg" /></figure><p>Photo by <a href="https://unsplash.com/@collab_media?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Collab Media</a> on <a href="https://unsplash.com/photos/a-machine-room-with-lots-of-machines-inside-of-it-lFqw0SGbd7Q?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p><p>I haven’t written in the blog for a long time, it’s time to fix that.</p><p>And so recently I finally got around to writing a CI/CD process for automatically rolling out new articles on adult topics through the version control system.</p><p>Let’s see what came of it.</p><p>A blog can be viewed as a product, and each new article as an improvement and a new version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cHurN44CHokcjEI3.png" /></figure><p>If we consider the canonical representation of the CI( <em>continuous integration</em>) process, as in the figure above, then we can identify the following steps:</p><ul><li><strong>Commit</strong> — confirming that the system is operational at a technical level. At this stage, the application is compiled and runs through a set of automated tests. In addition, code analysis is performed at this stage.</li><li><strong>Auto tests</strong> and <strong>Performance tests</strong> — confirming that the system works at the functional and non-functional levels. At this stage, it is also checked whether the system behavior meets the needs of users and the requirements of the specification.</li><li><strong>Manual tests</strong> — research and testing are carried out, the usability of the application is assessed, the appearance and behavior of the system on various platforms is checked.</li><li><strong>Release</strong> — delivering the system to users as a packaged application or by deploying it to production and debug environments.</li></ul><p>Below we’ll cover all of these steps, excluding automated tests, and how to use them to deploy a blog.</p><h3>Commit</h3><blockquote><em>The commit phase begins with a change in the project state that is committed to the version control system and ends with a bug report or, if the phase is successfully completed, the creation of a set of binary artifacts and deployable builds that are used in subsequent testing and delivery phases of the release.</em></blockquote><blockquote><em>-Jez Humble and David Farley</em></blockquote><p><a href="https://git-scm.com/">Git</a> as a distributed version control system has long since established itself as the best system and <a href="https://habr.com/ru/articles/233935/">a survey conducted back in 2014 on habr</a> already then showed usage statistics of over 70%, so the choice of a version control system was obvious.</p><p>The largest web service at the moment <a href="https://github.com/DerNitro/su-blog.ru">GitHub</a> was chosen as a hosting for git repositories, here are some reasons for the choice:</p><ul><li><strong>Codespaces</strong> lets you start coding faster with fully configured and secure cloud development environments built into GitHub.</li><li><strong>Issues</strong> Create issues, break them down into tasks, track relationships, add custom fields, and lead discussions.</li><li><strong>Code Review</strong> Every pull request has lightweight code review tools built into it.</li><li><strong>GitHub Actions</strong> simplifies automation of all software workflows. Create, test, and deploy your code directly from GitHub.</li></ul><p>So, we figured out how to store the code, but what kind of code will it be? Searching for tools led me to the project <a href="https://getnikola.com/">Nikola — Static Site Generator</a>, several features of the tool:</p><ul><li><strong>Generate static HTML content</strong>: Static websites are safer, use fewer resources, and avoid vendor and platform lock-in. You can host a Nikola website on any web server, big or small. It’s just a bunch of HTML files and data.</li><li><strong>Fast and incremental builds</strong>: Nikola is fast. It uses <a href="http://pydoit.org/">doit</a>, which provides incremental builds — in other words, it only rebuilds the pages that need it.</li><li><strong>Multiple format support</strong>: reStructuredText, Markdown, IPython (Jupyter) Notebooks, and HTML are supported initially, and plugins are available for many other formats.</li><li><strong>Built-in components</strong>: Nikola comes with everything you need to create a modern website: a blog (with comments, tags, categories, archives, RSS/Atom feeds), easy-to-use image galleries and code listings.</li><li><strong>Multi-language support</strong>: You can write posts in multiple languages ​​and have links between different versions of the post.</li><li><strong>CLI available</strong>: allows you to create projects, templates for new posts and pages.</li><li><strong>Built-in web server</strong>.</li></ul><p>As mentioned above, as an output artifact we get static HTML code, which we can then use both as a release and in a test environment. There is no point in storing this artifact separately, since its assembly does not take much time and computing resources, so I perform data assembly directly when creating the stand.</p><p>This solution has a number of pros and cons.</p><ul><li>+ The speed of assembly is achieved due to previously collected data.</li><li>+ Reduced computing resource usage</li><li>+ There is no need to store data and control its cleaning.</li><li>- When you delete page files, the pages and data collected before deletion remain.</li></ul><p>As a source, I chose the <strong>reStructuredText</strong> format. A huge plus is that, unlike Markdown, it has an extended syntax. But there is also a huge minus: the syntax has to be remembered every time if you rarely use it.</p><p>So, to summarize, we have a tool called Nikola to create a blog from code, and that code is stored in our version control system. Next, we put together a build pipeline.</p><p>The test and production environments should be as close and reproducible as possible. Therefore, we will launch in a container, a number of advantages:</p><ul><li>Configuration is stored in the code</li><li>Can be run locally</li><li>Fast build if there is a cache</li><li>Runs on any modern Linux OS</li><li>Isolated environment from the host system</li></ul><p>We will launch containers through the <a href="https://docs.docker.com/compose/">docker compose</a> utility, using environment variables, we can create both production and test environments.</p><p>The environment is created, let’s start testing:</p><ol><li><strong>Building the environment</strong>, since a new version can be not only the addition of a new post, but also an update of the environment itself, we must be completely sure that it is built.</li><li><strong>Running linters</strong>, since our source data is stored in <em>reStructuredText</em>, it is advisable to check its syntax before building, for this we will use the <a href="https://pypi.org/project/restructuredtext-lint/">restructuredtext-lint</a> package, which allows us to quickly check our code for syntax errors.</li><li><strong>Building static content</strong>, at this stage we will receive the generated HTML content, or learn about a build error.</li><li>Well, since our product is a blog, we <strong>check the spelling</strong>. After much research, the best results for working with the Russian language were shown by the <a href="https://github.com/facelessuser/pyspelling">pyspelling</a> package in conjunction with <a href="https://hunspell.github.io/">hunspell</a>.</li></ol><p>Now, to avoid confusion in the order of the steps, let’s combine them. Here I found it appropriate to use the <a href="https://www.gnu.org/software/make/">GNU make</a> tool, it looks simpler than a bash script, and due to target and dependencies you can form usage scenarios, so we have the following:</p><ul><li>build — Build environment, linters, static data assembly</li><li>test — Run spell checker</li><li>start — Run application</li><li>stop — Stop application</li><li>console — Additional target for diagnosing application operation in the environment.</li></ul><p>Also in Makefile we define the current state and parameters of the environment, and if it is the main branch of the version control system then this tells us that we need to start the production environment, and if the branch does not correspond to main then the test one.</p><h3>Manual testing</h3><p>And now the article is written, it’s time to create a Pull Request in the version control system for the main branch. And this is where the CI process will start, which will prepare a test environment for us, which we can see with our own eyes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iz80VUZVqjQGy3QB.png" /></figure><p>In The GitHub project has prepared self-hosted runners, one for each test and production environment. GitHub Actions, upon catching a pull request from the main branch, will run a task to create the environment in the test environment.</p><p>The test environment will be launched in a separate Docker container and will be accessible through a separate domain name <a href="https://dev.su-blog.ru/">dev.su-blog.ru</a></p><p>Once you have verified the display and functionality, you can proceed to merging into the main branch.</p><h3>Release</h3><p>As soon as a new commit appears in the main branch, the production environment update will be triggered. The only difference from creating a test environment is that the launch occurs on a separate self-hosted runner, the environment parameters are generated automatically based on the version control system branch.</p><h3>Conclusions</h3><p>I didn’t want to be a shoemaker without shoes, and this prompted me to put together a small but functional conveyor belt for the blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NwY_Mw96Fs176l4U.png" /></figure><p>Schematically it looks like this now.</p><p><em>Originally published at </em><a href="https://su-blog.ru/en/posts/2024/11/21/small-ci-for-a-small-blog/"><em>https://su-blog.ru</em></a><em> on December 29, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21b2d2145483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pyRegistryStore — Or how to create a register of objects]]></title>
            <link>https://dernitro.medium.com/pyregistrystore-or-how-to-create-a-register-of-objects-39991165ee40?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/39991165ee40</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 04:47:37 GMT</pubDate>
            <atom:updated>2021-07-15T04:47:37.404Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://su-blog.ru/en/posts/2021/05/24/pyregistrystore-or-how-to-create-a-register-of-objects/">pyRegistryStore — Or how to create a register of objects</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hT7AFWkC7YKsaT9L.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@alfonsmc10?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alfons Morales</a> on <a href="https://unsplash.com/s/photos/bookshelf?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Good afternoon colleague!</p><p>The history of the creation of this post is very interesting, it all started with the fact that I planned to write a little about the PyYAML library and how we domesticated it, but something went wrong, and all this resulted in the creation of a utility <a href="https://github.com/DerNitro/pyRegistryStore">pyRegistryStore</a></p><p>Let’s go…</p><h3>Starting…</h3><p>Any CI / CD automation has reference books, registries, test environments, analyzers, source code control systems, and this is all controlled by the orchestrator.</p><p>Our small group prepares and tests images of virtual machines + development of Ansible roles for installing the necessary software according to the role model.</p><p><strong>Task</strong> — There is a set of “Roles” — testing automation is required when a new image of a virtual machine appears and the test results successful / unsuccessful are written to the <strong>registry</strong>.</p><p>The task was completed, a script was written using PyYAML, and so far it copes with its task.</p><p>This solution seemed to me very interesting and I decided to tell a little about it, but since I am by nature more practitioners than a theoretician, I realized that what examples would be needed, and then everything went wrong as intended.</p><p>I could not use the script written at work, because there are quite a few letters on intellectual property in my contract. Therefore, I started writing examples from scratch and only describing the topic of the planned article…</p><p>At some point in time when writing the code, I realized that it would be nice to have a utility for creating a registry of objects, and objects should be dynamic, no hardcode, it should be possible for the user to create object templates by himself, spending a minimum of effort.</p><p>The result was <a href="https://github.com/DerNitro/pyRegistryStore">pyRegistryStore</a>.</p><p>Let’s go…</p><h3>PyYAML</h3><p><a href="http://yaml.org/">YAML</a> has grown from a markup language to a powerful data serialization tool.</p><pre>%YAML 1.2<br>---<br>YAML: YAML Ain&#39;t Markup Language<br><br>What It Is: YAML is a human friendly data serialization<br>standard for all programming languages.</pre><p>Data serialization is done through strict markup rules and the ability to specify tags, both global and local.</p><p>One of the frameworks for Python is <a href="https://pypi.org/project/PyYAML/">PyYAML</a>, which, based on tags, can save Python classes as yaml files.</p><p>This is exactly the given serialization/deserialization of objects used in the utility <a href="https://github.com/DerNitro/pyRegistryStore">pyRegistryStore</a></p><p>Let’s look at examples of using the utility.</p><h3>Object “Image VM”</h3><p>This type of object will describe all existing VM images for which we need to develop.</p><p>We will determine the requirements that we need to store information:</p><ul><li>Name</li><li>Distribution kit</li><li>Version</li><li>Kernel Linux</li><li>LTS</li></ul><p>We describe the object in <a href="https://github.com/DerNitro/pyRegistryStore">pyRegistryStore</a></p><pre>import objects<br><br>class Image(objects.RegistryStore):<br>    &quot;&quot;&quot;<br>    Image Object<br><br>    Parameters<br>    ----------<br>    name: str<br>        Name image<br>    distr: str<br>        Distribution kit<br>    version: str<br>        Version distr<br>    kernel: str<br>        Kernel Linux<br>    lts: bool<br>        Long term support<br>    &quot;&quot;&quot;<br>    uniq_key = [&#39;name&#39;]<br>    desc = &#39;Object image VM&#39;<br><br>    def __init__(self) -&gt; None:<br>        super().__init__()</pre><h3>Object “Ansible role”</h3><p>This object will describe successful tests of passing software rolling on VM images.</p><p>We will determine the requirements that we need to store information:</p><ul><li>Name</li><li>Image VM</li><li>Commit GIT</li><li>State</li></ul><p>The following code turned out</p><pre>import objects<br><br><br>class Role(objects.RegistryStore):<br>    &quot;&quot;&quot;<br>    Image Object<br><br>    Parameters<br>    ----------<br>    name: str<br>        Name role<br>    image: str<br>        Name image VM<br>    commit: str<br>        Commit GIT<br>    status: bool<br>        Success<br>    &quot;&quot;&quot;<br>    uniq_key = [&#39;name&#39;, &#39;image&#39;, &#39;status&#39;]<br>    desc = &#39;Object Ansible role&#39;<br><br>    def __init__(self) -&gt; None:<br>        super().__init__()</pre><h3>Pipeline</h3><p>At the moment, we have an empty object registry, let’s create 2 pipelines to work with this registry.</p><h3>Creating an image registry</h3><p>Creating an image is not a tricky process, we take a blank, update packages, install the necessary software and send it further along the business process.</p><p>We fill in the register:</p><pre>pyRegistryStore.py image set name=ubuntu_20.04_v0.image distr=ubuntu version=20.04 kernel=5.4.0-73-generic lts=true<br>pyRegistryStore.py image set name=centos_7_v0.image distr=centos version=7 kernel=3.10.0-1160.el7.x86_64 lts=true</pre><p>In total, we got 2 images that we can use further:</p><pre>pyRegistryStore.py image get | jq<br>[<br>    {<br>        &quot;_meta&quot;: {<br>            &quot;create_time&quot;: &quot;2021-05-27 06:07:19.950055&quot;,<br>            &quot;update_time&quot;: &quot;2021-05-27 06:07:19.950064&quot;,<br>            &quot;version&quot;: 1,<br>            &quot;uuid&quot;: &quot;95abb4e1-ed8f-42a0-b0b0-5496e91a7b58&quot;<br>        },<br>        &quot;distr&quot;: &quot;ubuntu&quot;,<br>        &quot;kernel&quot;: &quot;5.4.0-73-generic&quot;,<br>        &quot;lts&quot;: true,<br>        &quot;name&quot;: &quot;ubuntu_20.04_v0.image&quot;,<br>        &quot;version&quot;: &quot;20.04&quot;<br>    },<br>    {<br>        &quot;_meta&quot;: {<br>            &quot;create_time&quot;: &quot;2021-05-27 06:25:26.587628&quot;,<br>            &quot;update_time&quot;: &quot;2021-05-27 06:25:26.587637&quot;,<br>            &quot;version&quot;: 1,<br>            &quot;uuid&quot;: &quot;ab2fba4b-b9d0-4c05-8860-50f14580395a&quot;<br>        },<br>        &quot;distr&quot;: &quot;centos&quot;,<br>        &quot;kernel&quot;: &quot;3.10.0-1160.el7.x86_64&quot;,<br>        &quot;lts&quot;: true,<br>        &quot;name&quot;: &quot;centos_7_v0.image&quot;,<br>        &quot;version&quot;: 7<br>    }<br>]</pre><h3>Create Ansible Role Registry</h3><p>Let me remind you that the tasks of our group also include the development of Ansible roles for rolling out to VM images, and we must be completely sure that the current version of the role has successfully passed the rolling out and all synthetic tests.</p><p>Our testing stack looks like this:</p><ul><li>Jenkins</li><li><a href="https://molecule.readthedocs.io/en/latest/">Molecula</a></li><li><a href="https://testinfra.readthedocs.io/en/latest/">testinfra</a></li><li>Registry of images VM and Ansible roles.</li></ul><p>Yes, I was not mistaken in writing the registry, and not <a href="https://github.com/DerNitro/pyRegistryStore">pyRegistryStore</a>, since I wrote earlier that this project appeared spontaneously, but I plan to switch to pyRegistryStore.</p><p>And so let’s say we have a small role to set up and configure time synchronization with local NTP. Let’s call it <strong>ntp-client</strong></p><p>The first thing we need is to get a list of all available images:</p><pre>pyRegistryStore.py image get | jq .[].name<br>&quot;ubuntu_20.04_v0.image&quot;<br>&quot;centos_7_v0.image&quot;</pre><p>In total, we have 2 images, or to be more precise, <strong>a list of images</strong> on which we must test our role.</p><p>And since we have a list, we can organize a loop:</p><p><strong>check if the test for the image was successful for the current commit</strong></p><pre>pyRegistryStore.py role get name=ntp-client image=ubuntu_20.04_v0.image commit=b312abbb05a9be4fe82abcb60d44b7bdd0220bdc status=true</pre><p>as expected, the list turned out to be empty, which means we need to check this role on this VM image, if we received a list for the output, then we can skip testing.</p><p><strong>We run the Molecula, we run the tests, if we catch success, we write the information to the registry</strong></p><pre>pyRegistryStore.py role set name=ntp-client image=ubuntu_20.04_v0.image commit=b312abbb05a9be4fe82abcb60d44b7bdd0220bdc status=true</pre><p>well, if the tests were not successful, then just change the status = true key to status = false</p><p>Let’s say our tests passed like this:</p><pre>pyRegistryStore.py role get name=ntp-client | jq<br>[<br>{<br>    &quot;_meta&quot;: {<br>        &quot;create_time&quot;: &quot;2021-05-28 07:01:01.470657&quot;,<br>        &quot;update_time&quot;: &quot;2021-05-28 07:01:01.470665&quot;,<br>        &quot;version&quot;: 1,<br>        &quot;uuid&quot;: &quot;2fc0dabb-ea56-4eba-92de-75eea562f383&quot;<br>    },<br>    &quot;commit&quot;: &quot;b312abbb05a9be4fe82abcb60d44b7bdd0220bdc&quot;,<br>    &quot;image&quot;: &quot;ubuntu_20.04_v0.image&quot;,<br>    &quot;name&quot;: &quot;ntp-client&quot;,<br>    &quot;status&quot;: true<br>},<br>{<br>    &quot;_meta&quot;: {<br>        &quot;create_time&quot;: &quot;2021-05-28 07:05:38.572570&quot;,<br>        &quot;update_time&quot;: &quot;2021-05-28 07:05:38.572578&quot;,<br>        &quot;version&quot;: 1,<br>        &quot;uuid&quot;: &quot;c13a5266-8949-4d07-9c4e-8955d1cb3a8a&quot;<br>    },<br>    &quot;commit&quot;: &quot;b312abbb05a9be4fe82abcb60d44b7bdd0220bdc&quot;,<br>    &quot;image&quot;: &quot;centos_7_v0.image&quot;,<br>    &quot;name&quot;: &quot;ntp-client&quot;,<br>    &quot;status&quot;: false<br>}<br>]</pre><h3>Conclusion</h3><p>And so we got the following:</p><ul><li>There is a list of images to which we can automatically add new images</li><li>List of passing tests by role</li><li>Last successful commit for the image</li><li>Automate testing of new images</li></ul><p><strong>What’s next?</strong></p><p>Further, I plan to develop the utility, expanding the functionality. If this utility has its own community, I will be very happy.</p><p>I hope I haven’t bored anyone, and this material will be useful to someone, and someone will get some ideas for themselves for inspiration.</p><p><strong>Thank you for reading this article.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39991165ee40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parsing ini files]]></title>
            <link>https://dernitro.medium.com/parsing-ini-files-a17c8da6a99e?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a17c8da6a99e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 04:45:15 GMT</pubDate>
            <atom:updated>2021-03-15T04:45:15.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVC_xTtmEAjtxmSFX75zkw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sincerely Media</a> on <a href="https://unsplash.com/s/photos/file?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Good afternoon, casual reader.</p><p>For one project, it was required to get the value of a variable from an ini file.</p><p>And it seems like the solution is simple, a one-line script like:</p><pre>grep dbname db.conf | awk -F &#39;=&#39; &#39;{ print $2 }&#39;</pre><p>But what if there are several values in different sections? Then a one-line script will not work anymore.</p><p>Search for a solution for linux gave no results :(, although maybe I’m just lazy and have not looked through all the search results.</p><p>The decision was made quickly, we take Python and the configparser package. Result <a href="https://github.com/DerNitro/ini-file">ini-file</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a17c8da6a99e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Низкоуровневый анализ блочных устройств]]></title>
            <link>https://dernitro.medium.com/%D0%BD%D0%B8%D0%B7%D0%BA%D0%BE%D1%83%D1%80%D0%BE%D0%B2%D0%BD%D0%B5%D0%B2%D1%8B%D0%B9-%D0%B0%D0%BD%D0%B0%D0%BB%D0%B8%D0%B7-%D0%B1%D0%BB%D0%BE%D1%87%D0%BD%D1%8B%D1%85-%D1%83%D1%81%D1%82%D1%80%D0%BE%D0%B9%D1%81%D1%82%D0%B2-93ac4057e61e?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ac4057e61e</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[block-devices]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 11:03:18 GMT</pubDate>
            <atom:updated>2020-12-13T11:03:18.059Z</atom:updated>
            <content:encoded><![CDATA[<h3>Низкоуровневый анализ блочных устройств Linux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3NmK_vE4cY-VpS1KSsl7g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@0asa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vincent Botta</a> on <a href="https://unsplash.com/s/photos/hdd?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Добрый день, коллеги!</strong></p><p>В данной статье я хотел бы рассказать и показать как проводить низкоуровневый анализ производительности и работы блочных устройств в Linux.</p><p>Для работы на потребуется утилита <strong><em>blktrace</em></strong>, установка в CentOS 7 выглядит следующим образом:</p><pre>[root@centos7 ~]# yum install -y blktrace</pre><p>Первое что нам нужно сделать это, запустить запись дампа, всех событий отправленных на устройство.</p><pre>[root@centos7 blktrace]# blktrace -d /dev/sda -o sda</pre><p>В данной команде мы указываем через ключ <strong>-d</strong> наше устройство, и через ключ <strong>-o</strong> файл который будет содержать наш дамп.</p><p>Файл дампа <em>бинарный</em>, и что бы вывести содержимое в человекочитаемом виде запустим утилиту <strong><em>blkparse</em></strong><em>(которая входит в пакет blktrace)</em>.</p><pre>[root@centos7 blktrace]# blkparse -i sda.blktrace.0 <br>Input file sda.blktrace.0 added<br> 8,2 0 1 0.000000000 1322 A FWS 0 + 0 &lt;- (253,0) 0<br> 8,0 0 2 0.000001836 1322 Q FWS [kworker/0:3]<br> 8,0 0 3 0.000007583 1322 G FWS [kworker/0:3]<br> 8,0 0 4 0.000008596 1322 P N [kworker/0:3]<br> 8,0 0 5 0.000011182 1322 I FWS [kworker/0:3]<br> 8,0 0 6 0.000013240 1322 U N [kworker/0:3] 1<br> 8,2 0 7 0.000260525 393 A WM 1682144 + 32 &lt;- (253,0) 736<br> 8,0 0 8 0.000261325 393 A WM 3781344 + 32 &lt;- (8,2) 1682144<br> 8,0 0 9 0.000262451 393 Q WM 3781344 + 32 [xfsaild/dm-0]<br>…<br>CPU0 (sda):<br> Reads Queued: 8, 620KiB Writes Queued: 37, 689KiB<br> Read Dispatches: 8, 620KiB Write Dispatches: 29, 689KiB<br> Reads Requeued: 0 Writes Requeued: 0<br> Reads Completed: 8, 620KiB Writes Completed: 41, 689KiB<br> Read Merges: 0, 0KiB Write Merges: 2, 20KiB<br> Read depth: 1 Write depth: 8<br> IO unplugs: 18 Timer unplugs: 0<br>Throughput (R/W): 6KiB/s / 7KiB/s<br>Events (sda): 339 entries<br>Skips: 0 forward (0–0.0%)</pre><p>Данный вывод состоит из 2 блоков,</p><ol><li>события(на подобии tcpdump)</li><li>статистика, которая разбита по ядрам CPU</li></ol><h4>События</h4><p>Стандартный вывод статистики состоит из следующих полей данных</p><blockquote>%D %2c %8s %5T.%9t %5p %2a %3d</blockquote><p><strong>%D</strong> — Устройство, на котором было выполнено событие, Мажорная и минорная версия, соотношение можно посмотреть через вывод утилиты <strong><em>lsblk</em></strong></p><pre>[root@centos7 blktrace]# lsblk<br>NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT<br>sda <strong>8:0</strong> 0 8G 0 disk <br>├─sda1 <strong>8:1</strong> 0 1G 0 part /boot<br>└─sda2 <strong>8:2</strong> 0 7G 0 part <br> ├─centos_centos7-root <strong>253:0</strong> 0 6,2G 0 lvm /<br> └─centos_centos7-swap <strong>253:1</strong> 0 820M 0 lvm [SWAP]<br>sr0 11:0 1 1024M 0 rom</pre><p><strong>%2c </strong>— Номер ядра CPU, которое обрабатывало данное событие.</p><p><strong>%8s</strong> — Порядковый номер события</p><p><strong>%5T.%9t</strong> — Секунды и наносекунды с момента запуска дампа.</p><p><strong>%5p</strong> — PID процесса</p><p><strong>%2a</strong> — Действие с блоком данных, основные это:<br><strong>С — complet. </strong>Запрос выполнен, но это не означает что он выполнен успешно.<strong><br>Q — queued. </strong>Проверка очереди.<br><strong>A — remap. </strong>Передача события на устройство ниже. Например с LVM на диск.<br><strong>G — get request. </strong>Отправка запроса на устройство для выделения контейнера структуры данных.<br><strong>I — inserted. </strong>Добавление в очередь планировщика Linux.<br><strong>D — issued. </strong>Передача блока на драйвер устройства.<br><strong>M — back merge, F — front merge. </strong>Есть блоки которые имеют общую границу данных, и могут быть объедены в одну операцию.</p><p><strong>%3d — </strong>RWBS поле, где:<br><strong>R</strong> — чтение, <strong>W</strong> — запись, <strong>D </strong>— отмена операции, <strong>B </strong>— барьерная операция, <strong>S</strong> — синхронизация.</p><h4>Статистика</h4><p>После событий идет блок статистики по ядрам CPU, в которой агрегирована информация по всем действиям, сколько событий было, сколько было смерженых событий и выполненных.</p><h4>Практическое применение</h4><p>Запускаем запись дампа на устройстве <strong>SDA</strong></p><pre>[root@centos7 blktrace]# blktrace -d /dev/sda -o sda</pre><p>В другой консоли запускаем тестовое события записи данных на блочное устройство</p><pre>[root@centos7 ~]# sync; echo 1 &gt; /proc/sys/vm/drop_caches <br>[root@centos7 ~]# dd if=/dev/urandom of=/tmp/test bs=4k count=1024 &amp;<br>[1] <strong>3944</strong></pre><blockquote>Символ <strong>&amp;</strong> поставил в конце команды, что бы отправить ее в фоновое выполнение и получить PID процесса.<br>Так же требуется сбросить дисковый кеш.</blockquote><pre>[root@centos7 blktrace]# blkparse -i sda.blktrace.0 | awk &#39;$5==3944 {print}&#39; | wc -l<br>324</pre><p>Всего получилось событий 324, все их рассматривать не будем, разобьем на 2 этапа, чтение и запись.</p><h4>Чтение</h4><p>Возникает вопрос, откуда у нас в данном дампе чтение, если мы читали из псевдоустройства, ответ — т.к. перед запуском команды мы сбрасывали дисковый кеш, то для поднятия команды и зависимых библиотек потребовалось чтение с дисков.</p><p>Возьмем чтение одного блока и что мы видим:</p><pre>[root@centos7 blktrace]# blkparse -i sda.blktrace.0 | awk &#39;$5==3944 || $5==0  {print}&#39; | grep &quot;13560296\|11461096&quot;<br>  8,2    0       <strong>91</strong>     4.746796216  3944  A   R 11461096 + 32 &lt;- <strong>(253,0) 9779688</strong><br>  8,0    0       <strong>92</strong>     4.746797670  3944  A   R 13560296 + 32 &lt;- <strong>(8,2) 11461096</strong><br>  8,0    0       <strong>93</strong>     4.746799869  3944  Q   R 13560296 + 32 [bash]<br>  8,0    0       <strong>94</strong>     4.746809045  3944  G   R 13560296 + 32 [bash]<br>  8,0    0       <strong>96</strong>     4.746814636  3944  I   R 13560296 + 32 [bash]<br>  8,0    0       <strong>98</strong>     4.746820116  3944  D   R 13560296 + 32 [bash]<br>  8,0    0       <strong>99</strong>     4.761404769     0  C   R 13560296 + 32 [0]</pre><p><strong>91 </strong>— событие пришло на устройство 8,2 и выполнился <strong>remap</strong> на устройство 8,0. При этом хвост сообщения(&lt;- (253,0) 9779688) нам говорит, что и это событие пришло нам с устройства <strong>253,0</strong>, но так как дамп мы снимали с устройства 8,0 мы его не видим. Так же обратите внимание что сам блок меняется, так как у каждого устройства он свой.<br>lsblk — поможет нам определить трассировку события</p><pre>[root@centos7 blktrace]# lsblk<br>NAME                    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT<br>sda                       <strong>8:0</strong>    0    8G  0 disk <br>├─sda1                    8:1    0    1G  0 part /boot<br>└─sda2                    <strong>8:2</strong>    0    7G  0 part <br>  ├─centos_centos7-root <strong>253:0</strong>    0  6,2G  0 lvm  /<br>  └─centos_centos7-swap 253:1    0  820M  0 lvm  [SWAP]<br>sr0                      11:0    1 1024M  0 rom</pre><p><strong>92</strong> — событие <strong>remap</strong> на устройство 8,0</p><p><strong>93</strong> — <strong>queued. </strong>Проверка io очереди.</p><p><strong>94</strong> — <strong>get request</strong>. Проверка готовности устройства.</p><p><strong>96</strong> — <strong>inserted. </strong>Добавление команды чтения в очередь.</p><p><strong>98</strong> — <strong>issued.</strong> Отправка на устройство.</p><p><strong>99</strong> — <strong>complet. </strong>Уведомление от устройства что задача выполнена.</p><p>Если разбирать данное событие то видим что оно выполнилось успешно, за <strong>0.014608553</strong> секунды, что довольно быстро, но если разбить на этапы, то получим что самое медленная операция между 98 и 99 событием <strong>0.14584653</strong> секунды.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*a74ZJEUG4bqXFzs7DwrhlQ.png" /><figcaption>Время выполнения по событиям</figcaption></figure><p><strong>Запись.</strong></p><p>Аналогично проведем проверку одного блока на запись</p><pre>[root@centos7 blktrace]# blkparse -i sda.blktrace.0 | awk &#39;$5==3944 || $5==0  {print}&#39; | grep &quot;5804632\|7903832&quot;<br>  8,2    0      <strong>387</strong>     4.964830989  3944  A   W 5804632 + 1024 &lt;- (253,0) 4123224<br>  8,0    0      <strong>388</strong>     4.964831398  3944  A   W 7903832 + 1024 &lt;- (8,2) 5804632<br>  8,0    0      <strong>389</strong>     4.964832500  3944  Q   W 7903832 + 1024 [bash]<br>  8,0    0      <strong>390</strong>     4.964835923  3944  G   W 7903832 + 1024 [bash]<br>  8,0    0      <strong>391</strong>     4.964837361  3944  I   W 7903832 + 1024 [bash]<br>  8,0    0      <strong>392</strong>     4.964839281  3944  D   W 7903832 + 1024 [bash]<br>  8,0    0      <strong>411</strong>     4.965201318  3944  C   W 7903832 + 1024 [0]</pre><p>Состав событий идентичен как для чтения, повторятся не буду.</p><p>Итоговая временной график следующий</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*qNSeo2WK03jlvQJ1DqMYQQ.png" /></figure><h4>Итоги</h4><p>Как мы видим(и в принципе знаем), что самое узкое место PC — это блочное устройство, но умение пользоваться данным инструментом, может определить другие проблемы, например переполнение очереди, проводить исследование работы планировщиков и т.д.</p><h4>Bonus.</h4><p>Утилита BTT, визуализация дампа )</p><pre>[root@centos7 blktrace]# btt -i sda.blktrace.0 -o sda<br>[root@centos7 blktrace]# cat sda.avg<br>==================== All Devices ====================</pre><pre>ALL           MIN           AVG           MAX           N<br>--------- ------------- ------------- ------------- -----------</pre><pre><strong>Q2Q</strong>       0.000003499   0.169834820   8.225748599         106<br><strong>Q2G</strong>       0.000000420   0.000001949   0.000009176         104<br><strong>G2I</strong>       0.000000715   0.000059087   0.000447256         104<br><strong>Q2M</strong>       0.000000983   0.000001636   0.000002793           3<br><strong>I2D</strong>       0.000000259   0.001408037   0.018125005         104<br><strong>M2D</strong>       0.000659133   0.000666699   0.000675267           3<br><strong>D2C</strong>       0.000101756   0.020238508   0.042954645         107<br><strong>Q2C</strong>       0.000108231   0.021685131   0.051552538         107</pre><pre>==================== Device Overhead ====================</pre><pre>DEV        |       <strong>Q2G</strong>       <strong>G2I</strong>       <strong>Q2M</strong>       <strong>I2D</strong>       <strong>D2C</strong><br>---------- | --------- --------- --------- --------- ---------<br> (  8,  0) |   0.0087%   0.2648%   0.0002%   6.3111%  93.3290%<br>---------- | --------- --------- --------- --------- ---------<br>   Overall |   0.0087%   0.2648%   0.0002%   6.3111%  93.3290%</pre><p>Что это все обозначает:</p><ul><li><strong>Q2Q — </strong>время между трассировками очереди системы</li><li><strong>Q2I</strong> <strong>—</strong> Время, необходимое для вставки или объединения входящего ввода-вывода в запрос очередь.</li><li><strong>Q2G — </strong>Время, необходимое для получения запроса.</li><li><strong>G2I — </strong>Время, необходимое для помещения этого запроса в очередь запросов</li><li><strong>Q2M — </strong>Время на merge</li><li><strong>I2D — </strong>Время, затраченное на очередь запросов.</li><li><strong>D2C — </strong>Время выполнения запроса, с момента передачи на устройство.</li><li><strong>Q2C — </strong>Q2I + I2D + D2C</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ac4057e61e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Тестовое задание для соискателей. Linux.]]></title>
            <link>https://dernitro.medium.com/%D1%82%D0%B5%D1%81%D1%82%D0%BE%D0%B2%D0%BE%D0%B5-%D0%B7%D0%B0%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B4%D0%BB%D1%8F-%D1%81%D0%BE%D0%B8%D1%81%D0%BA%D0%B0%D1%82%D0%B5%D0%BB%D0%B5%D0%B9-linux-10ccfe4e7907?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ccfe4e7907</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[test-task]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 06:24:46 GMT</pubDate>
            <atom:updated>2020-12-11T06:24:46.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="https://unsplash.com/photos/wh-RPfR_3_M?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditShareLink" src="https://cdn-images-1.medium.com/max/1024/1*j0ygxtpcMo74J5j5ESAAGg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@arianismmm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arian Darvishi</a> on <a href="https://unsplash.com/s/photos/linux?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Коллеги, добрый день!</p><p>Перейдя а должность руководителя группы, стал более часто проводить собеседования. И проблема с кадрами, в регионе, дает о себе знать. Выход один — растить специалиста!</p><p>И главный вопрос становится, а готов ли он?! Решено было сделать тестовое задание, которое отправляли потенциальным коллегам.</p><p>Для проверки было создан образ виртуальной машины, специально поломанный. Восстановление данной VM ответит на следующие вопросы:</p><ul><li>Сброс пароля root</li><li>Работа с fstab</li><li>Iptables|firewalld</li><li>Маршрутизация linux</li><li>Сервисы systemd</li><li>LVM</li><li>Расширенные атрибуты файлов</li><li>Восстановление работы PostgreSQL</li><li>Восстановление работы bash скрипта.</li></ul><p>Ну и ссылки на задание :)</p><ul><li><a href="https://yadi.sk/d/zk8SKrg66R8qug">Яндекс</a></li><li><a href="https://drive.google.com/file/d/1MCMFml3RkL8MaUBvhBuM8JrCSUNc2h96/view?usp=sharing">Гугл</a></li></ul><p>Дальше планирую создать еще одну ВМ, для более продвинутых администраторов, так что ждем еще одну статью.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ccfe4e7907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Собираем TCP|UDP сессии в Linux]]></title>
            <link>https://dernitro.medium.com/%D1%81%D0%BE%D0%B1%D0%B8%D1%80%D0%B0%D0%B5%D0%BC-tcp-udp-%D1%81%D0%B5%D1%81%D1%81%D0%B8%D0%B8-%D0%B2-linux-bc633593bd0c?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc633593bd0c</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 04:12:03 GMT</pubDate>
            <atom:updated>2020-12-11T03:22:13.753Z</atom:updated>
            <content:encoded><![CDATA[<p>Приветствую тебя мой дорогой друг!</p><p>Как говорится “назвался компьютерщиком, полезай в ИТ отдел”.</p><h3>Преамбула</h3><p>Попался мне как то на глаза скрипт, для сбора всех соединений по хосту, ну что идея хорошая, запилили в забикс, ждем… 5 минут… 10 минут… Нет значений.</p><p>Ошибка поразила, скрипт не смог уложится в отведенные, забиксом, 30 секунд.</p><p>Тут по идее должна быть картинка типа: “30 секунд, Карл!!!”.</p><p>Не буду описывать свое удивление когда я прочитал скрипт, вкратце это кровь из глаз, куча матерных слов и истеричный смех, т.к. использовалось куча внешних утилит, это все парсилось, накладывались regexp и т.д. и т.п.<br>И это все на Linux, где получить любое значение можно <strong>просто прочитав файл</strong>!!!</p><h3>Начнем…</h3><p>Как я написал выше, для получения значений нам нужно прочитать файл, но какой!? Идем искать ответ.</p><p>Читаем ТЗ, нам нужно:</p><ol><li>TCP|UDP сессия, т.е SRC IP|PORT и DST IP|PORT</li><li>Процесс, который сгенерировал это подключение</li><li>Отображать нужно только LISTEN и ESTAB</li></ol><p>Отлично, можно начинать.</p><h4>Список TCP|UDP</h4><p>За что я люблю Linux системы, это за то что в нем все, это “Файл”:</p><p>Файл -&gt; Файл</p><p>Директория -&gt; Файл</p><p>Устройство -&gt; Файл</p><p>Сокет -&gt; Файл</p><p>…</p><p>Информация о всех tcp/upd сессиях так находится в файлах в /proc/net/tcp[6] и /proc/net/udp[6].</p><pre>sl local_address rem_address  st tx_queue rx_queue tr tm-&gt;when retrnsmt  uid timeout inode                             <br>   0: 0100007F:1B1E 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000    0 53620300 1 0000000000000000 100 0 0 10 0           <br>   1: 0100007F:DFFF 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000    0 46149718 1 0000000000000000 100 0 0 10 0           <br>   2: 0100007F:77CA 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000    0 52642353 1 0000000000000000 100 0 0 10 0</pre><p>По структуре данного формата можно обратится к документации по ядру linux</p><blockquote><a href="https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt"><em>https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt</em></a></blockquote><p>В данной структуре есть практически все, кроме принадлежности к процессу, чего нам не хватает для реализации ТЗ.</p><h4>Процессы</h4><p>Всю информацию о процессе, где можно получить… Правильно из файлов :)</p><p>В том числе и об открытых сокетах, которая хранится в /proc/PID/fd/.</p><p>Вот к примеру:</p><pre>sergey@steel /proc/16381/fd $ for i in $(ls); do readlink $i;done  <br> /dev/null  <br> /dev/null  <br> socket:[49244920]  <br> /dev/urandom  <br> socket:[49244917]  <br> socket:[49245354]  <br> socket:[49244939]  <br> socket:[49244941]  <br> socket:[49234589]  <br> pipe:[49245313]  <br> pipe:[49244937]  <br> pipe:[49244937]</pre><p>Т.е. из данного списка мы можем спокойно забрать только socket, где числовое значение будет значение inode.</p><p>Информацию об имени и pid можно получить из /proc/PID/status.</p><h4>Итого</h4><p>Прочитав несколько файлов и объединив информацию по сессиям и процессам, по ключу <strong>inode</strong>, мы получаем всю нужную информацию.</p><p>Т.к. файловая система <strong>proc</strong> располагается в RAM, то мы не упираемся в очереди блочных устройств, и получаем информацию максимально быстро.</p><p>Получившийся cкрипт можно взять в</p><blockquote>https://github.com/DerNitro/pyTcpProcess</blockquote><p>Что удалось добиться, увеличение скорости с 32 секунд, до 0,3 секунд. Что я считаю хорошим показателем.</p><p>Спасибо за внимание.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc633593bd0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Решение проблемы SSH(pam_limits.so)]]></title>
            <link>https://dernitro.medium.com/%D1%80%D0%B5%D1%88%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BF%D1%80%D0%BE%D0%B1%D0%BB%D0%B5%D0%BC%D1%8B-ssh-pam-limits-so-ab89830ea804?source=rss-5d74053052b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab89830ea804</guid>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[pams]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[DerNitro и все что с ним связано]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 04:11:50 GMT</pubDate>
            <atom:updated>2020-12-10T11:10:15.295Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Коллеги, добрый день!</strong></p><p>Хотелось бы сегодня поделится опытом решения проблемы, за 10 лет практики это было единожды, на восстановление было потрачено неприлично много времени. Ну не буду томить поехали.</p><h4>Проблема.</h4><p>В один момент времени пропал доступ по SSH на сервер СУБД, т.е. как пропал, авторизация и аутентификация проходит, но консоль не отдает. Подключение через iLo — результат тот же.</p><pre><em>[svutkin@db01 ~]$ ssh 192.168.176.252 -l root –vvv<br>…<br>debug1: Authentication succeeded (keyboard-interactive).<br>Authenticated to 192.168.176.252 ([10.108.176.252]:22).<br>debug2: shell request accepted on channel 0<br>…<br>* ********************************************************************<br>* Welcome to ******************* running RedHat 7.4<br>* Puppet hostgroup: Base/Oracle/RDBMS<br>* AD OU: OU=DWH,OU=DB,OU=Linux,OU=UNIX,OU=Servers,DC=********,DC=ru<br>* This system supported by IT-Platform-OS-Unix@*********.<br>* Run ‘sudo -l’ to view your privileges<br>* ********************************************************************<br>…<br></em><strong><em>debug2: channel 0: almost dead</em></strong><em><br>debug2: channel 0: gc: notify user<br>debug2: channel 0: gc: user detached<br>debug2: channel 0: send close<br>debug3: send packet: type 97<br>debug2: channel 0: is dead<br>…<br></em><strong><em>debug1: Exit status 254</em></strong></pre><p>Первые результаты гугления подтвердили предположение о проблеме с PAM(pam_limits.so), и даже был выдан метод решения, а именно снять unlim для пользователей, но каково было удивление когда мы получили доступ, никаких снятых лимитов нет!</p><h4>Что же произошло?</h4><p>А произошло следующие, подключение по SSH к серверу можно разбить на следующие шаги:</p><ol><li>Авторизация/Аутентификация</li><li>Запуск командной оболочки</li><li>Выделение ресурсов пользователю</li></ol><p>Вот как раз на последнем шаге и возникла проблема, как уже выше писал, отвечает за это — pam_limits.so.<br>pam_limits — для выделения ресурсов пользователю, запускается системный вызов <a href="http://www.opennet.ru/man.shtml?topic=setrlimit">setrlimit</a>, помимо выделения ограничений по CPU и RAM, так же выделяется максимальное количество открытых файлов, тут то мы и сели в лужу, лог strace подтвердил что при выделении ресурсов NOFILE происходит ошибка:</p><pre><em>setrlimit(RLIMIT_NOFILE, {rlim_cur=1685744, rlim_max=16815744}) = -1</em></pre><p>Понимаем что значение 1685744(/etc/security/limits.conf) не правильное, но не понимаем почему.<br>Следующий час, решения проблемы, посвятили изучению документации и интернета, и вот что мы узнали:<br>Значение выставляемые в setrlimit для NOFILE не должно превышать значение fs.file-max(cat /proc/sys/fs/nr_open) в ядре, наше значение превышало почти в 3 раза.</p><p>Выравняв значения, проблема решилась.</p><h4>Вывод.</h4><p>Для себя я сделал следующий вывод, бездумное выставление параметров, linux не прощает, всегда нужно быть очень внимательным и осторожным.</p><p>P.S. Если что вредителя нашли(и это был не я), ругать не стали, а провели небольшое обучение, в рамках которого я рассказал об этой проблеме, надеюсь в следующий раз будут умнее.</p><p><a href="https://drive.google.com/open?id=1fZ09yr6cSjQGhihZfrrwBdh6HotoXTVR">Тут</a> можно найти небольшую презенташку, на основе которой я проводил обзор проблемы.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab89830ea804" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>