💾 Archived View for foo.zone › gemfeed › atom.xml captured on 2023-06-14 at 13:55:43.

View Raw

More Information

⬅️ Previous capture (2023-05-24)

➡️ Next capture (2023-07-22)

🚧 View Differences

-=-=-=-=-=-=-

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <updated>2023-06-01T22:09:15+03:00</updated>
    <title>foo.zone feed</title>
    <subtitle>To be in the .zone!</subtitle>
    <link href="gemini://foo.zone/gemfeed/atom.xml" rel="self" />
    <link href="gemini://foo.zone/" />
    <id>gemini://foo.zone/</id>
    <entry>
        <title>KISS server monitoring with Gogios</title>
        <link href="gemini://foo.zone/gemfeed/2023-06-01-kiss-server-monitoring-with-gogios.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-06-01-kiss-server-monitoring-with-gogios.gmi</id>
        <updated>2023-06-01T21:10:17+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Gogios is a minimalistic and easy-to-use monitoring tool I programmed in Google Go designed specifically for small-scale self-hosted servers and virtual machines. The primary purpose of Gogios is to monitor my personal server infrastructure for `foo.zone`, my MTAs, my authoritative DNS servers, my NextCloud, Wallabag and Anki sync server installations, etc.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>KISS server monitoring with Gogios</h1><br />
<br />
<span class='quote'>Published at 2023-06-01T21:10:17+03:00</span><br />
<br />
<a href='./2023-06-01-kiss-server-monitoring-with-gogios/gogios-small.png'><img alt='Gogios logo' title='Gogios logo' src='./2023-06-01-kiss-server-monitoring-with-gogios/gogios-small.png' /></a><br />
<br />
<h2 style='display: inline'>Introduction</h2><br />
<br />
<span>Gogios is a minimalistic and easy-to-use monitoring tool I programmed in Google Go designed specifically for small-scale self-hosted servers and virtual machines. The primary purpose of Gogios is to monitor my personal server infrastructure for <span class='inlinecode'>foo.zone</span>, my MTAs, my authoritative DNS servers, my NextCloud, Wallabag and Anki sync server installations, etc.</span><br />
<br />
<span>With compatibility with the Nagios Check API, Gogios offers a simple yet effective solution for users looking to monitor a limited number of resources. In theory, Gogios scales to a couple of thousand checks, though. In this blog post, we&#39;ll explore Gogios&#39; features, configuration, and use cases to help you determine if it&#39;s the proper monitoring solution for your needs, too. You can clone it from Codeberg here:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/gogios'>https://codeberg.org/snonux/gogios</a><br />
<br />
<pre>
    _____________________________    ____________________________
   /                             \  /                            \
  |    _______________________    ||    ______________________    |
  |   /                       \   ||   /                      \   |
  |   | # Alerts with status c|   ||   | # Unhandled alerts:  |   |
  |   | hanged:               |   ||   |                      |   |
  |   |                       |   ||   | CRITICAL: Check Pizza|   |
  |   | OK-&gt;CRITICAL: Check Pi|   ||   | : Late delivery      |   |
  |   | zza: Late delivery    |   ||   |                      |   |
  |   |                       |   ||   | WARNING: Check Thirst|   |
  |   |                       |   ||   | : OutofKombuchaExcept|   |
  |   \_______________________/   ||   \______________________/   |
  |  /|\ GOGIOS MONITOR 1    _    ||  /|\ GOGIOS MONITOR 2   _    |
   \_____________________________/  \____________________________/
     !_________________________!      !________________________!

------------------------------------------------
ASCII art was modified by Paul Buetow
The original can be found at
https://asciiart.website/index.php?art=objects/computers
</pre>
<br />
<h2 style='display: inline'>Motivation</h2><br />
<br />
<span>With experience in monitoring solutions like Nagios, Icinga, Prometheus and OpsGenie, these tools often came with many features that I didn&#39;t necessarily need for personal use. Contact groups, host groups, check clustering, and the requirement of operating a DBMS and a WebUI added complexity and bloat to my monitoring setup.</span><br />
<br />
<span>My primary goal was to have a single email address for notifications and a simple mechanism to periodically execute standard Nagios check scripts and notify me of any state changes. I wanted the most minimalistic monitoring solution possible but wasn&#39;t satisfied with the available options.</span><br />
<br />
<span>This led me to create Gogios, a lightweight monitoring tool tailored to my specific needs. I chose the Go programming language for this project as it comes, in my opinion, with the best balance of ease to use and performance. Gogios eliminates unnecessary features and focuses on simplicity, providing a no-frills monitoring solution.</span><br />
<br />
<h2 style='display: inline'>Features</h2><br />
<br />
<ul>
<li>Compatible with Nagios Check scripts: Gogios leverages the widely-used Nagios Check API, allowing you to use existing Nagios plugins for monitoring various services.</li>
<li>Lightweight and Minimalistic: Gogios is designed to be simple and fairly easy to set up, making it an ideal choice for users with limited monitoring requirements.</li>
<li>Configurable Check Timeout and Concurrency: Gogios allows you to set a timeout for checks and configure the number of concurrent checks, offering flexibility in monitoring your resources.</li>
<li>Configurable check dependency: A check can depend on another check, which enables scenarios like not executing an HTTP check when the server isn&#39;t pingable.</li>
<li>Retries: Check retry and retry intervals are configurable per check.</li>
<li>Email Notifications: Gogios can send email notifications regarding the status of monitored services, ensuring you stay informed about potential issues.</li>
<li>CRON-based Execution: Gogios can be quickly scheduled to run periodically via CRON, allowing you to automate monitoring without needing a complex setup.</li>
</ul><br />
<h2 style='display: inline'>Example alert</h2><br />
<br />
<span>This is an example alert report received via E-Mail. Whereas, <span class='inlinecode'>[C:2 W:0 U:0 OK:51]</span> means that we&#39;ve got two alerts in status critical, 0 warnings, 0 unknowns and 51 OKs.</span><br />
<br />
<pre>
Subject: GOGIOS Report [C:2 W:0 U:0 OK:51]

This is the recent Gogios report!

# Alerts with status changed:

OK-&gt;CRITICAL: Check ICMP4 vulcan.buetow.org: Check command timed out
OK-&gt;CRITICAL: Check ICMP6 vulcan.buetow.org: Check command timed out

# Unhandled alerts:

CRITICAL: Check ICMP4 vulcan.buetow.org: Check command timed out
CRITICAL: Check ICMP6 vulcan.buetow.org: Check command timed out

Have a nice day!
</pre>
<br />
<h2 style='display: inline'>Installation</h2><br />
<br />
<h3 style='display: inline'>Compiling and installing Gogios</h3><br />
<br />
<span>This document is primarily written for OpenBSD, but applying the corresponding steps to any Unix-like (e.g. Linux-based) operating system should be easy. On systems other than OpenBSD, you may always have to replace <span class='inlinecode'>does</span> with the <span class='inlinecode'>sudo</span> command and replace the <span class='inlinecode'>/usr/local/bin</span> path with <span class='inlinecode'>/usr/bin</span>.</span><br />
<br />
<span>To compile and install Gogios on OpenBSD, follow these steps:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>git clone https<font color="#990000">:</font>//codeberg<font color="#990000">.</font>org/snonux/gogios<font color="#990000">.</font>git
cd gogios
go build -o gogios cmd/gogios/main<font color="#990000">.</font>go
doas cp gogios /usr/local/bin/gogios
doas chmod <font color="#993399">755</font> /usr/local/bin/gogios
</pre>
<br />
<span>You can use cross-compilation if you want to compile Gogios for OpenBSD on a Linux system without installing the Go compiler on OpenBSD. Follow these steps:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">export</font></b> <font color="#009900">GOOS</font><font color="#990000">=</font>openbsd
<b><font color="#0000FF">export</font></b> <font color="#009900">GOARCH</font><font color="#990000">=</font>amd64
go build -o gogios cmd/gogios/main<font color="#990000">.</font>go
</pre>
<br />
<span>On your OpenBSD system, copy the binary to <span class='inlinecode'>/usr/local/bin/gogios</span> and set the correct permissions as described in the previous section. All steps described here you could automate with your configuration management system of choice. I use Rexify, the friendly configuration management system, to automate the installation, but that is out of the scope of this document.</span><br />
<br />
<a class='textlink' href='https://www.rexify.org'>https://www.rexify.org</a><br />
<br />
<h3 style='display: inline'>Setting up user, group and directories</h3><br />
<br />
<span>It is best to create a dedicated system user and group for Gogios to ensure proper isolation and security. Here are the steps to create the <span class='inlinecode'>_gogios</span> user and group under OpenBSD:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>doas adduser -group _gogios -batch _gogios
doas usermod -d /var/run/gogios _gogios
doas mkdir -p /var/run/gogios
doas chown _gogios<font color="#990000">:</font>_gogios /var/run/gogios
doas chmod <font color="#993399">750</font> /var/run/gogios
</pre>
<br />
<span>Please note that creating a user and group might differ depending on your operating system. For other operating systems, consult their documentation for creating system users and groups.</span><br />
<br />
<h3 style='display: inline'>Installing monitoring plugins</h3><br />
<br />
<span>Gogios relies on external Nagios or Icinga monitoring plugin scripts. On OpenBSD, you can install the <span class='inlinecode'>monitoring-plugins</span> package with Gogios. The monitoring-plugins package is a collection of monitoring plugins, similar to Nagios plugins, that can be used to monitor various services and resources:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>doas pkg_add monitoring-plugins
doas pkg_add nrpe <i><font color="#9A1900"># If you want to execute checks remotely via NRPE.</font></i>
</pre>
<br />
<span>Once the installation is complete, you can find the monitoring plugins in the <span class='inlinecode'>/usr/local/libexec/nagios</span> directory, which then can be configured to be used in <span class='inlinecode'>gogios.json</span>.</span><br />
<br />
<h2 style='display: inline'>Configuration</h2><br />
<br />
<h3 style='display: inline'>MTA</h3><br />
<br />
<span>Gogios requires a local Mail Transfer Agent (MTA) such as Postfix or OpenBSD SMTPD running on the same server where the CRON job (see about the CRON job further below) is executed. The local MTA handles email delivery, allowing Gogios to send email notifications to monitor status changes. Before using Gogios, ensure that you have a properly configured MTA installed and running on your server to facilitate the sending of emails. Once the MTA is set up and functioning correctly, Gogios can leverage it to send email notifications.</span><br />
<br />
<span>You can use the mail command to send an email via the command line on OpenBSD. Here&#39;s an example of how to send a test email to ensure that your email server is working correctly:</span><br />
<br />
<pre>
echo &#39;This is a test email from OpenBSD.&#39; | mail -s &#39;Test Email&#39; your-email@example.com
</pre>
<br />
<span>Check the recipient&#39;s inbox to confirm the delivery of the test email. If the email is delivered successfully, it indicates that your email server is configured correctly and functioning. Please check your MTA logs in case of issues.</span><br />
<br />
<h3 style='display: inline'>Configuring Gogios</h3><br />
<br />
<span>To configure Gogios, create a JSON configuration file (e.g., <span class='inlinecode'>/etc/gogios.json</span>). Here&#39;s an example configuration:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#990000">{</font>
  "EmailTo": "<font color="#FF0000">paul@dev.buetow.org</font>"<font color="#990000">,</font>
  "EmailFrom": "<font color="#FF0000">gogios@buetow.org</font>"<font color="#990000">,</font>
  "CheckTimeoutS": <font color="#993399">10</font><font color="#990000">,</font>
  "CheckConcurrency": <font color="#993399">2</font><font color="#990000">,</font>
  "StateDir": "<font color="#FF0000">/var/run/gogios</font>"<font color="#990000">,</font>
  "Checks": <font color="#990000">{</font>
    "Check ICMP4 www.foo.zone": <font color="#990000">{</font>
      "Plugin": "<font color="#FF0000">/usr/local/libexec/nagios/check_ping</font>"<font color="#990000">,</font>
      "Args": <font color="#990000">[</font> "-H"<font color="#990000">,</font> "www.foo.zone"<font color="#990000">,</font> "-4"<font color="#990000">,</font> "-w"<font color="#990000">,</font> "50,10%"<font color="#990000">,</font> "-c"<font color="#990000">,</font> "100,15%" <font color="#990000">],</font>
      "Retries": <font color="#993399">3</font><font color="#990000">,</font>
      "RetryInterval": <font color="#993399">10</font>
    <font color="#990000">},</font>
    "Check ICMP6 www.foo.zone": <font color="#990000">{</font>
      "Plugin": "<font color="#FF0000">/usr/local/libexec/nagios/check_ping</font>"<font color="#990000">,</font>
      "Args": <font color="#990000">[</font> "-H"<font color="#990000">,</font> "www.foo.zone"<font color="#990000">,</font> "-6"<font color="#990000">,</font> "-w"<font color="#990000">,</font> "50,10%"<font color="#990000">,</font> "-c"<font color="#990000">,</font> "100,15%" <font color="#990000">],</font>
      "Retries": <font color="#993399">3</font><font color="#990000">,</font>
      "RetryInterval": <font color="#993399">10</font>
    <font color="#990000">},</font>
    "www.foo.zone HTTP IPv4": <font color="#990000">{</font>
      "Plugin": "<font color="#FF0000">/usr/local/libexec/nagios/check_http</font>"<font color="#990000">,</font>
      "Args": <font color="#990000">[</font>"www.foo.zone"<font color="#990000">,</font> "-4"<font color="#990000">],</font>
      "DependsOn": <font color="#990000">[</font>"Check ICMP4 www.foo.zone"<font color="#990000">]</font>
    <font color="#990000">},</font>
    "www.foo.zone HTTP IPv6": <font color="#990000">{</font>
      "Plugin": "<font color="#FF0000">/usr/local/libexec/nagios/check_http</font>"<font color="#990000">,</font>
      "Args": <font color="#990000">[</font>"www.foo.zone"<font color="#990000">,</font> "-6"<font color="#990000">],</font>
      "DependsOn": <font color="#990000">[</font>"Check ICMP6 www.foo.zone"<font color="#990000">]</font>
    <font color="#990000">}</font>
    "Check NRPE Disk Usage foo.zone": <font color="#990000">{</font>
      "Plugin": "<font color="#FF0000">/usr/local/libexec/nagios/check_nrpe</font>"<font color="#990000">,</font>
      "Args": <font color="#990000">[</font>"-H"<font color="#990000">,</font> "foo.zone"<font color="#990000">,</font> "-c"<font color="#990000">,</font> "check_disk"<font color="#990000">,</font> "-p"<font color="#990000">,</font> "5666"<font color="#990000">,</font> "-4"<font color="#990000">]</font>
    <font color="#990000">}</font>
  <font color="#990000">}</font>
<font color="#990000">}</font>
</pre>
<br />
<ul>
<li><span class='inlinecode'>EmailTo</span>: Specifies the recipient of the email notifications.</li>
<li><span class='inlinecode'>EmailFrom</span>: Indicates the sender&#39;s email address for email notifications.</li>
<li><span class='inlinecode'>CheckTimeoutS</span>: Sets the timeout for checks in seconds.</li>
<li><span class='inlinecode'>CheckConcurrency</span>: Determines the number of concurrent checks that can run simultaneously.</li>
<li><span class='inlinecode'>StateDir</span>: Specifies the directory where Gogios stores its persistent state in a <span class='inlinecode'>state.json</span> file. </li>
<li><span class='inlinecode'>Checks</span>: Defines a list of checks to be performed, each with a unique name, plugin path, and arguments.</li>
</ul><br />
<span>Adjust the configuration file according to your needs, specifying the checks you want Gogios to perform.</span><br />
<br />
<span>If you want to execute checks only when another check succeeded (status OK), use <span class='inlinecode'>DependsOn</span>. In the example above, the HTTP checks won&#39;t run when the hosts aren&#39;t pingable. They will show up as <span class='inlinecode'>UNKNOWN</span> in the report.</span><br />
<br />
<span><span class='inlinecode'>Retries</span> and <span class='inlinecode'>RetryInterval</span> are optional check configuration parameters. In case of failure, Gogios will retry <span class='inlinecode'>Retries</span> times each <span class='inlinecode'>RetryInterval</span> seconds.</span><br />
<br />
<span>For remote checks, use the <span class='inlinecode'>check_nrpe</span> plugin. You also need to have the NRPE server set up correctly on the target host (out of scope for this document).</span><br />
<br />
<span>The <span class='inlinecode'>state.json</span> file mentioned above keeps track of the monitoring state and check results between Gogios runs, enabling Gogios only to send email notifications when there are changes in the check status.</span><br />
<br />
<h2 style='display: inline'>Running Gogios</h2><br />
<br />
<span>Now it is time to give it a first run. On OpenBSD, do:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>doas -u _gogios /usr/local/bin/gogios -cfg /etc/gogios<font color="#990000">.</font>json
</pre>
<br />
<span>To run Gogios via CRON on OpenBSD as the <span class='inlinecode'>gogios</span> user and check all services once per minute, follow these steps:</span><br />
<br />
<span>Type <span class='inlinecode'>doas crontab -e -u _gogios</span> and press Enter to open the crontab file for the <span class='inlinecode'>_gogios</span> user for editing and add the following lines to the crontab file:</span><br />
<br />
<pre>

0 7 * * * /usr/local/bin/gogios -renotify -cfg /etc/gogios.json
</pre>
<br />
<span>Gogios is now configured to run every five minutes from 8 am to 10 pm via CRON as the <span class='inlinecode'>_gogios</span> user. It will execute the checks and send monitoring status whenever a check status changes via email according to your configuration. Also, Gogios will run once at 7 am every morning and re-notify all unhandled alerts as a reminder.</span><br />
<br />
<h3 style='display: inline'>High-availability</h3><br />
<br />
<span>To create a high-availability Gogios setup, you can install Gogios on two servers that will monitor each other using the NRPE (Nagios Remote Plugin Executor) plugin. By running Gogios in alternate CRON intervals on both servers, you can ensure that even if one server goes down, the other will continue monitoring your infrastructure and sending notifications.</span><br />
<br />
<ul>
<li>Install Gogios on both servers following the compilation and installation instructions provided earlier.</li>
<li>Install the NRPE server (out of scope for this document) and plugin on both servers. This plugin allows you to execute Nagios check scripts on remote hosts.</li>
<li>Configure Gogios on both servers to monitor each other using the NRPE plugin. Add a check to the Gogios configuration file (<span class='inlinecode'>/etc/gogios.json</span>) on both servers that uses the NRPE plugin to execute a check script on the other server. For example, if you have Server A and Server B, the configuration on Server A should include a check for Server B, and vice versa.</li>
<li>Set up alternate CRON intervals on both servers. Configure the CRON job on Server A to run Gogios at minutes 0, 10, 20, ..., and on Server B to run at minutes 5, 15, 25, ... This will ensure that if one server goes down, the other server will continue monitoring and sending notifications. </li>
<li>Gogios doesn&#39;t support clustering. So it means when both servers are up, unhandled alerts will be notified via E-Mail twice; from each server once. That&#39;s the trade-off for simplicity.</li>
</ul><br />
<span>There are plans to make it possible to execute certain checks only on certain nodes (e.g. on elected leader or master nodes). This is still in progress (check out my Gorum Git project).</span><br />
<br />
<h2 style='display: inline'>Conclusion:</h2><br />
<br />
<span>Gogios is a lightweight and straightforward monitoring tool that is perfect for small-scale environments. With its compatibility with the Nagios Check API, email notifications, and CRON-based scheduling, Gogios offers an easy-to-use solution for those looking to monitor a limited number of resources. I personally use it to execute around 500 checks on my personal server infrastructure. I am very happy with this solution.</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>'The Obstacle is the Way' book notes</title>
        <link href="gemini://foo.zone/gemfeed/2023-05-06-the-obstacle-is-the-way-book-notes.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-05-06-the-obstacle-is-the-way-book-notes.gmi</id>
        <updated>2023-05-06T17:23:16+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>These are my personal takeaways after reading 'The Obstacle Is the Way' by Ryan Holiday. This is mainly for my own use, but you might find it helpful too.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>"The Obstacle is the Way" book notes</h1><br />
<br />
<span class='quote'>Published at 2023-05-06T17:23:16+03:00</span><br />
<br />
<span>These are my personal takeaways after reading "The Obstacle Is the Way" by Ryan Holiday. This is mainly for my own use, but you might find it helpful too.</span><br />
<br />
<br />
<pre>
         ,..........   ..........,
     ,..,&#39;          &#39;.&#39;          &#39;,..,
    ,&#39; ,&#39;            :            &#39;, &#39;,
   ,&#39; ,&#39;             :             &#39;, &#39;,
  ,&#39; ,&#39;              :              &#39;, &#39;,
 ,&#39; ,&#39;............., : ,.............&#39;, &#39;,
,&#39;  &#39;............   &#39;.&#39;   ............&#39;  &#39;,
 &#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;;&#39;&#39;&#39;;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;
                    &#39;&#39;&#39;
</pre>
<br />
<span>"The obstacle is the way" is a powerful statement that encapsulates the wisdom of turning challenges into opportunities for growth and success. We will explore using obstacles as fuel, transforming weaknesses into strengths, and adopting a mindset that allows us to be creative and persistent in the face of adversity.</span><br />
<br />
<h2 style='display: inline'>Reframe your perspective</h2><br />
<br />
<span>The obstacle in your path can become your path to success. Instead of being paralyzed by challenges, see them as opportunities to learn and grow. Remember, the things that hurt us often instruct us. </span><br />
<br />
<span>We spend a lot of time trying to get things perfect and look at the rules, but what matters is that it works; it doesn&#39;t need to be after the book. Focus on results rather than on beautiful methods. In Jujitsu, it does matter that you bring your opponent down, but not how. There are many ways from point A to point B; it doesn&#39;t need to be a straight line. So many try to find the best solution but need to catch up on what is in Infront of them. Think progress and not perfection.</span><br />
<br />
<span>Don&#39;t always try to use the front door; a backdoor could open. It&#39;s nonsense. Don&#39;t fight the judo master with judo. Non-action can be action, exposing the weaknesses of others.</span><br />
<br />
<br />
<h2 style='display: inline'>Embrace rationality</h2><br />
<br />
<span>It is a superpower to see things rationally when others are fearful. Focus on the reality of the situation without letting emotions, such as anger, cloud your judgment. This ability will enable you to make better decisions in adversity. Ability to see things what they really are. E.g. wine is old fermented grapes, or other people behaving like animals during a fight. Show the middle finger if someone persists on the stupid rules occasionally.</span><br />
<br />
<h2 style='display: inline'>Control your response</h2><br />
<br />
<span>You can choose how you respond to obstacles. Focus on what you can control, and don&#39;t let yourself feel harmed by external circumstances. Remember, you decide how things affect you; nobody else does. Choose to feel good in response to any situation. Embrace the challenges and obstacles that come your way, as they are opportunities for growth and learning.</span><br />
<br />
<h2 style='display: inline'>Practice emotional and physical resilience</h2><br />
<br />
<span>Martial artists know the importance of developing physical and emotional strength. Cultivate the art of not panicking; it will help you avoid making mistakes during high-pressure situations.</span><br />
<br />
<span>Focus on what you can control. Don&#39;t choose to feel harmed, and then you won&#39;t be harmed. I decide things that affect me; nobody else does. E.g., in prison, your mind stays your own. Don&#39;t ignore fear but explain it away, have a different view.</span><br />
<br />
<h2 style='display: inline'>Persistence and patience</h2><br />
<br />
<span>Practice persistence and patience in your pursuits. Focus on the process rather than the prize and take one step at a time. Remember, the journey is about finishing tasks, projects, or workouts to the best of your ability. Never be in a hurry and never be desperate. There is no reason to be rushed; there are all in the long haul. Follow the process and not the price. Take it one step at a time. The process is about finishing (workout, task, project, etc.).</span><br />
<br />
<h2 style='display: inline'>Embrace failure</h2><br />
<br />
<span>Failure is a natural part of life and can make us stronger. Treat defeat as a stepping stone to success and education. What is defeat? The first step to education. Failure makes you stronger. If we do our best, we can be proud of it, regardless of the result. Do your job, but do it right. Only an asshole thinks he is too good at the things he does. Also, asking for forgiveness is easier than asking for permission. </span><br />
<br />
<h2 style='display: inline'>Be adaptable</h2><br />
<br />
<span>There are many ways to achieve your goals; sometimes, unconventional methods are necessary. Feel free to break the rules or go off the beaten path if it will lead to better results. Transform weaknesses into strengths. We have a choice of how to respond to things. It&#39;s not about being positive but to be creative. Aim high, but stuff will happen; E.g., surprises will always happen.</span><br />
<br />
<h2 style='display: inline'>Embrace non-action</h2><br />
<br />
<span>We constantly push to the next thing. Sometimes the best course of action is standing still or even going backwards. Obstacles might resolve by themselves. Or going sideways. Sometimes, the best action is to stand still, go sideways, or even go backwards. Obstacles may resolve themselves or present new opportunities if you&#39;re patient and observant. People always want your input before you have all the facts. They want you to play after their rules. The question is, do you let them? The English call it the cool head. Being in control of Stress; requires practice. Appear, the absence of fear (Greek). When all others do it one way, it does not mean it is the correct or best practice.</span><br />
<br />
<h2 style='display: inline'>Leverage crisis</h2><br />
<br />
<span>In times of crisis, seize the chance to do things never done before. Great people use negative situations to their advantage and become the most effective in challenging circumstances.</span><br />
<br />
<span>The art of not panicking; otherwise, you will make mistakes. When overs are shocked, you know which way to take due to your thinking of the problem at Hand. A crisis gives you a chance to do things which never done before. Ordinary people shy from negative situations; great people use these for their benefit and are the most effective. The obstacle is not just turned upside down but used as a catapult.</span><br />
<br />
<span>Be prepared for nothing to work. Problems are an opportunity to do your best, not to do miracles. Always manage your expectations. It will suck, but it will be ok. Be prepared to begin from the beginning. Be cheerful and eagerly work on the next obstacle. Each time you become better. Life is not a sprint but a marathon. After each obstacle lies another obstacle, there won&#39;t be anything without obstacles. Passing one means you are ready for the next.</span><br />
<br />
<h2 style='display: inline'>Build your inner citadel</h2><br />
<br />
<span>Develop your inner strength during good times so you can rely on it in bad times. Always prepare for adversity and face it with calmness and resilience. Be humble enough that things which happen will happen. Build your inner citadel. In good times strengthen it. In bad times rely on it.</span><br />
<br />
<span>We should always prepare for things to get tough. Your house burns down: no worries, we eliminated much rubbish. Imagine what can go wrong before things go wrong. We are prepared for adversity; it&#39;s other people who aren&#39;t. Phil Jackson&#39;s hip problem example. To receive unexpected benefits, you must first accept the unexpected obstacles. Meditate on death. It&#39;s a universal obstacle. Use it as a reminder to do your best.</span><br />
<br />
<h2 style='display: inline'>Love everything that happens</h2><br />
<br />
<span>Turn an obstacle the other way around for your benefit. Use it at fuel. It&#39;s simple but challenging. Most are paralyzed instead. The obstacle in the path becomes the path. Obstacles are neither good nor bad. The things which hurt, instruct.</span><br />
<br />
<span>Should I hate people who hate me? That&#39;s their problem and not mine. Be always calm and relaxed during the fight. The story of the battle is the story of the smile. Cheerfulness in all situations, especially the bad ones. Love for everything that happens; if it happens, it was meant to happen. We can choose how we react to things, so why not choose to feel good? I love everything that happens. You must never lower yourself to the person you don&#39;t like.</span><br />
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>Life is a marathon, not a sprint. Each obstacle we overcome prepares us for the next one. Remember, the obstacle is not just a barrier to be turned upside down; it can also be used as a catapult to propel us forward. By embracing challenges and using them as opportunities for growth, we become stronger, more adaptable, and, ultimately, more successful.</span><br />
<br />
<span>Other book notes of mine are:</span><br />
<br />
<a class='textlink' href='./2023-05-06-the-obstacle-is-the-way-book-notes.html'>2023-05-06 "The Obstacle is the Way" book notes (You are currently reading this)</a><br />
<a class='textlink' href='./2023-04-01-never-split-the-difference-book-notes.html'>2023-04-01 "Never split the difference" book notes</a><br />
<a class='textlink' href='./2023-03-16-the-pragmatic-programmer-book-notes.html'>2023-03-16 "The Pragmatic Programmer" book notes</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../resources.html'>More books and other resources I found useful.</a><br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Unveiling `guprecords.raku`: Global Uptime Records with Raku</title>
        <link href="gemini://foo.zone/gemfeed/2023-05-01-unveiling-guprecords:-uptime-records-with-raku.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-05-01-unveiling-guprecords:-uptime-records-with-raku.gmi</id>
        <updated>2023-04-30T13:10:26+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>For fun, I am tracking the uptime of various personal machines (servers, laptops, workstations...). I have been doing this for over ten years now, so I have a lot of statistics collected.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Unveiling <span class='inlinecode'>guprecords.raku</span>: Global Uptime Records with Raku</h1><br />
<br />
<span class='quote'>Published at 2023-04-30T13:10:26+03:00</span><br />
<br />
<pre>
+-----+-----------------+-----------------------------+
| Pos |            Host |                    Lifespan |
+-----+-----------------+-----------------------------+
|  1. |        dionysus |  8 years, 6 months, 17 days |
|  2. |          uranus |  7 years, 2 months, 16 days |
|  3. |   alphacentauri |  6 years, 9 months, 13 days |
|  4. |         *vulcan |   4 years, 5 months, 6 days |
|  5. |             sun |  3 years, 10 months, 2 days |
|  6. |           uugrn |   3 years, 5 months, 5 days |
|  7. |       deltavega |  3 years, 1 months, 21 days |
|  8. |           pluto | 2 years, 10 months, 30 days |
|  9. |         tauceti |  2 years, 3 months, 22 days |
| 10. |        callisto |  2 years, 3 months, 13 days |
+-----+-----------------+-----------------------------+
</pre>
<br />
<h1 style='display: inline'>Introduction</h1><br />
<br />
<span>For fun, I am tracking the uptime of various personal machines (servers, laptops, workstations...). I have been doing this for over ten years now, so I have a lot of statistics collected.</span><br />
<br />
<span>As a result of this, I am introducing <span class='inlinecode'>guprecords.raku</span>, a handy Raku script that helps me combine uptime statistics from multiple servers into one comprehensive report. In this blog post, I&#39;ll explore what Guprecords is and some examples of its application. I will also add some notes on Raku.</span><br />
<br />
<span>Guprecords, or global uptime records, is a Raku script designed to generate a consolidated uptime report from multiple hosts:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/guprecords'>https://codeberg.org/snonux/guprecords</a><br />
<a class='textlink' href='https://raku.org'>The Raku Programming Language</a><br />
<br />
<span>A previous version of Guprecords was actually written in Perl, the older and more established language from which Raku was developed. One of the primary motivations for rewriting Guprecords in Raku was to learn the language and explore its features. Raku is a more modern and powerful language compared to Perl, and working on a real-world project like Guprecords provided a practical and engaging way to learn the language.</span><br />
<br />
<span>Over the last years, I have been reading the following books and resources about Raku:</span><br />
<br />
<ul>
<li>Raku Guide (at raku.guide)</li>
<li>Think Perl 6</li>
<li>Raku Fundamentals</li>
<li>Raku Recipes</li>
</ul><br />
<span>And I have been following the Raku newsletter, and sometimes I have been lurking around in the IRC channels, too. Watching Raku coding challenges on YouTube was pretty fun, too. However, nothing beats actually using Raku to learn the language. After reading all of these resources, I may have a good idea about the features and paradigms, but I am by far not an expert.</span><br />
<br />
<h2 style='display: inline'>How Guprecords works</h2><br />
<br />
<span>Guprecords works in three stages:</span><br />
<br />
<ul>
<li>1. Generating uptime statistics using <span class='inlinecode'>uptimed</span>: First, I need to install and run <span class='inlinecode'>uptimed</span> on each host to generate uptime statistics. This tool is available for most common Linux and *BSD distributions and macOS via Homebrew.</li>
<li>2. Collecting uptime records to a central location: The next step involves collecting the raw uptime statistics files generated by <span class='inlinecode'>uptimed</span> on each host. It&#39;s a good idea to store all record files in a central git repository. The records file contains information about the total uptime since boot, boot time, and the operating system and kernel version. Guprecords itself does not do the collection part, but have a look at the <span class='inlinecode'>README.md</span> in the git repository for some guidance.</li>
<li>3. Generating global uptime stats: Finally, run the <span class='inlinecode'>guprecords.raku</span> script with the appropriate flags to create a global uptime report. For example, I can use the following command:</li>
</ul><br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>$ raku guprecords<font color="#990000">.</font>raku --stats<font color="#990000">=</font><font color="#009900">dir</font><font color="#990000">=</font><font color="#009900">$HOME</font>/git/uprecords/stats --all
</pre>
<br />
<span>This command will generate a comprehensive uptime report from the collected statistics, making it easy to review and enjoy the data.</span><br />
<br />
<span>Guprecords supports the following features:</span><br />
<br />
<ul>
<li>Supports multiple categories: Host, Kernel, KernelMajor, and KernelName</li>
<li>Supports multiple metrics: Boots, Uptime, Score, Downtime, and Lifespan</li>
<li>Output formats available: Plaintext, Markdown, and Gemtext</li>
<li>Provides top entries based on the specified limit</li>
</ul><br />
<h2 style='display: inline'>Example</h2><br />
<br />
<span>You have already seen an example at the very top of this post, where the hosts were grouped by their total lifespans (uptime+downtime). Here&#39;s an example of what the global uptime report (grouped by total host uptimes) might look like:</span><br />
<br />
<pre>
Top 20 Uptime&#39;s by Host

+-----+-----------------+-----------------------------+
| Pos |            Host |                      Uptime |
+-----+-----------------+-----------------------------+
|  1. |         *vulcan |   4 years, 5 months, 6 days |
|  2. |          uranus | 3 years, 11 months, 21 days |
|  3. |             sun |  3 years, 9 months, 26 days |
|  4. |           uugrn |   3 years, 5 months, 5 days |
|  5. |       deltavega |  3 years, 1 months, 21 days |
|  6. |           pluto | 2 years, 10 months, 29 days |
|  7. |         tauceti |  2 years, 3 months, 19 days |
|  8. |       tauceti-f |  1 years, 9 months, 18 days |
|  9. | *ultramega15289 |  1 years, 8 months, 17 days |
| 10. |          *earth |  1 years, 5 months, 22 days |
| 11. |       *blowfish |  1 years, 4 months, 20 days |
| 12. |   ultramega8477 |  1 years, 3 months, 25 days |
| 13. |           host0 |   1 years, 3 months, 9 days |
| 14. |       tauceti-e |  1 years, 2 months, 20 days |
| 15. |        makemake |   1 years, 1 months, 6 days |
| 16. |        callisto | 0 years, 10 months, 31 days |
| 17. |   alphacentauri | 0 years, 10 months, 28 days |
| 18. |          london |  0 years, 9 months, 16 days |
| 19. |         twofish |  0 years, 8 months, 31 days |
| 20. |     *fishfinger |  0 years, 8 months, 17 days |
+-----+-----------------+-----------------------------+
</pre>
<br />
<span>This table ranks the top 20 hosts based on their total uptime, with the host having the highest uptime at the top. The hosts marked with <span class='inlinecode'>*</span> are still active, means stats were collected within the last couple of months. </span><br />
<br />
<span>My up to date stats can be seen here:</span><br />
<br />
<a class='textlink' href='../uptime-stats.html'>My machine uptime stats</a><br />
<br />
<span>Just recently, I decommissioned <span class='inlinecode'>vulcan</span> (the number one stop from above), which used to be my CentOS 7 (initially CentOS 6) VM hosting my personal NextCloud and Wallabag (which I modernised just recently with a brand new shiny Rocky Linux 9 VM). This was the last <span class='inlinecode'>uptimed</span> output before shutting it down (it always makes me feel sentimental decommissioning one of my machines <span class='inlinecode'>:&#39;-(</span>):</span><br />
<br />
<pre>
     #               Uptime | System                                     Boot up
----------------------------+---------------------------------------------------
     1   545 days, 17:58:15 | Linux 3.10.0-1160.15.2.e  Sun Jul 25 19:32:25 2021
     2   279 days, 10:12:14 | Linux 3.10.0-957.21.3.el  Sun Jun 30 12:43:41 2019
     3   161 days, 06:08:43 | Linux 3.10.0-1160.15.2.e  Sun Feb 14 11:05:38 2021
     4   107 days, 01:26:35 | Linux 3.10.0-957.1.3.el7  Thu Dec 20 09:29:13 2018
     5    96 days, 21:13:49 | Linux 3.10.0-1127.13.1.e  Sat Jul 25 17:56:22 2020
-&gt;   6    89 days, 23:05:32 | Linux 3.10.0-1160.81.1.e  Sun Jan 22 12:39:36 2023
     7    63 days, 18:30:45 | Linux 3.10.0-957.10.1.el  Sat Apr 27 18:12:43 2019
     8    63 days, 06:53:33 | Linux 3.10.0-1127.8.2.el  Sat May 23 10:41:08 2020
     9    48 days, 11:44:49 | Linux 3.10.0-1062.18.1.e  Sat Apr  4 22:56:07 2020
    10    42 days, 08:00:13 | Linux 3.10.0-1127.19.1.e  Sat Nov  7 11:47:33 2020
    11    36 days, 22:57:19 | Linux 3.10.0-1160.6.1.el  Sat Dec 19 19:47:57 2020
    12    21 days, 06:16:28 | Linux 3.10.0-957.10.1.el  Sat Apr  6 11:56:01 2019
    13    12 days, 20:11:53 | Linux 3.10.0-1160.11.1.e  Mon Jan 25 18:45:27 2021
    14     7 days, 21:29:18 | Linux 3.10.0-1127.13.1.e  Fri Oct 30 14:18:04 2020
    15     6 days, 20:07:18 | Linux 3.10.0-1160.15.2.e  Sun Feb  7 14:57:35 2021
    16     1 day , 21:46:41 | Linux 3.10.0-957.1.3.el7  Tue Dec 18 11:42:19 2018
    17     0 days, 01:25:57 | Linux 3.10.0-957.1.3.el7  Tue Dec 18 10:16:08 2018
    18     0 days, 00:42:34 | Linux 3.10.0-1160.15.2.e  Sun Jul 25 18:49:38 2021
    19     0 days, 00:08:32 | Linux 3.10.0-1160.81.1.e  Sun Jan 22 12:30:52 2023
----------------------------+---------------------------------------------------
1up in     6 days, 22:08:18 | at                        Sat Apr 29 10:53:25 2023
no1 in   455 days, 18:52:44 | at                        Sun Jul 21 07:37:51 2024
    up  1586 days, 00:20:28 | since                     Tue Dec 18 10:16:08 2018
  down     0 days, 01:08:32 | since                     Tue Dec 18 10:16:08 2018
   %up               99.997 | since                     Tue Dec 18 10:16:08 2018
</pre>
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>Guprecords is a small, yet powerful tool for analyzing uptime statistics. While developing Guprecords, I have come to truly appreciate and love Raku&#39;s expressiveness. The language is designed to be both powerful and flexible, allowing developers to express their intentions and logic more clearly and concisely.</span><br />
<br />
<span>Raku&#39;s expressive syntax, support for multiple programming paradigms, and unique features, such as grammars and lazy evaluation, make it a joy to work with. </span><br />
<br />
<span>Working on Guprecords in Raku has been an enjoyable experience, and I&#39;ve found that Raku&#39;s expressiveness has significantly contributed to the overall quality and effectiveness of the script. The language&#39;s ability to elegantly express complex logic and data manipulation tasks makes it an excellent choice for developing tools like these, where expressiveness and productiveness are of the utmost importance.</span><br />
<br />
<span>So far, I have only scratched the surface of what Raku can do. I hope to find more time to become a regular Rakoon (a Raku Programmer). I have many Ideas for other small tools like Guprecords, but the challenge is finding the time. I&#39;d love to explore Raku Grammars and also I would love to explore writing concurrent code in Raku (I also love Go (Golang), btw!). Ideas for future Raku personal projects include:</span><br />
<br />
<ul>
<li>A log file analyzer, for generating anonymized <span class='inlinecode'>foo.zone</span> visitor stats for both, the Web and Gemini.</li>
<li>A social media sharing scheduler a la <span class='inlinecode'>buffer.com</span>. I am using Buffer at the moment to share posts on Mastadon, Twitter, Telegram and LinkedIn, but it is proprietary and also it&#39;s not really reliable.</li>
<li>Rewrite the static photo album generator of <span class='inlinecode'>irregular.ninja</span> in Raku (from Bash).</li>
</ul><br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2023-05-01-unveiling-guprecords:-uptime-records-with-raku.html'>2023-05-01 Unveiling <span class='inlinecode'>guprecords.raku</span>: Global Uptime Records with Raku (You are currently reading this)</a><br />
<a class='textlink' href='./2022-06-15-sweating-the-small-stuff.html'>2022-06-15 Sweating the small stuff - Tiny projects of mine</a><br />
<a class='textlink' href='./2022-05-27-perl-is-still-a-great-choice.html'>2022-05-27 Perl is still a great choice</a><br />
<a class='textlink' href='./2011-05-07-perl-daemon-service-framework.html'>2011-05-07 Perl Daemon (Service Framework)</a><br />
<a class='textlink' href='./2008-06-26-perl-poetry.html'>2008-06-26 Perl Poetry</a><br />
<br />
<span>E-Mail your comments to hi@foo.zone :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Algorithms and Data Structures in Go - Part 1</title>
        <link href="gemini://foo.zone/gemfeed/2023-04-09-algorithms-and-data-structures-in-golang-part-1.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-04-09-algorithms-and-data-structures-in-golang-part-1.gmi</id>
        <updated>2023-04-09T22:31:42+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This is the first blog post about my Algorithms and Data Structures in Go series. I am not a Software Developer in my day job. In my current role, programming and scripting skills are desirable but not mandatory. I have been learning about Data Structures and Algorithms many years ago at University. I thought it would be fun to revisit/refresh my knowledge here and implement many of the algorithms in Go.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Algorithms and Data Structures in Go - Part 1</h1><br />
<br />
<span class='quote'>Published at 2023-04-09T22:31:42+03:00</span><br />
<br />
<pre>
         ,_---~~~~~----._         
  _,,_,*^____      _____``*g*\"*, 
 / __/ /&#39;     ^.  /      \ ^@q   f 
[  @f | @))    |  | @))   l  0 _/  
 \`/   \~____ / __ \_____/    \   
  |           _l__l_           I   
  }          [______]           I  
  ]            | | |            |  
  ]             ~ ~             |  
  |                            |   
   |                           |   
</pre>
<br />
<span>This is the first blog post about my Algorithms and Data Structures in Go series. I am not a Software Developer in my day job. In my current role, programming and scripting skills are desirable but not mandatory. I have been learning about Data Structures and Algorithms many years ago at University. I thought it would be fun to revisit/refresh my knowledge here and implement many of the algorithms in Go.</span><br />
<br />
<a class='textlink' href='./2023-04-09-algorithms-and-data-structures-in-golang-part-1.html'>2023-04-09 Algorithms and Data Structures in Go - Part 1 (You are currently reading this)</a><br />
<br />
<span>This post is about setting up some basic data structures and methods for this blog series. I promise, everything will be easy to follow in this post. It will become more interesting later in this series.</span><br />
<br />
<h2 style='display: inline'>Type constraints</h2><br />
<br />
<span>First, the package <span class='inlinecode'>ds</span> (data structures) defines the <span class='inlinecode'>types.go</span>. All examples will either operate on the <span class='inlinecode'>Integer</span> or <span class='inlinecode'>Number</span> type:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">package</font></b> ds

<b><font color="#0000FF">import</font></b> <font color="#990000">(</font>
	<font color="#FF0000">"golang.org/x/exp/constraints"</font>
<font color="#990000">)</font>

<b><font color="#0000FF">type</font></b> Integer <b><font color="#0000FF">interface</font></b> <font color="#FF0000">{</font>
	constraints<font color="#990000">.</font>Integer
<font color="#FF0000">}</font>

<b><font color="#0000FF">type</font></b> Number <b><font color="#0000FF">interface</font></b> <font color="#FF0000">{</font>
	constraints<font color="#990000">.</font>Integer <font color="#990000">|</font> constraints<font color="#990000">.</font>Float
<font color="#FF0000">}</font>

</pre>
<br />
<h2 style='display: inline'>ArrayList</h2><br />
<br />
<span>Next comes the <span class='inlinecode'>arraylist.go</span>, which defines the underlying data structure all the algorithms of this series will use. <span class='inlinecode'>ArrayList</span> is just a type alias of a Go array (or slice) with custom methods on it:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">package</font></b> ds

<b><font color="#0000FF">import</font></b> <font color="#990000">(</font>
	<font color="#FF0000">"fmt"</font>
	<font color="#FF0000">"math/rand"</font>
	<font color="#FF0000">"strings"</font>
<font color="#990000">)</font>

<b><font color="#0000FF">type</font></b> ArrayList<font color="#990000">[</font>V Number<font color="#990000">]</font> <font color="#990000">[]</font>V

<b><font color="#0000FF">func</font></b> NewArrayList<font color="#990000">[</font>V Number<font color="#990000">](</font>l int<font color="#990000">)</font> ArrayList<font color="#990000">[</font>V<font color="#990000">]</font> <font color="#FF0000">{</font>
	<b><font color="#0000FF">return</font></b> <b><font color="#000000">make</font></b><font color="#990000">(</font>ArrayList<font color="#990000">[</font>V<font color="#990000">],</font> l<font color="#990000">)</font>
<font color="#FF0000">}</font>
</pre>
<br />
<span>As you can see, the code uses Go generics, which I refactored recently. Besides the default constructor (which only returns an empty <span class='inlinecode'>ArrayList</span> with a given capacity), there are also a bunch of special constructors. <span class='inlinecode'>NewRandomArrayList</span> is returning an <span class='inlinecode'>ArrayList</span> with random numbers, <span class='inlinecode'>NewAscendingArrayList</span> and <span class='inlinecode'>NewDescendingArrayList</span> are returning <span class='inlinecode'>ArrayList</span>s in either ascending or descending order. They all will be used later on for testing and benchmarking the algorithms.</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">func</font></b> NewRandomArrayList<font color="#990000">[</font>V Number<font color="#990000">](</font>l<font color="#990000">,</font> max int<font color="#990000">)</font> ArrayList<font color="#990000">[</font>V<font color="#990000">]</font> <font color="#FF0000">{</font>
	a <font color="#990000">:=</font> <b><font color="#000000">make</font></b><font color="#990000">(</font>ArrayList<font color="#990000">[</font>V<font color="#990000">],</font> l<font color="#990000">)</font>
	<b><font color="#0000FF">for</font></b> i <font color="#990000">:=</font> <font color="#993399">0</font><font color="#990000">;</font> i <font color="#990000">&lt;</font> l<font color="#990000">;</font> i<font color="#990000">++</font> <font color="#FF0000">{</font>
		<b><font color="#0000FF">if</font></b> max <font color="#990000">&gt;</font> <font color="#993399">0</font> <font color="#FF0000">{</font>
			a<font color="#990000">[</font>i<font color="#990000">]</font> <font color="#990000">=</font> <b><font color="#000000">V</font></b><font color="#990000">(</font>rand<font color="#990000">.</font><b><font color="#000000">Intn</font></b><font color="#990000">(</font>max<font color="#990000">))</font>
			<b><font color="#0000FF">continue</font></b>
		<font color="#FF0000">}</font>
		a<font color="#990000">[</font>i<font color="#990000">]</font> <font color="#990000">=</font> <b><font color="#000000">V</font></b><font color="#990000">(</font>rand<font color="#990000">.</font><b><font color="#000000">Int</font></b><font color="#990000">())</font>
	<font color="#FF0000">}</font>
	<b><font color="#0000FF">return</font></b> a
<font color="#FF0000">}</font>

<b><font color="#0000FF">func</font></b> NewAscendingArrayList<font color="#990000">[</font>V Number<font color="#990000">](</font>l int<font color="#990000">)</font> ArrayList<font color="#990000">[</font>V<font color="#990000">]</font> <font color="#FF0000">{</font>
	a <font color="#990000">:=</font> <b><font color="#000000">make</font></b><font color="#990000">(</font>ArrayList<font color="#990000">[</font>V<font color="#990000">],</font> l<font color="#990000">)</font>
	<b><font color="#0000FF">for</font></b> i <font color="#990000">:=</font> <font color="#993399">0</font><font color="#990000">;</font> i <font color="#990000">&lt;</font> l<font color="#990000">;</font> i<font color="#990000">++</font> <font color="#FF0000">{</font>
		a<font color="#990000">[</font>i<font color="#990000">]</font> <font color="#990000">=</font> <b><font color="#000000">V</font></b><font color="#990000">(</font>i<font color="#990000">)</font>
	<font color="#FF0000">}</font>
	<b><font color="#0000FF">return</font></b> a
<font color="#FF0000">}</font>

<b><font color="#0000FF">func</font></b> NewDescendingArrayList<font color="#990000">[</font>V Number<font color="#990000">](</font>l int<font color="#990000">)</font> ArrayList<font color="#990000">[</font>V<font color="#990000">]</font> <font color="#FF0000">{</font>
	a <font color="#990000">:=</font> <b><font color="#000000">make</font></b><font color="#990000">(</font>ArrayList<font color="#990000">[</font>V<font color="#990000">],</font> l<font color="#990000">)</font>
	j <font color="#990000">:=</font> l <font color="#990000">-</font> <font color="#993399">1</font>
	<b><font color="#0000FF">for</font></b> i <font color="#990000">:=</font> <font color="#993399">0</font><font color="#990000">;</font> i <font color="#990000">&lt;</font> l<font color="#990000">;</font> i<font color="#990000">++</font> <font color="#FF0000">{</font>
		a<font color="#990000">[</font>i<font color="#990000">]</font> <font color="#990000">=</font> <b><font color="#000000">V</font></b><font color="#990000">(</font>j<font color="#990000">)</font>
		j<font color="#990000">--</font>
	<font color="#FF0000">}</font>
	<b><font color="#0000FF">return</font></b> a
<font color="#FF0000">}</font>
</pre>
<br />
<h2 style='display: inline'>Helper methods</h2><br />
<br />
<span>The <span class='inlinecode'>FirstN</span> method only returns the first N elements of the <span class='inlinecode'>ArrayList</span>. This is useful for printing out only parts of the data structure:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">func</font></b> <font color="#990000">(</font>a ArrayList<font color="#990000">[</font>V<font color="#990000">])</font> <b><font color="#000000">FirstN</font></b><font color="#990000">(</font>n int<font color="#990000">)</font> <font color="#009900">string</font> <font color="#FF0000">{</font>
	<b><font color="#0000FF">var</font></b> sb strings<font color="#990000">.</font>Builder
	j <font color="#990000">:=</font> n

	l <font color="#990000">:=</font> <b><font color="#000000">len</font></b><font color="#990000">(</font>a<font color="#990000">)</font>
	<b><font color="#0000FF">if</font></b> j <font color="#990000">&gt;</font> l <font color="#FF0000">{</font>
		j <font color="#990000">=</font> l
	<font color="#FF0000">}</font>

	<b><font color="#0000FF">for</font></b> i <font color="#990000">:=</font> <font color="#993399">0</font><font color="#990000">;</font> i <font color="#990000">&lt;</font> j<font color="#990000">;</font> i<font color="#990000">++</font> <font color="#FF0000">{</font>
		fmt<font color="#990000">.</font><b><font color="#000000">Fprintf</font></b><font color="#990000">(&amp;</font>sb<font color="#990000">,</font> <font color="#FF0000">"%v "</font><font color="#990000">,</font> a<font color="#990000">[</font>i<font color="#990000">])</font>
	<font color="#FF0000">}</font>

	<b><font color="#0000FF">if</font></b> j <font color="#990000">&lt;</font> l <font color="#FF0000">{</font>
		fmt<font color="#990000">.</font><b><font color="#000000">Fprintf</font></b><font color="#990000">(&amp;</font>sb<font color="#990000">,</font> <font color="#FF0000">"... "</font><font color="#990000">)</font>
	<font color="#FF0000">}</font>

	<b><font color="#0000FF">return</font></b> sb<font color="#990000">.</font><b><font color="#000000">String</font></b><font color="#990000">()</font>
<font color="#FF0000">}</font>
</pre>
<br />
<span>The <span class='inlinecode'>Sorted</span> method checks whether the <span class='inlinecode'>ArrayList</span> is sorted. This will be used by the unit tests later on:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">func</font></b> <font color="#990000">(</font>a ArrayList<font color="#990000">[</font>V<font color="#990000">])</font> <b><font color="#000000">Sorted</font></b><font color="#990000">()</font> <font color="#009900">bool</font> <font color="#FF0000">{</font>
	<b><font color="#0000FF">for</font></b> i <font color="#990000">:=</font> <b><font color="#000000">len</font></b><font color="#990000">(</font>a<font color="#990000">)</font> <font color="#990000">-</font> <font color="#993399">1</font><font color="#990000">;</font> i <font color="#990000">&gt;</font> <font color="#993399">0</font><font color="#990000">;</font> i<font color="#990000">--</font> <font color="#FF0000">{</font>
		<b><font color="#0000FF">if</font></b> a<font color="#990000">[</font>i<font color="#990000">]</font> <font color="#990000">&lt;</font> a<font color="#990000">[</font>i<font color="#990000">-</font><font color="#993399">1</font><font color="#990000">]</font> <font color="#FF0000">{</font>
			<b><font color="#0000FF">return</font></b> false
		<font color="#FF0000">}</font>
	<font color="#FF0000">}</font>
	<b><font color="#0000FF">return</font></b> true
<font color="#FF0000">}</font>
</pre>
<br />
<span>And the last utility method used is <span class='inlinecode'>Swap</span>, which allows swapping the values of two indices in the <span class='inlinecode'>ArrayList</span>:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">func</font></b> <font color="#990000">(</font>a ArrayList<font color="#990000">[</font>V<font color="#990000">])</font> <b><font color="#000000">Swap</font></b><font color="#990000">(</font>i<font color="#990000">,</font> j int<font color="#990000">)</font> <font color="#FF0000">{</font>
	aux <font color="#990000">:=</font> a<font color="#990000">[</font>i<font color="#990000">]</font>
	a<font color="#990000">[</font>i<font color="#990000">]</font> <font color="#990000">=</font> a<font color="#990000">[</font>j<font color="#990000">]</font>
	a<font color="#990000">[</font>j<font color="#990000">]</font> <font color="#990000">=</font> aux
<font color="#FF0000">}</font>

</pre>
<br />
<h2 style='display: inline'>Sleep sort</h2><br />
<br />
<span>Let&#39;s implement our first algorithm, sleep sort. Sleep sort is a non-traditional and unconventional sorting algorithm based on the idea of waiting a certain amount of time corresponding to the value of each element in the input <span class='inlinecode'>ArrayList</span>. It&#39;s more of a fun, creative concept rather than an efficient or practical sorting technique. This is not a sorting algorithm you would use in any production code. As you can imagine, it is quite an inefficient sorting algorithm (it&#39;s only listed here as a warm-up exercise). This sorting method may also return false results depending on how the Goroutines are scheduled by the Go runtime. </span><br />
<br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">package</font></b> sort

<b><font color="#0000FF">import</font></b> <font color="#990000">(</font>
	<font color="#FF0000">"codeberg.org/snonux/algorithms/ds"</font>
	<font color="#FF0000">"sync"</font>
	<font color="#FF0000">"time"</font>
<font color="#990000">)</font>

<b><font color="#0000FF">func</font></b> Sleep<font color="#990000">[</font>V ds<font color="#990000">.</font>Integer<font color="#990000">](</font>a ds<font color="#990000">.</font>ArrayList<font color="#990000">[</font>V<font color="#990000">])</font> ds<font color="#990000">.</font>ArrayList<font color="#990000">[</font>V<font color="#990000">]</font> <font color="#FF0000">{</font>
	sorted <font color="#990000">:=</font> ds<font color="#990000">.</font>NewArrayList<font color="#990000">[</font>V<font color="#990000">](</font><b><font color="#000000">len</font></b><font color="#990000">(</font>a<font color="#990000">))</font>

	numCh <font color="#990000">:=</font> <b><font color="#000000">make</font></b><font color="#990000">(</font><b><font color="#0000FF">chan</font></b> V<font color="#990000">)</font>
	<b><font color="#0000FF">var</font></b> wg sync<font color="#990000">.</font>WaitGroup
	wg<font color="#990000">.</font><b><font color="#000000">Add</font></b><font color="#990000">(</font><b><font color="#000000">len</font></b><font color="#990000">(</font>a<font color="#990000">))</font>

	<b><font color="#0000FF">go</font></b> <b><font color="#0000FF">func</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
		wg<font color="#990000">.</font><b><font color="#000000">Wait</font></b><font color="#990000">()</font>
		<b><font color="#000000">close</font></b><font color="#990000">(</font>numCh<font color="#990000">)</font>
	<font color="#FF0000">}</font><font color="#990000">()</font>

	<b><font color="#0000FF">for</font></b> _<font color="#990000">,</font> num <font color="#990000">:=</font> <b><font color="#0000FF">range</font></b> a <font color="#FF0000">{</font>
		<b><font color="#0000FF">go</font></b> <b><font color="#0000FF">func</font></b><font color="#990000">(</font>num V<font color="#990000">)</font> <font color="#FF0000">{</font>
			<b><font color="#0000FF">defer</font></b> wg<font color="#990000">.</font><b><font color="#000000">Done</font></b><font color="#990000">()</font>
			time<font color="#990000">.</font><b><font color="#000000">Sleep</font></b><font color="#990000">(</font>time<font color="#990000">.</font><b><font color="#000000">Duration</font></b><font color="#990000">(</font>num<font color="#990000">)</font> <font color="#990000">*</font> time<font color="#990000">.</font>Second<font color="#990000">)</font>
			numCh <font color="#990000">&lt;-</font> num
		<font color="#FF0000">}</font><font color="#990000">(</font>num<font color="#990000">)</font>
	<font color="#FF0000">}</font>

	<b><font color="#0000FF">for</font></b> num <font color="#990000">:=</font> <b><font color="#0000FF">range</font></b> numCh <font color="#FF0000">{</font>
		sorted <font color="#990000">=</font> <b><font color="#000000">append</font></b><font color="#990000">(</font>sorted<font color="#990000">,</font> num<font color="#990000">)</font>
	<font color="#FF0000">}</font>

	<b><font color="#0000FF">return</font></b> sorted
<font color="#FF0000">}</font>
</pre>
<br />
<span>This Go code implements the sleep sort algorithm using generics and goroutines. The main function <span class='inlinecode'>Sleep[V ds.Integer](a ds.ArrayList[V]) ds.ArrayList[V]</span> takes a generic <span class='inlinecode'>ArrayList</span> as input and returns a sorted <span class='inlinecode'>ArrayList</span>. The code creates a separate goroutine for each element in the input array, sleeps for a duration proportional to the element&#39;s value, and then sends the element to a channel. Another goroutine waits for all the sleeping goroutines to finish and then closes the channel. The sorted result <span class='inlinecode'>ArrayList</span> is constructed by appending the elements received from the channel in the order they arrive. The <span class='inlinecode'>sync.WaitGroup</span> is used to synchronize goroutines and ensure that all of them have completed before closing the channel.</span><br />
<br />
<h3 style='display: inline'>Testing</h3><br />
<br />
<span>For testing, we only allow values up to 10, as otherwise, it would take too long to finish:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">package</font></b> sort

<b><font color="#0000FF">import</font></b> <font color="#990000">(</font>
	<font color="#FF0000">"fmt"</font>
	<font color="#FF0000">"testing"</font>

	<font color="#FF0000">"codeberg.org/snonux/algorithms/ds"</font>
<font color="#990000">)</font>

<b><font color="#0000FF">func</font></b> <b><font color="#000000">TestSleepSort</font></b><font color="#990000">(</font>t <font color="#990000">*</font>testing<font color="#990000">.</font>T<font color="#990000">)</font> <font color="#FF0000">{</font>
	a <font color="#990000">:=</font> ds<font color="#990000">.</font>NewRandomArrayList<font color="#990000">[</font>int<font color="#990000">](</font><font color="#993399">10</font><font color="#990000">,</font> <font color="#993399">10</font><font color="#990000">)</font>
	a <font color="#990000">=</font> <b><font color="#000000">Sleep</font></b><font color="#990000">(</font>a<font color="#990000">)</font>
	<b><font color="#0000FF">if</font></b> <font color="#990000">!</font>a<font color="#990000">.</font><b><font color="#000000">Sorted</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
		t<font color="#990000">.</font><b><font color="#000000">Errorf</font></b><font color="#990000">(</font><font color="#FF0000">"Array not sorted: %v"</font><font color="#990000">,</font> a<font color="#990000">)</font>
	<font color="#FF0000">}</font>
<font color="#FF0000">}</font>
</pre>
<br />
<span>As you can see, it takes <span class='inlinecode'>9s</span> here for the algorithm to finish (which is the highest value in the <span class='inlinecode'>ArrayList</span>):</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>❯ go <b><font color="#0000FF">test</font></b> <font color="#990000">.</font>/sort -v -run SleepSort
<font color="#990000">===</font> RUN   TestSleepSort
--- PASS<font color="#990000">:</font> TestSleepSort <font color="#990000">(</font><font color="#993399">9</font><font color="#990000">.</font>00s<font color="#990000">)</font>
PASS
ok      codeberg<font color="#990000">.</font>org/snonux/algorithms/sort     <font color="#993399">9</font><font color="#990000">.</font>002s
</pre>
<br />
<span>I won&#39;t write any benchmark for sleep sort; that will be done for the algorithms to come in this series :-).</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>'Never split the difference' book notes</title>
        <link href="gemini://foo.zone/gemfeed/2023-04-01-never-split-the-difference-book-notes.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-04-01-never-split-the-difference-book-notes.gmi</id>
        <updated>2023-04-01T20:00:17+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>These are my personal takeaways after reading 'Never split the difference' by Chris Voss. Note that the book contains much more knowledge wisdom and that these notes only contain points I personally found worth writing down. This is mainly for my own use, but you might find it helpful too.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>"Never split the difference" book notes</h1><br />
<br />
<span class='quote'>Published at 2023-04-01T20:00:17+03:00</span><br />
<br />
<span>These are my personal takeaways after reading "Never split the difference" by Chris Voss. Note that the book contains much more knowledge wisdom and that these notes only contain points I personally found worth writing down. This is mainly for my own use, but you might find it helpful too.</span><br />
<br />
<pre>
         ,..........   ..........,
     ,..,&#39;          &#39;.&#39;          &#39;,..,
    ,&#39; ,&#39;            :            &#39;, &#39;,
   ,&#39; ,&#39;             :             &#39;, &#39;,
  ,&#39; ,&#39;              :              &#39;, &#39;,
 ,&#39; ,&#39;............., : ,.............&#39;, &#39;,
,&#39;  &#39;............   &#39;.&#39;   ............&#39;  &#39;,
 &#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;;&#39;&#39;&#39;;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;
                    &#39;&#39;&#39;
</pre>
<br />
<h2 style='display: inline'>Tactical listening, spreading empathy</h2><br />
<br />
<span>Be a mirror, copy each other to be comfy with each other to build up trust. Mirroring is mainly body language. A mirror is to repeat the words the other just said. Simple but effective.</span><br />
<br />
<ul>
<li>A mirror needs space and silence between the words. At least 4 seconds.</li>
<li>A mirror might be awkward to be used at first, especially with a question coupled to it.</li>
<li>We fear what&#39;s different and are drawn to what is similar.</li>
</ul><br />
<span>Mirror training is like Jedi training. Simple but effective. A mirror needs space. Be silent after "you want this?" </span><br />
<br />
<h2 style='display: inline'>Mindset of discovery</h2><br />
<br />
<span>Try to have multiple realities in your mind and use facts to distinguish between real and false.</span><br />
<br />
<ul>
<li>Focus on what the counterpart has to say and what he needs and wants. Understanding him makes him vulnerable.</li>
<li>Empathy understanding the other person from his perspective, but it does not mean agreeing with him.</li>
<li>Detect and label the emotions of others for your powers. </li>
<li>To be understood seems to solve all problems magically.</li>
</ul><br />
<span>Try: to put a label on someone&#39;s emotion and then be silent. Wait for the other to reveal himself. "You seem unhappy about this?"</span><br />
<br />
<h3 style='display: inline'>More tips </h3><br />
<br />
<ul>
<li>Put on a poker face and don&#39;t show emotions.</li>
<li>Slow things down. Don&#39;t be a problem solver.</li>
<li>Smile while you are talking, even on the phone. Be easy and encouraging.</li>
<li>Being right is not the key to successful negotiation; being mindful is.</li>
<li>Be in the safe zone of empathy and acknowledge bad news.</li>
</ul><br />
<h2 style='display: inline'>"No" starts the conversation</h2><br />
<br />
<span>When the opponent starts with a "no", he feels in control and comfortable. That&#39;s why he has to start with "no".</span><br />
<br />
<ul>
<li>"Yes" and "maybe" might be worthless, but "no" starts the conversation.</li>
<li>If someone is saying "no" to you, he will be open to what you have to say next.</li>
<li>"No" is not stopping the negotiation but will open up opportunities you were not thinking about before.</li>
<li>Start with "no". Great negotiators seek "no" because that&#39;s when the great discussions begin.</li>
<li>A "no" can be scary if you are not used to it. If your biggest fear is "no", then you can&#39;t negotiate.</li>
</ul><br />
<span>Get a "That&#39;s right" when negotiating. Don&#39;t get a "you&#39;re right". You can summarise the opponent to get a "that&#39;s right".</span><br />
<br />
<h2 style='display: inline'>Win-win</h2><br />
<br />
<span>Win-win is a naive approach when encountering the win-lose counterpart, but always cooperate. Don&#39;t compromise, and don&#39;t split the difference. We don&#39;t compromise because it&#39;s right; we do it because it is easy. You must embrace the hard stuff; that&#39;s where the great deals are.</span><br />
<br />
<h2 style='display: inline'>On Deadlines</h2><br />
<br />
<ul>
<li>All deadlines are imaginary.</li>
<li>Most of the time, deadlines unsettle us without a good reason.</li>
<li>They push a deal to a conclusion.</li>
<li>They rush the counterpart to cause pressure and anxiety.</li>
</ul><br />
<h2 style='display: inline'>Analyse the opponent</h2><br />
<br />
<ul>
<li>Understand the motivation of people behind the table as well.</li>
<li>Ask how affected they will be.</li>
<li>Determine your and the opposite negotiation style. Accommodation, analyst, assertive.</li>
<li>Treat them how they need to be treated.</li>
</ul><br />
<span>The person on the other side is never the issue; the problem is the issue. Keep this in mind to avoid emotional issues with the person and focus on the problem, not the person. The bond is essential; never create an enemy.</span><br />
<br />
<h2 style='display: inline'>Use different ways of saying "no."</h2><br />
<br />
<span class='quote'>I had paid my rent always in time. I had positive experiences with the building and would be sad for the landlord to lose a good tenant. I am looking for a win-win agreement between us. Pulling out the research, other neighbours offer much lower prices even if your building is a better location and services. How can I effort 200 more.... </span><br />
<br />
<span>...then put an extreme anker.</span><br />
<br />
<span>You always have to embrace thoughtful confrontation for good negotiation and life. Don&#39;t avoid honest, clear conflict. It will give you the best deals. Compromises are mostly bad deals for both sides. Most people don&#39;t negotiate a win-win but a win-lose. Know the best and worst outcomes and what is acceptable for you.</span><br />
<br />
<h2 style='display: inline'>Calibrated question</h2><br />
<br />
<span>Calibrated questions. Give the opponent a sense of power. Ask open-how questions to get the opponent to solve your problem and move him in your direction. Calibrated questions are the best tools. Summarise everything, and then ask, "how I am supposed to do that?". Asking for help this way with a calibrated question is a powerful tool for joint problem solving</span><br />
<br />
<span>Being calm and respectful is essential. Without control of your emotions, it won&#39;t work. The counterpart will have no idea how constrained they are with your question. Avoid questions which get a yes or short answers. Use "why?".</span><br />
<br />
<span>Counterparts are more involved if these are their solutions. The counterpart must answer with "that&#39;s right", not "you are right". He has to own the problem. If not, then add more why questions.</span><br />
<br />
<ul>
<li>Tone and body language need to align with what people are saying.</li>
<li>Deal with it via a labelled question. </li>
<li>Liers tend to talk with "them" and "their" and not with "I".</li>
<li>Also, liars tend to talk in complex sentences.</li>
</ul><br />
<span>Prepare 3 to 5 calibrated questions for your counterpart. Be curious what is really motivating the other side. You can get out the "Black Swan".</span><br />
<br />
<h2 style='display: inline'>The black swan </h2><br />
<br />
<span>What we don&#39;t know can break our deal. Uncovering it can bring us unexpected success. You get what you ask for in this world, but you must learn to ask correctly. Reveal the black swan by asking questions.</span><br />
<br />
<h2 style='display: inline'>More</h2><br />
<br />
<span>Establish a range at top places like corp. I get... (e.g. remote London on a project basis). Set a high salary range and not a number. Also, check on LinkedIn premium for the salaries.</span><br />
<br />
<ul>
<li>Give an unexpected gift, e.g. show them my pet project and publicity for engineering.</li>
<li>Use an odd number, which makes you seem to have thought a lot about the sum and calculated it.</li>
<li>Define success and metrics for your next raise.</li>
<li>What does it take to be successful here? Ask the question, and they will tell you and guide you.</li>
<li>Set an extreme anker. Make the counterpart the illusion of losing something.</li>
<li>Hope-based deals. Hope is not a strategy.</li>
<li>Tactical empathy, listening as a martial art. It is emotional intelligence on steroids.</li>
<li>Being right isn&#39;t the key to a successful negotiation, but having the correct mindset is.</li>
<li>Don&#39;t shop the groceries when you are hungry.</li>
</ul><br />
<span>Slow.... it.... down....</span><br />
<br />
<span>Other book notes of mine are:</span><br />
<br />
<a class='textlink' href='./2023-05-06-the-obstacle-is-the-way-book-notes.html'>2023-05-06 "The Obstacle is the Way" book notes</a><br />
<a class='textlink' href='./2023-04-01-never-split-the-difference-book-notes.html'>2023-04-01 "Never split the difference" book notes (You are currently reading this)</a><br />
<a class='textlink' href='./2023-03-16-the-pragmatic-programmer-book-notes.html'>2023-03-16 "The Pragmatic Programmer" book notes</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Gemtexter 2.0.0 - Let's Gemtext again²</title>
        <link href="gemini://foo.zone/gemfeed/2023-03-25-gemtexter-2.0.0-lets-gemtext-again-2.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-03-25-gemtexter-2.0.0-lets-gemtext-again-2.gmi</id>
        <updated>2023-03-25T17:50:32+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I proudly announce that I've released Gemtexter version `2.0.0`. What is Gemtexter? It's my minimalist static site generator for Gemini Gemtext, HTML and Markdown written in GNU Bash.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Gemtexter 2.0.0 - Let&#39;s Gemtext again²</h1><br />
<br />
<span class='quote'>Published at 2023-03-25T17:50:32+02:00</span><br />
<br />
<pre>
-=[ typewriters ]=-  1/98

       .-------.
      _|~~ ~~  |_       .-------.
    =(_|_______|_)=    _|~~ ~~  |_
      |:::::::::|    =(_|_______|_)
      |:::::::[]|      |:::::::::|
      |o=======.|      |:::::::[]|
 jgs  `"""""""""`      |o=======.|
  mod. by Paul Buetow  `"""""""""`
</pre>
<br />
<span>I proudly announce that I&#39;ve released Gemtexter version <span class='inlinecode'>2.0.0</span>. What is Gemtexter? It&#39;s my minimalist static site generator for Gemini Gemtext, HTML and Markdown written in GNU Bash.</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/gemtexter'>https://codeberg.org/snonux/gemtexter</a><br />
<br />
<span>This is a new major release, so it contains a breaking change (see "Meta cache made obsolete").</span><br />
<br />
<span>Let&#39;s list what&#39;s new!</span><br />
<br />
<h2 style='display: inline'>Minimal template engine</h2><br />
<br />
<span>Gemtexter now supports templating, enabling dynamically generated content to <span class='inlinecode'>.gmi</span> files before converting anything to any output format like HTML and Markdown.</span><br />
<br />
<span>A template file name must have the suffix <span class='inlinecode'>gmi.tpl</span>. A template must be put into the same directory as the Gemtext <span class='inlinecode'>.gmi</span> file to be generated. Gemtexter will generate a Gemtext file <span class='inlinecode'>index.gmi</span> from a given template <span class='inlinecode'>index.gmi.tpl</span>. A <span class='inlinecode'>&lt;&lt;&lt;</span> and <span class='inlinecode'>&gt;&gt;&gt;</span> encloses a multiline template. All lines starting with <span class='inlinecode'>&lt;&lt; </span> will be evaluated as a single line of Bash code and the output will be written into the resulting Gemtext file.</span><br />
<br />
<span>For example, the template <span class='inlinecode'>index.gmi.tpl</span>:</span><br />
<br />
<pre>
# Hello world

&lt;&lt; echo "&gt; This site was generated at $(date --iso-8601=seconds) by \`Gemtexter\`"

Welcome to this capsule!

&lt;&lt;&lt;
  for i in {1..10}; do
    echo Multiline template line $i
  done
&gt;&gt;&gt;
</pre>
<br />
<span>... results into the following <span class='inlinecode'>index.gmi</span> after running <span class='inlinecode'>./gemtexter --generate</span> (or <span class='inlinecode'>./gemtexter --template</span>, which instructs to do only template processing and nothing else):</span><br />
<br />
<pre>
# Hello world

&gt; This site was generated at 2023-03-15T19:07:59+02:00 by `Gemtexter`

Welcome to this capsule!

Multiline template line 1
Multiline template line 2
Multiline template line 3
Multiline template line 4
Multiline template line 5
Multiline template line 6
Multiline template line 7
Multiline template line 8
Multiline template line 9
Multiline template line 10
</pre>
<br />
<span>Another thing you can do is insert an index with links to similar blog posts. E.g.:</span><br />
<br />
<pre>
See more entries about DTail and Golang:

&lt;&lt; template::inline::index dtail golang

Blablabla...
</pre>
<br />
<span>... scans all other post entries with <span class='inlinecode'>dtail</span> and <span class='inlinecode'>golang</span> in the file name and generates a link list like this:</span><br />
<br />
<pre>
See more entries about DTail and Golang:

=&gt; ./2022-10-30-installing-dtail-on-openbsd.gmi 2022-10-30 Installing DTail on OpenBSD
=&gt; ./2022-04-22-programming-golang.gmi 2022-04-22 The Golang Programming language
=&gt; ./2022-03-06-the-release-of-dtail-4.0.0.gmi 2022-03-06 The release of DTail 4.0.0
=&gt; ./2021-04-22-dtail-the-distributed-log-tail-program.gmi 2021-04-22 DTail - The distributed log tail program (You are currently reading this)

Blablabla...
</pre>
<br />
<h2 style='display: inline'>Added hooks</h2><br />
<br />
<span>You can configure <span class='inlinecode'>PRE_GENERATE_HOOK</span> and <span class='inlinecode'>POST_PUBLISH_HOOK</span> to point to scripts to be executed before running <span class='inlinecode'>--generate</span>, or after running <span class='inlinecode'>--publish</span>. E.g. you could populate some of the content by an external script before letting Gemtexter do its thing or you could automatically deploy the site after running <span class='inlinecode'>--publish</span>.</span><br />
<br />
<span>The sample config file <span class='inlinecode'>gemtexter.conf</span> includes this as an example now; these scripts will only be executed when they actually exist:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">declare</font></b> -xr <font color="#009900">PRE_GENERATE_HOOK</font><font color="#990000">=.</font>/pre_generate_hook<font color="#990000">.</font>sh
<b><font color="#0000FF">declare</font></b> -xr <font color="#009900">POST_PUBLISH_HOOK</font><font color="#990000">=.</font>/post_publish_hook<font color="#990000">.</font>sh
</pre>
<br />
<h2 style='display: inline'>Use of safer Bash options</h2><br />
<br />
<span>Gemtexter now does <span class='inlinecode'>set -euf -o pipefile</span>, which helps to eliminate bugs and to catch scripting errors sooner. Previous versions only <span class='inlinecode'>set -e</span>.</span><br />
<br />
<h2 style='display: inline'>Meta cache made obsolete</h2><br />
<br />
<span>Here is the breaking change to older versions of Gemtexter. The <span class='inlinecode'>$BASE_CONTENT_DIR/meta</span> directory was made obsolete. <span class='inlinecode'>meta</span> was used to store various information about all the blog post entries to make generating an Atom feed in Bash easier. Especially the publishing dates of each post were stored there. Instead, the publishing date is now encoded in the <span class='inlinecode'>.gmi</span> file. And if it is missing, Gemtexter will set it to the current date and time at first run.</span><br />
<br />
<span>An example blog post without any publishing date looks like this:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#990000">%</font> cat gemfeed<font color="#990000">/</font><font color="#993399">2023</font>-<font color="#993399">02</font>-<font color="#993399">26</font>-title-here<font color="#990000">.</font>gmi
<i><font color="#9A1900"># Title here</font></i>

The remaining content of the Gemtext file<font color="#990000">...</font>
</pre>
<br />
<span>Gemtexter will add a line starting with  <span class='inlinecode'>&gt; Published at ...</span> now. Any subsequent Atom feed generation will then use that date.</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#990000">%</font> cat gemfeed<font color="#990000">/</font><font color="#993399">2023</font>-<font color="#993399">02</font>-<font color="#993399">26</font>-title-here<font color="#990000">.</font>gmi
<i><font color="#9A1900"># Title here</font></i>

<font color="#990000">&gt;</font> Published at <font color="#993399">2023</font>-<font color="#993399">02</font>-26T21<font color="#990000">:</font><font color="#993399">43</font><font color="#990000">:</font><font color="#993399">51</font><font color="#990000">+</font><font color="#993399">01</font><font color="#990000">:</font><font color="#993399">00</font>

The remaining content of the Gemtext file<font color="#990000">...</font>
</pre>
<br />
<h2 style='display: inline'>XMLLint support</h2><br />
<br />
<span>Optionally, when the <span class='inlinecode'>xmllint</span> binary is installed, Gemtexter will perform a simple XML lint check against the Atom feed generated. This is a double-check of whether the Atom feed is a valid XML.</span><br />
<br />
<h2 style='display: inline'>More</h2><br />
<br />
<span>Additionally, there were a couple of bug fixes, refactorings and overall improvements in the documentation made. </span><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2023-03-25-gemtexter-2.0.0-lets-gemtext-again-2.html'>2023-03-25 Gemtexter 2.0.0 - Let&#39;s Gemtext again² (You are currently reading this)</a><br />
<a class='textlink' href='./2022-08-27-gemtexter-1.1.0-lets-gemtext-again.html'>2022-08-27 Gemtexter 1.1.0 - Let&#39;s Gemtext again</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all</a><br />
<a class='textlink' href='./2021-04-24-welcome-to-the-geminispace.html'>2021-04-24 Welcome to the Geminispace</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>'The Pragmatic Programmer' book notes</title>
        <link href="gemini://foo.zone/gemfeed/2023-03-16-the-pragmatic-programmer-book-notes.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-03-16-the-pragmatic-programmer-book-notes.gmi</id>
        <updated>2023-03-16T00:55:20+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>These are my personal takeaways after reading 'The Pragmatic Programmer' by David Thomas and Andrew Hunt. Note that the book contains much more knowledge wisdom and that these notes only contain points I personally found worth writing down. This is mainly for my own use, but you might find it helpful too.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>"The Pragmatic Programmer" book notes</h1><br />
<br />
<span class='quote'>Published at 2023-03-16T00:55:20+02:00</span><br />
<br />
<span>These are my personal takeaways after reading "The Pragmatic Programmer" by David Thomas and Andrew Hunt. Note that the book contains much more knowledge wisdom and that these notes only contain points I personally found worth writing down. This is mainly for my own use, but you might find it helpful too.</span><br />
<br />
<pre>
         ,..........   ..........,
     ,..,&#39;          &#39;.&#39;          &#39;,..,
    ,&#39; ,&#39;            :            &#39;, &#39;,
   ,&#39; ,&#39;             :             &#39;, &#39;,
  ,&#39; ,&#39;              :              &#39;, &#39;,
 ,&#39; ,&#39;............., : ,.............&#39;, &#39;,
,&#39;  &#39;............   &#39;.&#39;   ............&#39;  &#39;,
 &#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;;&#39;&#39;&#39;;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;
                    &#39;&#39;&#39;
</pre>
<br />
<span>Think about your work while doing it - every day on every project. Have a feeling of continuous improvement. </span><br />
<br />
<ul>
<li>Be a realist.</li>
<li>Smell challenges.</li>
<li>Care about your craft.</li>
<li>Code can always be flawed, but it can meet the requirements.</li>
<li>You should be proud of your code, though.</li>
</ul><br />
<span>No one writes perfect code, including you. However:</span><br />
<br />
<ul>
<li>Paranoia is good thinking.</li>
<li>Practice defensive programming and crash early.</li>
<li>Crashing is often the best thing you can do. </li>
<li>Changes should be reversible.</li>
</ul><br />
<span>Erlang: Defensive programming is a waste of time. Let it crash. "This can never happen" - don&#39;t practise that kind of self-deception when programming. </span><br />
<br />
<span>Leave assertions in the code, even in production. Only leave out the assertions causing the performance issues.</span><br />
<br />
<span>Take small steps, always. Get feedback, too, for each of the steps the code does. Avoid fortune telling. If you have to involve in it, then the step is too large.</span><br />
<br />
<span>Decouple the code (e.g. OOP or functional programming). Prefer interfaces for types and mixins for a class extension over class inheritance.</span><br />
<br />
<ul>
<li>Refactor now and not later.</li>
<li>Later, it will be even more painful.</li>
</ul><br />
<span>Don&#39;t think outside the box. Find the box. The box is more extensive than you think. Think about the hard problem at hand. Do you have to do it a certain way, or do you have to do it at all?</span><br />
<br />
<span>Do what works and not what&#39;s fashionable. E.g. does SCRUM make sense? The goal is to deliver deliverables and not to "become" agile.</span><br />
<br />
<h2 style='display: inline'>Continuous learning</h2><br />
<br />
<span>Add new tools to your repertoire every day and keep the momentum up. Learning new things is your most crucial aspect. Invest regularly in your knowledge portfolio. The learning process extends your thinking. It does not matter if you will never use it.</span><br />
<br />
<ul>
<li>Learn a new programming language every year.</li>
<li>Read a technical book every month.</li>
<li>Take courses.</li>
</ul><br />
<span>Think critically about everything you learn. Use paper for your notes. There is something special about it.</span><br />
<br />
<h2 style='display: inline'>Stay connected</h2><br />
<br />
<span>It&#39;s your life, and you own it. Bruce Lee once said: </span><br />
<br />
<span class='quote'>"I am not on the world to life after your expectations, neither are you to life after mine."</span><br />
<br />
<ul>
<li>Go to meet-ups and actively engage.</li>
<li>Stay current.</li>
<li>Dealing with computers is hard. Dealing with people is harder. </li>
</ul><br />
<span>It&#39;s your life. Share it, celebrate it, be proud and have fun.</span><br />
<br />
<h2 style='display: inline'>The story of stone soup</h2><br />
<br />
<span>How to motivate others to contribute something (e.g. ideas to a startup):</span><br />
<br />
<span class='quote'>A kindly, old stranger was walking through the land when he came upon a village. As he entered, the villagers moved towards their homes, locking doors and windows. The stranger smiled and asked, why are you all so frightened. I am a simple traveler, looking for a soft place to stay for the night and a warm place for a meal. "There&#39;s not a bite to eat in the whole province," he was told. "We are weak and our children are starving. Better keep moving on." "Oh, I have everything I need," he said. "In fact, I was thinking of making some stone soup to share with all of you." He pulled an iron cauldron from his cloak, filled it with water, and began to build a fire under it. Then, with great ceremony, he drew an ordinary-looking stone from a silken bag and dropped it into the water. By now, hearing the rumor of food, most of the villagers had come out of their homes or watched from their windows. As the stranger sniffed the "broth" and licked his lips in anticipation, hunger began to overcome their fear. "Ahh," the stranger said to himself rather loudly, "I do like a tasty stone soup. Of course, stone soup with cabbage -- that&#39;s hard to beat." Soon a villager approached hesitantly, holding a small cabbage he&#39;d retrieved from its hiding place, and added it to the pot. "Wonderful!!" cried the stranger. "You know, I once had stone soup with cabbage and a bit of salt beef as well, and it was fit for a king." The village butcher managed to find some salt beef . . .  And so it went, through potatoes, onions, carrots, mushrooms, and so on, until there was indeed a delicious meal for everyone in the village to share. The village elder offered the stranger a great deal of money for the magic stone, but he refused to sell it and traveled on the next day. As he left, the stranger came upon a group of village children standing near the road. He gave the silken bag containing the stone to the youngest child, whispering to a group, "It was not the stone, but the villagers that had performed the magic." </span><br />
<br />
<span>By working together, everyone contributes what they can, achieving a greater good together.</span><br />
<br />
<span>Other book notes of mine are:</span><br />
<br />
<a class='textlink' href='./2023-05-06-the-obstacle-is-the-way-book-notes.html'>2023-05-06 "The Obstacle is the Way" book notes</a><br />
<a class='textlink' href='./2023-04-01-never-split-the-difference-book-notes.html'>2023-04-01 "Never split the difference" book notes</a><br />
<a class='textlink' href='./2023-03-16-the-pragmatic-programmer-book-notes.html'>2023-03-16 "The Pragmatic Programmer" book notes (You are currently reading this)</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../resources.html'>More books and other resources I found useful.</a><br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>How to shut down after work</title>
        <link href="gemini://foo.zone/gemfeed/2023-02-26-how-to-shut-down-after-work.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-02-26-how-to-shut-down-after-work.gmi</id>
        <updated>2023-02-26T23:48:01+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Do you need help fully discharging from work in the evenings or for the weekend? Shutting down from work won't just improve your work-life balance; it will also significantly improve the quality of your personal life and work. After a restful weekend, you will be much more energized and productive the next working day. So it should not just be in your own, but also your employers' interest that you fully relax and shut down after work. </summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>How to shut down after work</h1><br />
<br />
<span class='quote'>Published at 2023-02-26T23:48:01+02:00</span><br />
<br />
<pre>
    |\   "Music should be heard not only with the ears, but also the soul."
|---|--\-----------------------|-----------------------------------------|  
|   |   |\                     |                   |@     |\             |
|---|---|--\-------------------|-------------/|----|------|--\----|------|     
|  @|   |   |\          |O     |        3  /  |    |@     |       |      | 
|---|--@|---|--\--------|------|---------/----|----|------|-------|------|      
|  @|      @|    \      |O     |       / |    |    |@    @|      @|.     | 
|-----------|-----|-----|------|-----/---|---@|----|--------------|------|     
|          @|     |     |O     |    |    |         |             @|.     | 
|-----------|----@|-----|------|----|---@|------------------------|------|  
           @|           |           |        Larry Komro         @|.     
                                  -@-        [kom...@uwec.edu]
</pre>
<br />
<span>Do you need help fully discharging from work in the evenings or for the weekend? Shutting down from work won&#39;t just improve your work-life balance; it will also significantly improve the quality of your personal life and work. After a restful weekend, you will be much more energized and productive the next working day. So it should not just be in your own, but also your employers&#39; interest that you fully relax and shut down after work. </span><br />
<br />
<h2 style='display: inline'>Have a shutdown routine</h2><br />
<br />
<span>Have a routine. Try to finish work around the same time every day. Write any outstanding tasks down for the next day, so you are sure you will remember them. Writing them down brings wonders as you can remove them from your mind for the remainder of the day (or the upcoming weekend) as you know you will surely pick them up the next working day. Tidying up your workplace could also count toward your daily shutdown routine. </span><br />
<br />
<span>A commute home from the office also greatly helps, as it disconnects your work from your personal life. Don&#39;t work on your commute home, though! If you don&#39;t commute but work from home, then it helps to walk around the block or in a nearby park to disconnect from work. </span><br />
<br />
<h2 style='display: inline'>Don&#39;t work when you officially don&#39;t work</h2><br />
<br />
<span>Unless you are self-employed, you have likely signed an N-hour per week contract with your employer, and your regular working times are from X o&#39;clock in the morning to Y o&#39;clock in the evening (with M minutes lunch break in the middle). And there might be some flexibility in your working times, too. But that kind of flexibility (e.g. extending the lunch break so that there is time to pick up a family member from the airport) will be agreed upon, and you will counteract it, for example, by starting working earlier the next day or working late, that one exception. But overall, your weekly working time will stay N hours. </span><br />
<br />
<span>Another exception would be when you are on an on-call schedule and are expected to watch your work notifications out-of-office times. But that is usually only a few days per month and, therefore, not the norm. And it should also be compensated accordingly. </span><br />
<br />
<span>There might be some maintenance work you must carry out, which can only be done over the weekend, but it should be explicitly agreed upon and compensated for. Also, there might be a scenario that a production incident comes up shortly before the end of the work day, requiring you (and your colleagues) to stay a bit longer. But this should be an exceptional case.</span><br />
<br />
<span>Other than that, there is no reason why you should work out-of-office hours. I know many people who suffer "the fear of missing out", so slack messages and E-Mails are checked until late in the evening, during weekends or holidays. I have been improving here personally a lot over the last couple of months, but still, I fall into this trap occasionally. </span><br />
<br />
<span>Also, when you respond to slack messages and E-Mails, your colleagues can think that you have nothing better to do. They also will take it for granted and keep slacking and messaging you out of regular office times. </span><br />
<br />
<span>Checking for your messages constantly outside of regular office times makes it impossible to shut down and relax from work altogether. </span><br />
<br />
<h2 style='display: inline'>Distract your mind</h2><br />
<br />
<span>Often, your mind goes back to work-related stuff even after work. That&#39;s normal as you concentrated highly on your work throughout the day. The brain unconsciously continues to work and will automatically present you with random work-related thoughts. You can counteract this by focusing on non-work stuff, which may include:</span><br />
<br />
<ul>
<li>Exercise. A half an hour workout or yoga session, followed by some stretching, helps to calm your mind after work. </li>
<li>Play (with your family, pets, friends, or video game)</li>
<li>Mindfully listen to music. When have you ever "really" listened to music? I mean, not just as a background stimulation but really paid attention to the melody, rhythm, voice and lyrics? That requires focused attention and distracts you from other thoughts. </li>
<li>Think of or work on that fun passion project. I currently, for example, like to learn and code a bit in Rakulang. </li>
<li>Read. Nothing beats reading a good Science Fiction Novel (or whatever you prefer) before falling asleep.</li>
</ul><br />
<span>Some of these can be habit-stacked: Exercise could be combined with watching videos about your passion project (e.g. watching lectures about that new programming language you are currently learning for fun). With walking, for example, you could combine listening to an Audiobook or music, or you could also think about your passion project during that walk.  </span><br />
<br />
<h2 style='display: inline'>Get a pet</h2><br />
<br />
<span>Even if you have children, it helps wonders to get a pet. My cat, for example, will remind me a few times daily to take a few minute&#39;s breaks to pet, play or give food. So my cat not only helps me after work but throughout the day.</span><br />
<br />
<span>My neighbour also works from home, and he has dogs, which he regularly has to take out to the park.</span><br />
<br />
<h2 style='display: inline'>Journal your day</h2><br />
<br />
<span>If you are upset about something, making it impossible to shut down from work, write down everything (e.g., with a pen in a paper journal). Writing things down helps you to "get rid" of the negative. Especially after conflicts with colleagues or company decisions, you don&#39;t agree on. This kind of self-therapy is excellent. Brainstorm all your emotions and (even if opinionated) opinions so you have everything on paper. Once done, you don&#39;t think about it so much anymore, as you know you can access that information if required. But stopping ruminating about it will be much easier now. You will likely never access that information again, though. But at least writing the thoughts down saved your day. </span><br />
<br />
<span>Write down three things which went well for the day. This helps you to appreciate the day. </span><br />
<br />
<h2 style='display: inline'>Don&#39;t stress about what your employer expects from you</h2><br />
<br />
<span>Think about what&#39;s fun and motivates you. Maybe the next promotion to Principal or a Manager role isn&#39;t for you. Many fall into the trap of stressing themselves out to satisfy the employer so that the next upgrade will happen and think about it constantly, even after work. But it is more important that you enjoy your craftsmanship. Work on what you expect from yourself. Ideally, your goals should be aligned with your employer. I am not saying you should abandon everything what your manager is asking you to do, but it is, after all, your life. And you have to decide where and on what you want to work. But don&#39;t sell yourself short. Keep track of your accomplishments.</span><br />
<br />
<h2 style='display: inline'>Call it a day</h2><br />
<br />
<span>Every day you gave your best was good; the day&#39;s outcome doesn&#39;t matter. What matters is that you know you gave your best and are closer to your goals than the previous day. This gives you a sense of progress and accomplishment.</span><br />
<br />
<span>There are some days at work you feel drained afterwards and think you didn&#39;t progress towards your goals at all. It&#39;s more challenging to shut down from work after such a day. A quick hack is to work on a quick win before the end of the day, giving you a sense of accomplishment after all. Another way is to make progress on your fun passion project after work. It must not be work-related, but a sense of accomplishment will still be there.</span><br />
<span> </span><br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Why GrapheneOS rox</title>
        <link href="gemini://foo.zone/gemfeed/2023-01-23-why-grapheneos-rox.gmi" />
        <id>gemini://foo.zone/gemfeed/2023-01-23-why-grapheneos-rox.gmi</id>
        <updated>2023-01-23T15:31:52+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Art by Joan Stark</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Why GrapheneOS rox</h1><br />
<br />
<span class='quote'>Published at 2023-01-23T15:31:52+02:00</span><br />
<br />
<pre>
Art by Joan Stark
               _.===========================._
            .&#39;`  .-  - __- - - -- --__--- -.  `&#39;.
        __ / ,&#39;`     _|--|_________|--|_     `&#39;. \
      /&#39;--| ;    _.&#39;\ |  &#39;         &#39;  | /&#39;._    ; |
     //   | |_.-&#39; .-&#39;.&#39;      ___      &#39;.&#39;-. &#39;-._| |
    (\)   \"` _.-` /     .-&#39;`_ `&#39;-.     \ `-._ `"/
    (\)    `-&#39;    |    .&#39; .-&#39;" "&#39;-. &#39;.    |    `-`
   (\)            |   / .&#39;(3)(2)(1)&#39;. \   |
   (\)            |  / / (4) .-.     \ \  |
   (\)            |  | |(5) (   )&#39;==,J |  |
  (\)             |  \ \ (6) &#39;-&#39; (0) / /  |
 (\)              |   \ &#39;.(7)(8)(9).&#39; /   |
 (\)           ___|    &#39;. &#39;-.._..-&#39; .&#39;    |
 (\)          /.--|      &#39;-._____.-&#39;      |
  (\)        (\)  |\_  _  __   _   __  __/|
 (\)        (\)   |                       |
(\)_._._.__(\)    |                       |
 (\\\\jgs\\\)      &#39;.___________________.&#39;
  &#39;-&#39;-&#39;-&#39;--&#39;
</pre>
<br />
<span>In 2021 I wrote "On Being Pedantic about Open-Source", and there was a section "What about mobile?" where I expressed the dilemma about the necessity of using proprietary mobile operating systems. With GrapheneOS, I found my perfect solution for personal mobile phone use. </span><br />
<br />
<a class='textlink' href='./2021-08-01-on-being-pedantic-about-open-source.html'>On Being Pedantic about Open-Source</a><br />
<br />
<span>What is GrapheneOS?</span><br />
<br />
<span class='quote'>GrapheneOS is a privacy and security-focused mobile OS with Android app compatibility developed as a non-profit open-source project. It&#39;s focused on the research and development of privacy and security technologies, including substantial improvements to sandboxing, exploits mitigations and the permission model.</span><br />
<br />
<span>GrapheneOS is an independent Android distribution based on the Android Open Source Project (AOSP) but hardened in multiple ways. Other independent Android distributions, like LineageOS, are also based on AOSP, but GrapheneOS takes it further so that it can be my daily driver on my phone.</span><br />
<br />
<a class='textlink' href='https://GrapheneOS.org'>https://GrapheneOS.org</a><br />
<a class='textlink' href='https://LineageOS.org'>https://LineageOS.org</a><br />
<br />
<h2 style='display: inline'>User Profiles</h2><br />
<br />
<span>GrapheneOS allows configuring up to 32 user profiles (including a guest profile) on a single phone. A profile is a completely different environment within the phone, and it is possible to switch between them instantly. Sessions of a profile can continue running in the background or be fully terminated. Each profile can have completely different settings and different applications installed.</span><br />
<br />
<span>I use my default profile with primarily open-source applications installed, which I trust. I use another profile for banking (PayPal, various proprietary bank apps, Amazon store app, etc.) and another profile for various Google services (which I try to avoid, but I have to use once in a while). Furthermore, I have configured a profile for Social Media use (that one isn&#39;t in my default profile, as otherwise I am tempted to scroll social media all the time, which I try to avoid and only want to do intentionally when switching to the corresponding profile!).</span><br />
<br />
<span>The neat thing about the profiles is that some can run a sandboxed version of Google Play (see later in this post), while others don&#39;t. So some profiles can entirely operate without any Google Play, and only some profiles (to which I rarely switch) have Google Play enabled. </span><br />
<br />
<span>You notice how much longer (multiple days) your phone can be on a single charge when Google Play Services isn&#39;t running in the background. This tells a lot about the background activities and indicates that using Google Play shouldn&#39;t be the norm.</span><br />
<br />
<h2 style='display: inline'>Proxying some of the Google offerings </h2><br />
<br />
<span>There&#39;s also the case that I am using an app from the Google Play store (as the app isn&#39;t available from F-Droid), which doesn&#39;t require Google Play Services to run in the background. Here&#39;s where I use the Aurora Android store. The Aurora store can be installed through F-Droid. Aurora acts as an anonymous proxy from your phone to the Google Play Store and lets you install apps from there. No Google credentials are required for that!</span><br />
<br />
<a class='textlink' href='https://f-droid.org'>https://f-droid.org</a><br />
<br />
<span>There&#39;s a similar solution for watching videos on YouTube. You can use the NewPipe app (also from F-Droid), which acts as an anonymous proxy for watching videos from YouTube. So there isn&#39;t any need to install the official YouTube app, and there isn&#39;t any need to login to your Google account. What&#39;s so bad about the official app? You don&#39;t know which data it is sending about you to Google, so it is a privacy concern. </span><br />
<br />
<h2 style='display: inline'>Google Play Sandboxing </h2><br />
<br />
<span>Before switching to GrapheneOS, I had been using LineageOS on one of my phones for a couple of years. Still, I always had to have a secondary personal phone with all of these proprietary apps which (partially) only work with Google Play on the phone (e.g. Banking, Navigation, various travel apps from various Airlines, etc.) somewhere around as I didn&#39;t install Google Play on my LineageOS phone due to privacy concerns and only installed apps from the F-Droid store on it. When travelling, I always had to carry around a second phone with Google Play on it, as without it; life would become inconvenient pretty soon. </span><br />
<br />
<span>With GrapheneOS, it is different. Here, I do not just have a separate user profile, "Google", for various Google apps where Google Play runs, but Google Play also runs in a sandbox!!!</span><br />
<br />
<span class='quote'>GrapheneOS has a compatibility layer providing the option to install and use the official releases of Google Play in the standard app sandbox. Google Play receives no special access or privileges on GrapheneOS instead of bypassing the app sandbox and receiving a massive amount of highly privileged access. Instead, the compatibility layer teaches it how to work within the full app sandbox. It also isn&#39;t used as a backend for the OS services as it would be elsewhere since GrapheneOS doesn&#39;t use Google Play even when it&#39;s installed.</span><br />
<br />
<span>When I need to access Google Play, I can switch to the "Google" profile. Even there, Google is sandboxed to the absolute minimum permissions required to be operational, which gives additional privacy protection.</span><br />
<br />
<span>The sad truth is that Google Maps is still the best navigation app. When driving unknown routes, I can switch to my Google profile to use Google Maps. I don&#39;t need to do that when going streets I know about, but it is crucial (for me) to have Google Maps around when driving to a new destination.</span><br />
<br />
<span>Also, Google Translate and Google Lens are still the best translation apps I know. I just recently relocated to another country, where I am still learning the language, so Google Lens has been proven very helpful on various occasions by ad-hoc translating text into English or German for me.</span><br />
<br />
<span>The same applies to banking. Many banking apps require Google Play to be available (It might be even more secure to only use banking apps from the Google Play store due to official support and security updates). I rarely need to access my mobile banking app, but once in a while, I need to. As you have guessed by now, I can switch to my banking profile (with Google Play enabled), do what I need to do, and then terminate the session and go back to my default profile, and then my life can go on :-). </span><br />
<br />
<span>It is great to have the flexibility to use any proprietary Android app when needed. That only applies to around 1% of my phone usage time, but you often don&#39;t always know when you need "that one app now". So it&#39;s perfect that it&#39;s covered with the phone you always have with you. </span><br />
<br />
<h2 style='display: inline'>The camera and the cloud </h2><br />
<br />
<span>I really want my phone to shoot good looking pictures, so that I can later upload them to the Irregular Ninja:</span><br />
<br />
<a class='textlink' href='https://irregular.ninja'>https://irregular.ninja</a><br />
<br />
<span>The stock camera app of the OASP could be better. Photos usually look washed out, and the app lacks features. With GrapheneOS, there are two options:</span><br />
<br />
<ul>
<li>Use the official Google camera app with sandboxed Google Play Services running. You will get the full Google experience here.</li>
<li>Or, just use the default GrapheneOS camera app.</li>
</ul><br />
<span>The GrapheneOS camera app is much better than the stock OASP camera app. I have been comparing the photo quality of my Pixel phone under LineageOS and GrapheneOS, and the differences are pronounced. I didn&#39;t compare the quality with the official Google camera app, but I have seen some comparison videos and the differences seem like they aren&#39;t groundbreaking. </span><br />
<br />
<span>For automatic backups of my photos, I am relying on a self-hosted instance of NextCloud (with a client app available via F-Droid). So there isn&#39;t any need to rely on any Google apps and services (Google Play Photos or Google Camera app) anymore, and that&#39;s great!</span><br />
<br />
<a class='textlink' href='https://nextcloud.com'>https://nextcloud.com</a><br />
<br />
<span>I also use NextCloud to synchronize my notes (NextCloud Notes), my RSS news feeds (NextCloud News) and contacts (DAVx5). All apps required are available in the F-Droid store.</span><br />
<br />
<h2 style='display: inline'>Fine granular permissions</h2><br />
<br />
<span>Another great thing about GrapheneOS is that, besides putting your apps into different profiles, you can also restrict network access and configure storage scopes per app individually.</span><br />
<br />
<span>For example, let&#39;s say you are installing that one proprietary app from the Google Play Store through the Aurora store, and then you want to ensure that the app doesn&#39;t send data "home" through the internet. Nothing is easier to do than that. Just remove network access permissions from that only app.</span><br />
<br />
<span>The app also wants to store and read some data from your phone (e.g. it could be a proprietary app for enhancing photos, and therefore storage access to a photo folder would be required). In GrapheneOS, you can configure a storage scope for that particular app, e.g. only read and write from one folder but still forbid access to all other folders on your phone.</span><br />
<br />
<h2 style='display: inline'>Termux</h2><br />
<br />
<span>Termux can be installed on any Android phone through F-Droid, so it doesn&#39;t need to be a GrapheneOS phone. But I have to mention Termux here as it significantly adds value to my phone experience. </span><br />
<br />
<span class='quote'>Termux is an Android terminal emulator and Linux environment app that works directly with no rooting or setup required. A minimal base system is installed automatically - additional packages are available using the APT package manager.</span><br />
<br />
<a class='textlink' href='https://termux.dev'>https://termux.dev</a><br />
<br />
<span>In short, Termux is an entire Linux environment running on your Android phone. Just pair your phone with a Bluetooth keyboard, and you will have the whole Linux experience. I am only using terminal Linux applications with Termux, though. What makes it especially great is that I could write on a new blog post (in Neovim through Termux on my phone) or do some coding whilst travelling (e.g. during a flight), or look up my passwords or some other personal documents (through my terminal-based password manager). All changes I commit to Git can be synced to the server with a simple <span class='inlinecode'>git push</span> once online (e.g. after the plane landed) again.</span><br />
<br />
<span>There are Pixel phones with a screen size of 6", and that&#39;s decent enough for occasional use like that, and everything (the phone, the BT keyboard, maybe an external battery pack) all fit nicely in a small travel pocket.</span><br />
<br />
<h2 style='display: inline'>So, why not use a pure Linux phone?</h2><br />
<br />
<span>Strictly speaking, an Android phone is a Linux phone, but it&#39;s heavily modified and customized. For me, a "pure" Linux phone is a more streamlined Linux kernel running in a distribution like Ubuntu Touch or Mobian. </span><br />
<br />
<span>A pure Linux phone, e.g. with Ubuntu Touch installed, e.g. on a PinePhone, Fairphone, the Librem 5 or the Volla phone, is very appealing to me. And they would also provide an even better Linux experience than Termux does. Some support running LineageOS within an Anbox, enabling you to run various proprietary Android apps occasionally within Linux.</span><br />
<br />
<a class='textlink' href='https://ubuntu-touch.io/'>Ubuntu Touch</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Linux_for_mobile_devices'>More Linux distributions for mobile devices </a><br />
<br />
<span>But here, Google Play would not be sandboxed; you could not configure individual network permissions and storage scopes like in GrapheneOS. Pure Linux-compatible phones usually come with a crappy camera, and the battery life is generally pretty bad (only a few hours). Also, no big tech company pushes the development of Linux phones. Everything relies on hobbyists, whereas multiple big tech companies put a lot of effort into the Android project, and a lot of code also goes into the Android Open-Source project.  </span><br />
<br />
<span>Currently, pure Linux phones are only a nice toy to tinker with but are still not ready (will they ever?) to be the daily driver. SailfishOS may be an exception; I played around with it in the past. It is pretty usable, but it&#39;s not an option for me as it is partial a proprietary operating system.</span><br />
<br />
<a class='textlink' href='https://sailfishos.org'>SailfishOS</a><br />
<br />
<h2 style='display: inline'>Small GrapheneOS downsides </h2><br />
<br />
<span>Sometimes, switching a profile to use a different app is annoying, and you can&#39;t copy and paste from the system clipboard from one profile to another. But that&#39;s a small price I am willing to pay!</span><br />
<br />
<span>Another thing is that GrapheneOS can only run on Google Pixel phones, whereas LineageOS can be installed on a much larger variety of hardware. But on the other hand, GrapheneOS works very well on Pixel phones. The GrapheneOS team can concentrate their development efforts on a smaller set of hardware which then improves the software&#39;s quality (best example: The camera app).</span><br />
<br />
<span>And, of course, GrapheneOS is an open-source project. This is a good thing; however, on the other side, nobody can guarantee that the OS will not break or will not damage your phone. You have to trust the GrapheneOS project and donate to the project so they can keep up with the great work. But I rather trust the GrapheneOS team than big tech. </span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>(Re)learning Java - My takeaways</title>
        <link href="gemini://foo.zone/gemfeed/2022-12-24-ultrarelearning-java-my-takeaways.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-12-24-ultrarelearning-java-my-takeaways.gmi</id>
        <updated>2022-12-24T23:18:40+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>As a regular participant in the annual Pet Project competition at work, I always try to find a project where I can learn something new. In this post, I would like to share my takeaways after revisiting Java. You can read about my motivations in my 'Creative universe' post:</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>(Re)learning Java - My takeaways</h1><br />
<br />
<span class='quote'>Published at 2022-12-24T23:18:40+02:00</span><br />
<br />
<a href='./2022-12-24-ultrarelearning-java-my-takeaways/learnjava.jpg'><img src='./2022-12-24-ultrarelearning-java-my-takeaways/learnjava.jpg' /></a><br />
<br />
<span>As a regular participant in the annual Pet Project competition at work, I always try to find a project where I can learn something new. In this post, I would like to share my takeaways after revisiting Java. You can read about my motivations in my "Creative universe" post:</span><br />
<br />
<a class='textlink' href='./2022-04-10-creative-universe.html'>Creative universe</a><br />
<br />
<span>I have been programming in Java back in the days as a university student, and even my Diploma Thesis I implemented in Java (it would require some overhaul so that it is fully compatible with a recent version of Java, though - It still compiles and runs, but with a lot of warnings, though!):</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/vs-sim'>VS-Sim: Distributed systems simulator</a><br />
<br />
<span>However, after that, I became a Linux Sysadmin and mainly continued programming in Perl, Puppet, bash, and a little Python. For personal use, I also programmed a bit in Haskell and C. After my Sysadmin role, I moved to London and became a Site Reliability Engineer (SRE), where I mainly programmed in Ruby, bash, Puppet and Golang and a little bit of C. </span><br />
<br />
<span>At my workplace, as an SRE, I don&#39;t do Java a lot. I have been reading Java code to understand the software better so I can apply and suggest workarounds or fixes to existing issues and bugs. However, most of our stack is in Java, and our Software Engineers use Java as their primary programming language.</span><br />
<br />
<h2 style='display: inline'>Stuck at Java 1.4</h2><br />
<br />
<span>Over time, I had been missing out on many new features that were added to the language since Java 1.4, so I decided to implement my next Pet Project in Java and learn every further aspect of the language as my main goal. Of course, I still liked the idea of winning a Pet Project Prize, but my main objective was to level up my Java skills.</span><br />
<br />
<h2 style='display: inline'>(Re)learning &amp; upskilling to Java 18</h2><br />
<br />
<h3 style='display: inline'>Effective Java</h3><br />
<br />
<span>This book was recommended by my brother and also by at least another colleague at work to be one of the best, if not the best, book about Java programming. I read the whole book from the beginning to the end and immersed myself in it. I fully agree; this is a great book. Every Java developer or Java software engineer should read it!</span><br />
<br />
<a href='./2022-12-24-ultrarelearning-java-my-takeaways/effective-java.jpg'><img src='./2022-12-24-ultrarelearning-java-my-takeaways/effective-java.jpg' /></a><br />
<br />
<span>I recommend reading the 90-part effective Java Series on <span class='inlinecode'>dev.to</span>. It&#39;s a perfect companion to the book as it explains all the chapters again but from a slightly different perspective and helps you to really understand the content.</span><br />
<br />
<a class='textlink' href='https://dev.to/kylec32/series/2292'>Kyle Carter&#39;s 90-part Effective Java Series </a><br />
<br />
<h3 style='display: inline'>Java Pub House</h3><br />
<br />
<span>During my lunch breaks, I usually have a walk around the block or in a nearby park. I used that time to listen to the Java Pub House podcast. I listened to *every* episode and learned tons of new stuff. I can highly recommend this podcast. Especially GraalVM, a high-performance JDK distribution written for Java and other JVM languages, captured my attention. GraalVM can compile Java code into native binaries, improving performance and easing the distribution of Java programs. Because of the latter, I should release a VS-Sim GraalVM edition one day through a Linux AppImage ;-).</span><br />
<br />
<a class='textlink' href='https://www.javapubhouse.com'>https://www.javapubhouse.com</a><br />
<a class='textlink' href='https://www.graalvm.org'>https://www.graalvm.org</a><br />
<br />
<h3 style='display: inline'>Java Concurrency course</h3><br />
<br />
<span>I also watched a course on O&#39;Reilly Safari Books online about Java Concurrency. That gave an excellent refresher on how the Java thread pools work and what were the concurrency primitives available in the standard library.</span><br />
<br />
<h3 style='display: inline'>Read a lot of Java code</h3><br />
<br />
<span>First, the source code is often the best documentation (if programmed nicely), and second, it helps to get the hang of the language and standard practices. I started to read more and more Java code at work. I did that whenever I had to understand how something, in particular, worked (e.g. while troubleshooting and debugging an issue). </span><br />
<br />
<h3 style='display: inline'>Observed Java code reviews</h3><br />
<br />
<span>Another great way to get the hang of Java again was to sneak into the code reviews of the Software Engineer colleagues. They are the expert on the matter and are a great source to copy knowledge. It&#39;s OK to stay passive and only follow the reviews. Sometimes, it&#39;s OK to step up and take ownership of the review. The developers will also always be happy to answer any naive questions which come up.</span><br />
<br />
<h3 style='display: inline'>Took ownership of a roadmap-Java project</h3><br />
<br />
<span>Besides my Pet Project, I also took ownership of a regular roadmap Java project at work, making an internal Java service capable of running in  Kubernetes. This was a bunch of minor changes and adding a bunch of classes and unit tests dealing with the statelessness and a persistent job queue in Redis. The job also involved reading and understanding a lot of already existing Java code. It wasn&#39;t part of my job description, but it was fun, and I learned a lot. The service runs smoothly in production now. Of course, all of my code got reviewed by my Software Engineering colleagues.</span><br />
<br />
<h2 style='display: inline'>The good</h2><br />
<br />
<span>From the new language features and syntaxes, there are many personal takeaways, and I can&#39;t possibly list them all, but here are some of my personal highlights:</span><br />
<br />
<ul>
<li>Static factory methods and public constructors both have their uses, and it pays to understand their relative merits. Often static factories are preferable (cleaner and easier to read), so avoid the reflex to provide public constructors without first considering static factories.</li>
<li>Java streams were utterly new to me. I love how they can help to produce more compact code. But it&#39;s challenging to set the line of when enough is enough. Overusing streams can have the opposite effect: Code becomes more complex and challenging to understand. And it is so easy to parallelize the computation of streams by "just" marking the stream as <span class='inlinecode'>.parallel()</span> (more on that later in this post).</li>
<li>Overall, object-oriented languages tend to include more and more functional paradigms. The functional interfaces, which Java provides now, are fantastic. Their full powers shine in combination with the use of streams. An entire book can be written about Java functional interfaces, so I leave it to you to do any further digging.</li>
<li>Local type inference help to reduce even more boilerplate code. E.g. instead of <span class='inlinecode'>Hash&lt;String,Hash&lt;String,String&gt;&gt; foo = new Hash&lt;String,Hash&lt;String,String&gt;&gt;();</span> it&#39;s possible to just write <span class='inlinecode'>var foo = new Hash&lt;String,Hash&lt;String,String&gt;&gt;();</span></li>
<li>Class inheritance isn&#39;t the preferred way anymore to structure reusable code. Now, it&#39;s composition over inheritance. E.g. use dependency injection (inject one object to another object through its constructor) or prefer interfaces (which now also support default implementations of methods) over class inheritance. This makes sense to me as I do that already when I program in Ruby. </li>
<li>I learned the <span class='inlinecode'>try-with-resources</span> pattern. Very useful in ensuring closing resources again correctly. No need anymore for complicated and nested <span class='inlinecode'>finally</span>-blocks, which used to be almost impossible to get right previously in case of an error condition (e.g. I/O error somewhere deeply nested in an input or output stream).</li>
<li>Optimize only when required. It&#39;s considered to be cleaner to prefer immutable variables (declaring them as <span class='inlinecode'>final</span>). I knew that already, but for Java, it always seemed to be a waste of resources (creating entirely new objects whenever states change), but apparently, it&#39;s okay. Java also does many internal tricks for performance optimization here, e.g. interning strings.</li>
<li>I learned about the concept of static member classes and the difference between non-static member classes (also sometimes known as inner classes). Non-static member classes have full access to all members of their outer class (think of closure). In contrast, static member classes act like completely separate classes without such access but provide the benefit of a nested name that can help group functionality in the code.</li>
<li>I learned about the existence of thread-local variables. These are only available to the current thread and aren&#39;t shared with other threads.</li>
<li>I learned about the concept of Java modules, which help to structure larger code bases better. The traditional Java packages are different. </li>
<li>I learned to love the new <span class='inlinecode'>Optional</span> type. I already knew the concept from Haskell, where <span class='inlinecode'>Maybe</span> would be the corresponding type. <span class='inlinecode'>Optional</span> helps to avoid <span class='inlinecode'>null</span>-pointers but comes with some (minimal) performance penalty. So, in the end, you end up with both <span class='inlinecode'>Optional</span> types and <span class='inlinecode'>null</span>-pointers in your code (depending on the requirements). But I like to prefer <span class='inlinecode'>Optional</span> over <span class='inlinecode'>null</span>-pointer when "no result" is a valid return value from a method.</li>
<li>The <span class='inlinecode'>enum</span> type is way more powerful than I thought. Initially, I felt an <span class='inlinecode'>enum</span> could only be used to define a list of constants and then to compare an instance to another instance of the same. An <span class='inlinecode'>enum</span> is still there to define a list of constants, but it&#39;s also almost like a <span class='inlinecode'>class</span> (you can implement constructors, and methods, inherit from other enums). There are quite a lot of possible use cases.</li>
<li>A small but almost the most helpful thing I learned is always to use the <span class='inlinecode'>@Override</span> annotation when overriding a method from a parent class. If done, Java helps to detect any typos or type errors when overriding methods. That&#39;s useful and spares a lot of time debugging where a method was mistakenly overloaded but not overridden.</li>
<li>Lambdas are much cleaner, shorter and easier to read than anonymous classes. Many Java libraries require passing instances of (anonymous) classes (e.g. in Swing) to other objects. Lambdas are so lovely because they are primarily compatible with the passing of anonymous classes, so they are a 1:1 replacement in many instances. Lambdas also play very nicely together with the Java functional interfaces, as each Lambda got a type, and the type can be an already existing functional interface (or, if you got a particular case, you could define your custom functional interface for your own set of Lambdas, of course).</li>
<li>I love the concept of Java records. You can think of a record as an immutable object holding some data (as members). They are ideal for pipe and stream processing. They are much easier to define (with much less boilerplate) and come with write protection out of the box.</li>
</ul><br />
<h2 style='display: inline'>The bad and the ugly</h2><br />
<br />
<span>There are also many ugly corners in Java. Many are doomed to stay there forever due to historical decisions and ensuring backward compatibility with older versions of the Java language and the Java standard library. </span><br />
<br />
<ul>
<li>Finalizers and cleaners seem obsolete, fragile and still, you can use them.</li>
<li>In many cases, extreme caution needs to be taken to minimize the accessibility of class members. You might think that Java provides the best "out-of-the-box" solution for proper encapsulation, but the language has many loopholes.</li>
<li>In the early days, Java didn&#39;t support generics yet. So what you would use is to cast everything to <span class='inlinecode'>Object</span>. Java now fully supports generics (for a while already), but you can still cast everything to <span class='inlinecode'>Object</span> and back to whatever type you want. That can lead to nasty runtime errors. Also, there&#39;s a particular case to convert between an Array of Object to an Array of String or from an Array of String to a List of String. Java can&#39;t convert between these types automatically, and extreme caution needs to be taken when enforcing so (e.g. through explicit type casts). In many of these cases, Java would print out warnings that need to be manually suppressed via annotations. Programming that way, converting data between old and new best practices, is clunky.</li>
<li>If you don&#39;t know what you do, Java streams can be all wrong. Side effects in functions used in streams can be nasty to debug. Also, don&#39;t just blindly add a <span class='inlinecode'>.parallel()</span> to your stream. You need to understand what the stream does and how it exactly works; otherwise, parallelizing a stream can impact the performance drastically (in a negative way). There need to be language constructs preventing you from doing the wrong things. That&#39;s so much easier to do it right in a purely functional programming language like Haskell.</li>
<li>Java is a pretty old language (already), so there are many obstacles to consider. There are too many exceptions and different outcomes of how Java code can behave. In most cases, when you write an API, every method you program needs to be documented so the user won&#39;t encounter any surprises using your code. Writing and reading a lot of documentation seems to be quite the overhead when the method name is already descriptive.</li>
<li>Java serialization is broken. It works, and the language still supports it, but you better not use Java&#39;s native way of object serialization and deserialization. Unbelievable how much can get wrong here, especially regarding security (injecting arbitrary code).</li>
<li>Being a bit spoiled by Golang&#39;s Goroutines, I was shocked about the limitations of the Java threads. They are resource hungry, and you can&#39;t just spin up millions of them as you would with Goroutines. I knew this limitation of threads already (as it&#39;s not a problem of the language but of how threads work in the OS), but still, I was pretty shocked when I got reminded of them again. Of course, there&#39;s a workaround: Use asynchronous sockets so that you don&#39;t waste a whole thread on a single I/O operation (in my case, waiting for a network response). Golang&#39;s runtime does that automatically for you: An OS thread will be re-used for other tasks until the network socket unblocks. Every modern programming language should support lightweight threads or Coroutines like Go&#39;s Goroutines. </li>
</ul><br />
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>While (re)learning Java, I felt like a student again and was quite enthusiastic about it initially. I invested around half a year, immersing myself intensively in Java (again). The last time I did that was many years ago as a university student. I even won a Silver Prize at work, implementing a project this year (2022 as of writing this). I feel confident now with understanding, debugging and patching Java code at work, which boosted my debugging and troubleshooting skills. </span><br />
<br />
<span>I don&#39;t hate Java, but I don&#39;t love programming in it, either. I will, I guess, always see Java as the necessary to get stuff done (reading code to understand how the service works, adding a tiny feature to make my life easier, adding a quick bug fix to overcome an obstacle...).</span><br />
<br />
<span>Although Java has significantly improved since 1.4, its code still tends to be more boilerplate. Not mainly because due to lines of code (Golang code tends to be quite repetitive, primarily when no generics are used), but due to the levels of abstractions it uses. Class hierarchies can be ten classes or deeper, and it is challenging to understand what the code is doing. Good test coverage and much documentation can mitigate the problem partially. Big enterprises use Java, and that also reflects to the language. There are too many libraries and too many abstractions that are bundled with too many legacy abstractions and interfaces and too many exceptions in the library APIs. There&#39;s even an external library named Lombok, which aims to reduce Java boilerplate code. Why is there a need for an external library? It should be all part of Java itself.</span><br />
<br />
<a class='textlink' href='https://projectlombok.org/'>https://projectlombok.org/</a><br />
<br />
<span>Java needs a clean cut. The clean cut shall be incompatible with previous versions of Java and only promote modern best practices without all the legacy burden carried around. The same can be said for other languages, e.g. Perl, but in Perl, they already attack the problem with the use of flags which change the behaviour of the language to more modern standards. Or do it like Python, where they had a hard (incompatible) cut from version 2 to version 3. It will be painful, for sure. But that would be the only way I would enjoy using that language as one of my primary languages to code new stuff regularly. Currently, my Java will stay limited to very few projects and the more minor things already mentioned in this post. </span><br />
<br />
<span>Am I a Java expert now? No, by far not. But I am better now than before :-).</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>I tried (Doom) Emacs, but I switched back to (Neo)Vim</title>
        <link href="gemini://foo.zone/gemfeed/2022-11-24-i-tried-emacs-but-i-switched-back-to-neovim.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-11-24-i-tried-emacs-but-i-switched-back-to-neovim.gmi</id>
        <updated>2022-11-24T11:17:15+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Art by      \ \_!  / __!</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>I tried (Doom) Emacs, but I switched back to (Neo)Vim</h1><br />
<br />
<span class='quote'>Published at 2022-11-24T11:17:15+02:00; Updated at 2022-11-26</span><br />
<br />
<pre>
             _/  \    _(\(o
             /     \  /  _  ^^^o
            /   !   \/  ! &#39;!!!v&#39;
           !  !  \ _&#39; ( \____
           ! . \ _!\   \===^\)
Art by      \ \_!  / __!
 Gunnar Z.   \!   /    \    &lt;--- Emacs is a giant dragon
       (\_      _/   _\ )
        \ ^^--^^ __-^ /(__ 
         ^^----^^    "^--v&#39;
</pre>
<br />
<span>As a long-lasting user of Vim (and NeoVim), I always wondered what GNU Emacs is really about, so I decided to try it. I didn&#39;t try vanilla GNU Emacs, but Doom Emacs. I chose Doom Emacs as it is a neat distribution of Emacs with Evil mode enabled by default. Evil mode allows Vi(m) key bindings (so to speak, it&#39;s emulating Vim within Emacs), and I am pretty sure I won&#39;t be ready to give up all the muscle memory I have built over more than a decade.</span><br />
<br />
<a class='textlink' href='https://www.gnu.org/software/emacs/'>GNU Emacs</a><br />
<a class='textlink' href='https://github.com/doomemacs/'>Doom Emacs</a><br />
<br />
<span>I used Doom Emacs for around two months. Still, ultimately I decided to switch back to NeoVim as my primary editor and IDE and Vim (usually pre-installed on Linux-based systems) and Nvi (usually pre-installed on *BSD systems) as my "always available editor" for quick edits. (It is worth mentioning that I don&#39;t have a high opinion on whether Vim or NeoVim is the better editor, I prefer NeoVim as it comes with better defaults out of the box, but there is no real blocker to use Vim instead).</span><br />
<br />
<a class='textlink' href='https://www.vim.org'>Vim</a><br />
<a class='textlink' href='https://neovim.io'>NeoVim</a><br />
<br />
<span>So why did I switch back to the Vi-family?</span><br />
<br />
<h2 style='display: inline'>Emacs is a giant dragon</h2><br />
<br />
<span>Emacs feels like a giant dragon as it is much more than an editor or an integrated development environment. Emacs is a whole platform on its own. There&#39;s an E-Mail client, an IRC client, or even games you can run within Emacs. And you can also change Emacs within Emacs using its own Lisp dialect, Emacs Lisp (Emacs is programmed in Emacs Lisp). Therefore, Emacs is also its own programming language. You can change every aspect of Emacs within Emacs itself. People jokingly state Emacs is an operating system and that you should directly use it as the <span class='inlinecode'>init 1</span> process (if you don&#39;t know what the <span class='inlinecode'>init 1</span> process is: Under UNIX and similar operating systems, it&#39;s the very first userland processed launched. That&#39;s usually <span class='inlinecode'>systemd</span> on Linux-based systems, <span class='inlinecode'>launchd</span> on macOS, or any other init script or init system used by the OS)!</span><br />
<br />
<span>In many aspects, Emacs is like shooting at everything with a bazooka! However, I prefer it simple. I only wanted Emacs to be a good editor (which it is, too), but there&#39;s too much other stuff in Emacs that I don&#39;t need to care about! Vim and NeoVim do one thing excellent: Being great text editors and, when loaded with plugins, decent IDEs, too. </span><br />
<br />
<h2 style='display: inline'>Magit love</h2><br />
<br />
<span>I almost fell in love with Magit, an integrated Git client for Emacs. But I think the best way to interact with Git is to use the <span class='inlinecode'>git</span> command line directly. I don&#39;t worry about typing out all the commands, as the most commonly used commands are in my shell history. Other useful Git programs I use frequently are <span class='inlinecode'>bit</span> and <span class='inlinecode'>tig</span>. Also, get a mechanical keyboard that makes hammering whole commands into the terminal even more enjoyable.</span><br />
<br />
<a class='textlink' href='https://magit.vc/'>Magit</a><br />
<a class='textlink' href='https://github.com/jonas/tig'>Tig</a><br />
<br />
<span>Magit is pretty neat for basic Git operations, but I found myself searching the internet for the correct sub-commands to do the things I wanted to do in Git. Mainly, the way how branches are managed is confusing. Often, I fell back to the command line to fix up the mess I produced with Magit (e.g. accidentally pushing to the wrong remote branch, so I found myself fixing things manually on the terminal with the <span class='inlinecode'>git</span> command with forced pushes....). Magit is hotkey driven, and common commands are quickly explorable through built-in hotkey menus. Still, I found it challenging to navigate to more advanced Git sub-commands that way which was much easier accomplished by using the <span class='inlinecode'>git</span> command directly.</span><br />
<br />
<h2 style='display: inline'>Graphical UI</h2><br />
<br />
<span>If there is one thing I envy about Emacs is that it&#39;s a graphical program, whereas the Vi-family of editors are purely terminal-based. I see the benefits of being a graphical program as this enables the use of multiple fonts simultaneously to embed pictures and graphs (that would be neat as a Markdown preview, for example). There&#39;s also GVim (Vim with GTK UI), but that&#39;s more of an afterthought.</span><br />
<br />
<span>There are now graphical front-end clients for NeoVim, but I still need to dig into them. Let me know your experience if you have one. Luckily, I don&#39;t rely on something graphical in my text editor, but it would improve how the editor looks and feels. UTF8 can already do a lot in the terminal, and terminal emulators also allow you to use TrueType fonts. Still, you will always be limited to one TTF font for the whole terminal, and it isn&#39;t possible to have, for example, a different font for headings, paragraphs, etc... you get the idea. TTF+UTF8 can&#39;t beat authentic graphics. </span><br />
<br />
<h2 style='display: inline'>Scripting it</h2><br />
<br />
<span>It is possible to customize every aspect of Emacs through Emacs Lisp. I have done some Elk Scheme programming in the past (a dialect of Lisp), but that was a long time ago, and I am not willing to dive here again to customize my environment. I would instead take the pragmatic approach and script what I need in VimScript (a terrible language, but it gets the job done!). I watched Damian Conway&#39;s VimScript course on O&#39;Reilly Safari Books Online, which I greatly recommend. Yes, VimScript feels clunky, funky and weird and is far less elegant than Lisp, but it gets its job done - in most cases! (That reminds me that the Vim team has announced a new major version of VimScript with improvements and language changes made - I haven&#39;t gotten to it yet - but I assume that VimScript will always stay VimScript).</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Emacs_Lisp'>Emacs Lisp</a><br />
<a class='textlink' href='http://sam.zoy.org/elk/'>Elk Scheme</a><br />
<a class='textlink' href='http://vimscript.org/'>VimScript</a><br />
<a class='textlink' href='https://www.oreilly.com/library/view/scripting-vim/9781491996287/'>Scripting Vim by Damian Conway</a><br />
<br />
<span>NeoVim is also programmable with Lua, which seems to be a step up and Vim comes with a Perl plugin API (which was removed from NeoVim, but that is a different story - why would someone remove the most potent mature text manipulation programming language from one of the most powerful text editors?).</span><br />
<br />
<a class='textlink' href='https://neovim.io/doc/user/lua.html'>NeoVim Lua API</a><br />
<br />
<span>One example is my workflow of how I compose my blog articles (e.g. this one you are currently reading): I am writing everything in NeoVim, but I also want to have every paragraph checked against Grammarly (as English is not my first language). So I write a whole paragraph, then I select the entire paragraph via visual selection with <span class='inlinecode'>SHIFT+v</span>, and then I press <span class='inlinecode'>,y</span> to yank the paragraph to the systems clipboard, then I paste the paragraph to Grammarly&#39;s browser window with <span class='inlinecode'>CTRL+v</span>, let Grammarly suggest the improvements, and then I copy the result back with <span class='inlinecode'>CTRL+c</span> to the system clipboard and in NeoVim I type <span class='inlinecode'>,i</span> to insert the result back overriding the old paragraph (which is still selected in visual mode) with the new content. That all sounds a bit complicated, but it&#39;s surprisingly natural and efficient.</span><br />
<br />
<span>To come back to the example, for the clipboard integration, I use this small VimScript snippet, and I didn&#39;t have to dig into any Lisp or Perl for this:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><i><font color="#9A1900">" Clipboard</font></i>
vnoremap ,<b><font color="#0000FF">y</font></b> !pbcopy<font color="#FF6600">&lt;CR&gt;</font>ugv
vnoremap ,<b><font color="#0000FF">i</font></b> !pbpaste<font color="#FF6600">&lt;CR&gt;</font>
nmap ,<b><font color="#0000FF">i</font></b> !wpbpaste<font color="#FF6600">&lt;CR&gt;</font>
</pre>
<br />
<span>That&#39;s only a very few lines and does precisely what I want. It&#39;s quick and dirty but get&#39;s the job done! If VimScript becomes too cumbersome, I can use Lua for NeoVim scripting.</span><br />
<br />
<h2 style='display: inline'>The famous Emacs Org mode</h2><br />
<br />
<span>Org-mode is an Emacs mode for keeping notes, authoring documents, computational notebooks, literate programming, maintaining to-do lists, planning projects, and more — in a fast and effective plain-text system. There&#39;s even a dedicated website for it:</span><br />
<br />
<a class='textlink' href='https://orgmode.org/'>https://orgmode.org/</a><br />
<br />
<span>In short, Org-mode is an "interactive markup language" that helps you organize everything mentioned above. I rarely touched the surface during my two-month experiment with Emacs, and I am impressed by it, so I see the benefits of having that. But it&#39;s not for me.</span><br />
<br />
<span>I use "Dead Tree Mode" to organize my work and notes. Dead tree? Yeah, I use an actual pen and a real paper journal (Leuchtturm or a Moleskine and a set of coloured <span class='inlinecode'>0.5</span> Muji Pens are excellent choices). That&#39;s far more immersive and flexible than a computer program can ever be. Yes, some automation and interaction with the computer (like calendar scheduling etc.) are missing. Still, an actual paper journal forces you to stay simple and focus on the actual work rather than tinkering with your computer program. (But I could not resist, and I wrote a VimScript which parses a table of contents page in Markdown format of my scanned paper journals, and NeoVim allows me to select a topic so that the corresponding PDF scan on the right journal page gets opened in an external PDF viewer (the PDF viewer is <span class='inlinecode'>zathura</span>, it uses Vi-keybindings, of course) :-). (See the appendix of this blog post for that script).</span><br />
<br />
<a class='textlink' href='https://pwmt.org/projects/zathura/'>Zathura</a><br />
<br />
<span>On the road, I also write some of my notes in Markdown format to NextCloud Notes, which is editable from my phone and via NeoVim on my computers. Markdown is much less powerful than Org-mode, but I prefer it the simple way. There&#39;s a neat terminal application, <span class='inlinecode'>ranger</span>, which I use to browse my NextCloud Notes when they are synced to a local folder on my machine. <span class='inlinecode'>ranger</span> is a file manager inspired by Vim and therefore makes use of Vim keybindings and it feels just natural to me. </span><br />
<br />
<a class='textlink' href='https://github.com/ranger/ranger'>Ranger - A Vim inspired file manager</a><br />
<span>Did I mention that I also use my <span class='inlinecode'>zsh</span> (my default shell) and my <span class='inlinecode'>tmux</span> (terminal multiplexer) in Vi-mode?</span><br />
<br />
<a class='textlink' href='https://zsh.sourceforge.io/'>Z shell</a><br />
<a class='textlink' href='https://github.com/tmux/tmux'>tmux terminal multiplexer</a><br />
<br />
<h2 style='display: inline'>Seeking simplicity</h2><br />
<br />
<span>I am not ready to dive deep into the whole world of Emacs. I prefer small and simple tools as opposed to complex tools. Emacs comes with many features out of the box, whereas in Vim/NeoVim, you would need to install many plugins to replicate some of the behaviour. Yes, I need to invest time managing all the Vim/NeoVim plugins I use, but I feel more in control compared to Doom Emacs, where a framework around vanilla Emacs manages all the plugins. I could use vanilla Emacs and manage all my plugins the vanilla way, but for me, it&#39;s not worth the effort to learn and dive into that as all that I want to do I can already do with Vim/NeoVim.</span><br />
<br />
<span>I am not saying that Vim/NeoVim are simple programs, but they are much simpler than Emacs with much smaller footprints; furthermore, they appear to be more straightforward as I am used to them. I only need Vim/NeoVim to be an editor, an IDE (through some plugins), and nothing more.</span><br />
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>I understand the Emacs users now. Emacs is an incredibly powerful platform for almost everything, not just text editing. With Emacs, you can do nearly everything (Writing, editing, programming, calendar scheduling and note taking, Jira integration, playing games, listening to music, reading/writing emails, browsing the web, using as a calculator, generating HTML pages, configuring interactive menus, jumping around between every feature and every file within one single session, chat on IRC, surf the Gopherspace, ... the options are endless....). If you want to have one piece of software which rules it all and you are happy to invest a large part of your time in your platform: Pick Emacs, and over time Emacs will become "your" Emacs, customized to your own needs and change the way it works, which makes the Emacs users stick even more to it.</span><br />
<br />
<span>Vim/NeoVim also comes with a very high degree of customization options, but to a lesser extreme than Emacs (but still, a much higher degree than most other editors out there). If you want the best text editor in the world, which can also be tweaked to be a decent IDE, you are only looking for: Pick Vim or NeoVim! You would also need to invest a lot of time in learning, tweaking and customizing Vim/NeoVim, but that&#39;s a little more straightforward, and the result is much more lightweight once you get used to the "Vi way of doing things" you never would want to change back. I haven&#39;t tried the Emacs vanilla keystrokes, but they are terrible (that&#39;s probably one of the reasons why Doom Emacs uses Vim keybindings by default).</span><br />
<br />
<span class='quote'>Update: One reader recommended to have a look at NvChad. NvChad is a NeoVim config written in Lua aiming to provide a base configuration with very beautiful UI and blazing fast startuptime (around <span class='inlinecode'>0.02</span> secs ~ <span class='inlinecode'>0.07</span> secs). They tweak UI plugins such as telescope, nvim-tree, bufferline etc well to provide an aesthetic UI experience. That sounds interesting!</span><br />
<br />
<a class='textlink' href='https://github.com/NvChad/NvChad'>https://github.com/NvChad/NvChad</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
<br />
<h1 style='display: inline'>Appendix</h1><br />
<br />
<span>This is the VimScript I mentioned earlier, which parses a table of contents index of my scanned paper journals and opens the corresponding PDF at the right page in <span class='inlinecode'>zathura</span>:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">function</font></b>! ReadJournalPageNumber<font color="#990000">()</font>
    <b><font color="#0000FF">let</font></b> page <font color="#990000">=</font> <b><font color="#000080">expand</font></b><font color="#990000">(</font><font color="#FF0000">"&lt;cword&gt;"</font><font color="#990000">)</font>
    <b><font color="#0000FF">if</font></b> page <font color="#990000">!~</font># <font color="#FF0000">'^</font><font color="#CC33CC">\d\+</font><font color="#FF0000">


</font>
        <b><font color="#0000FF">for</font></b><font color="#FF6600"> str in </font><b><font color="#0000FF">split</font></b><font color="#990000">(</font><b><font color="#000080">getline</font></b><font color="#990000">(</font><font color="#FF0000">"."</font><font color="#990000">)</font>, <font color="#FF0000">"[ ,]"</font><font color="#990000">)</font>
            <b><font color="#0000FF">if</font></b> str <font color="#990000">=~</font># <font color="#FF0000">'^</font><font color="#CC33CC">\d\+</font><font color="#FF0000">


</font>
                <b><font color="#0000FF">let</font></b> page <font color="#990000">=</font> str
                <b><font color="#0000FF">break</font></b>
            <b><font color="#0000FF">end</font></b>
        <b><font color="#0000FF">endfor</font></b>
    <b><font color="#0000FF">endif</font></b>
    <b><font color="#0000FF">return</font></b> page
<b><font color="#0000FF">endfunction</font></b>

<b><font color="#0000FF">function</font></b>! ReadJournalMeta<font color="#990000">()</font>
<font color="#FF6600">   </font> normal! mj

<font color="#FF6600">   </font> <font color="#993399">1</font>/MetaFilePath:/
<font color="#FF6600">   </font> normal! 3w
    <b><font color="#0000FF">let</font></b> <font color="#000080">s:metaFilePath</font> <font color="#990000">=</font> <b><font color="#000080">expand</font></b><font color="#990000">(</font><font color="#FF0000">"&lt;cWORD&gt;"</font><font color="#990000">)</font>
    <b><font color="#0000FF">echom</font></b> <font color="#000080">s:metaFilePath</font>

<font color="#FF6600">   </font> <font color="#993399">1</font>/MetaOffset:/
<font color="#FF6600">   </font> normal! 3w
    <b><font color="#0000FF">let</font></b> <font color="#000080">s:metaOffset</font> <font color="#990000">=</font> <b><font color="#000080">expand</font></b><font color="#990000">(</font><font color="#FF0000">"&lt;cword&gt;"</font><font color="#990000">)</font>
    <b><font color="#0000FF">echom</font></b> <font color="#000080">s:metaOffset</font>

<font color="#FF6600">   </font> <font color="#993399">1</font>/MetaPageAtOffset:/
<font color="#FF6600">   </font> normal! 3w
    <b><font color="#0000FF">let</font></b> <font color="#000080">s:metaPageAtOffset</font> <font color="#990000">=</font> <b><font color="#000080">expand</font></b><font color="#990000">(</font><font color="#FF0000">"&lt;cword&gt;"</font><font color="#990000">)</font>
    <b><font color="#0000FF">echom</font></b> <font color="#000080">s:metaPageAtOffset</font>

<font color="#FF6600">   </font> <font color="#993399">1</font>/MetaPagesPerScan:/
<font color="#FF6600">   </font> normal! 3w
    <b><font color="#0000FF">let</font></b> <font color="#000080">s:metaPagesPerScan</font> <font color="#990000">=</font> <b><font color="#000080">expand</font></b><font color="#990000">(</font><font color="#FF0000">"&lt;cword&gt;"</font><font color="#990000">)</font>
    <b><font color="#0000FF">echom</font></b> <font color="#000080">s:metaPagesPerScan</font>

<font color="#FF6600">   </font> normal! `<b><font color="#0000FF">j</font></b>
<b><font color="#0000FF">endfunction</font></b>

<b><font color="#0000FF">function</font></b>! GetPdfPage<font color="#990000">(</font>page<font color="#990000">)</font>
    <b><font color="#0000FF">return</font></b> <font color="#000080">s:metaOffset</font> <font color="#990000">+</font> <font color="#990000">(</font><font color="#000080">a:page</font> <font color="#990000">-</font> <font color="#000080">s:metaPageAtOffset</font><font color="#990000">)</font> / <font color="#000080">s:metaPagesPerScan</font>
<b><font color="#0000FF">endfunction</font></b>

<b><font color="#0000FF">function</font></b>! OpenJournalPage<font color="#990000">()</font>
    <b><font color="#0000FF">let</font></b> page <font color="#990000">=</font> ReadJournalPageNumber<font color="#990000">()</font>
    <b><font color="#0000FF">if</font></b> page <font color="#990000">!~</font># <font color="#FF0000">'^</font><font color="#CC33CC">\d\+</font><font color="#FF0000">


</font>
        <b><font color="#0000FF">echoerr</font></b> <font color="#FF0000">"Could not identify Journal page number"</font>
    <b><font color="#0000FF">end</font></b>
    <b><font color="#0000FF">call</font></b> ReadJournalMeta<font color="#990000">()</font>
    <b><font color="#0000FF">let</font></b> pdfPage <font color="#990000">=</font> GetPdfPage<font color="#990000">(</font>page<font color="#990000">)</font>
    <b><font color="#0000FF">echon</font></b> <font color="#FF0000">"Location is "</font> <font color="#990000">.</font> <font color="#000080">s:metaFilePath</font> <font color="#990000">.</font> <font color="#FF0000">":"</font> <font color="#990000">.</font> pdfPage
    <b><font color="#0000FF">call</font></b> <b><font color="#000080">system</font></b><font color="#990000">(</font><font color="#FF0000">"zathura --mode fullscreen -P "</font> <font color="#990000">.</font> pdfPage <font color="#990000">.</font> <font color="#FF0000">" "</font> <font color="#990000">.</font> <font color="#000080">s:metaFilePath</font><font color="#990000">)</font>
<i><font color="#9A1900">    " call system("evince -p " . pdfPage . " " . s:metaFilePath)</font></i>
<b><font color="#0000FF">endfunction</font></b>

nmap ,<b><font color="#0000FF">j</font></b> :<b><font color="#0000FF">call</font></b> OpenJournalPage<font color="#990000">()</font><font color="#FF6600">&lt;CR&gt;</font>
</pre>
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Installing DTail on OpenBSD</title>
        <link href="gemini://foo.zone/gemfeed/2022-10-30-installing-dtail-on-openbsd.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-10-30-installing-dtail-on-openbsd.gmi</id>
        <updated>2022-10-30T11:03:19+02:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This will be a quick blog post, as I am busy with my personal life now. I have relocated to a different country and am still busy arranging things. So bear with me :-)</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Installing DTail on OpenBSD</h1><br />
<br />
<span class='quote'>Published at 2022-10-30T11:03:19+02:00</span><br />
<br />
<pre>
       ,_---~~~~~----._
 _,,_,*^____      _____``*g*\"*,
/ __/ /&#39;     ^.  /      \ ^@q   f
 @f   |       |  |       |  0 _/
\`/   \~__((@/ __ \__((@/    \
 |           _l__l_           I    &lt;--- The Go Gopher
 }          [______]           I
 ]            | | |            |
 ]             ~ ~             |
 |                            |
  |                           |
  |                           |       A       ;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~|~~~,--,-/ \---,-/|~~,~~~~~~~~~~~~~~~~~~~~~~~~~~~
                           _|\,&#39;. /|      /|   `/|-.
                       \`.&#39;    /|      ,            `;.
                      ,&#39;\   A     A         A   A _ /| `.;
                    ,/  _              A       _  / _   /|  ;
                   /\  / \   ,  ,           A  /    /     `/|
                  /_| | _ \         ,     ,             ,/  \
                 // | |/ `.\  ,-      ,       ,   ,/ ,/      \/
                 / @| |@  / /&#39;   \  \      ,              &gt;  /|    ,--.
                |\_/   \_/ /      |  |           ,  ,/        \  ./&#39; __:..
                |  __ __  |       |  | .--.  ,         &gt;  &gt;   |-&#39;   /     `
              ,/| /  &#39;  \ |       |  |     \      ,           |    /
             /  |&lt;--.__,-&gt;|       |  | .    `.        &gt;  &gt;    /   (
            /_,&#39; \\  ^  /  \     /  /   `.    &gt;--            /^\   |
                  \\___/    \   /  /      \__&#39;     \   \   \/   \  |
                   `.   |/          ,  ,                  /`\    \  )
                     \  &#39;  |/    ,       V    \          /        `-\
 OpenBSD Puffy ---&gt;   `|/  &#39;  V      V           \    \.&#39;            \_
                       &#39;`-.       V       V        \./&#39;\
                           `|/-.      \ /   \ /,---`\         kat
                            /   `._____V_____V&#39;
                                       &#39;     &#39;
</pre>
<br />
<span>This will be a quick blog post, as I am busy with my personal life now. I have relocated to a different country and am still busy arranging things. So bear with me :-)</span><br />
<br />
<span> In this post, I want to give a quick overview (or how-to) about installing DTail on OpenBSD, as the official documentation only covers Red Hat and Fedora Linux! And this blog post will also be used as my reference!</span><br />
<br />
<a class='textlink' href='https://dtail.dev'>https://dtail.dev</a><br />
<br />
<span>I am using Rexify for my OpenBSD automation. Check out the following article covering my Rex setup in a little bit more detail:</span><br />
<br />
<a class='textlink' href='./2022-07-30-lets-encrypt-with-openbsd-and-rex.html'>Let&#39;s Encrypt with OpenBSD and Rex</a><br />
<br />
<span>I will also mention some relevant <span class='inlinecode'>Rexfile</span> snippets in this post!</span><br />
<br />
<h2 style='display: inline'>Compile it</h2><br />
<br />
<span>First of all, DTail needs to be downloaded and compiled. For that, <span class='inlinecode'>git</span>, <span class='inlinecode'>go</span>, and <span class='inlinecode'>gmake</span> are required:</span><br />
<br />
<pre>
$ doas pkg_add git go gmake
</pre>
<br />
<span>I am happy that the Go Programming Language is readily available in the OpenBSD packaging system. Once the dependencies got installed, clone DTail and compile it:</span><br />
<br />
<pre>
$ mkdir git
$ cd git
$ git clone https://github.com/mimecast/dtail
$ cd dtail
$ gmake 
</pre>
<br />
<span>You can verify the version by running the following command:</span><br />
<br />
<pre>
$ ./dtail --version
 DTail  4.1.0  Protocol 4.1  Have a lot of fun!
$ file dtail
 dtail: ELF 64-bit LSB executable, x86-64, version 1
</pre>
<br />
<span>Now, there isn&#39;t any need anymore to keep <span class='inlinecode'>git</span>, <span class='inlinecode'>go</span> and <span class='inlinecode'>gmake</span>, so they can be deinstalled now:</span><br />
<br />
<pre>
$ doas pkg_delete git go gmake
</pre>
<br />
<span>One day I shall create an official OpenBSD port for DTail.</span><br />
<br />
<h2 style='display: inline'>Install it</h2><br />
<br />
<span>Installing the binaries is now just a matter of copying them to <span class='inlinecode'>/usr/local/bin</span> as follows:</span><br />
<br />
<pre>
$ for bin in dserver dcat dgrep dmap dtail dtailhealth; do
  doas cp -p $bin /usr/local/bin/$bin
  doas chown root:wheel /usr/local/bin/$bin
done
</pre>
<br />
<span>Also, we will be creating the <span class='inlinecode'>_dserver</span> service user:</span><br />
<br />
<pre>
$ doas adduser -class nologin -group _dserver -batch _dserver
$ doas usermod -d /var/run/dserver/ _dserver
</pre>
<br />
<span>The OpenBSD init script is created from scratch (not part of the official DTail project). Run the following to install the bespoke script:</span><br />
<br />
<pre>
$ cat &lt;&lt;&#39;END&#39; | doas tee /etc/rc.d/dserver
#!/bin/ksh

daemon="/usr/local/bin/dserver"
daemon_flags="-cfg /etc/dserver/dtail.json"
daemon_user="_dserver"

. /etc/rc.d/rc.subr

rc_reload=NO

rc_pre() {
    install -d -o _dserver /var/log/dserver
    install -d -o _dserver /var/run/dserver/cache
}

rc_cmd $1 &amp;
END
$ doas chmod 755 /etc/rc.d/dserver
</pre>
<br />
<h3 style='display: inline'>Rexification</h3><br />
<br />
<span>This is the task for setting it up via Rex. Note the <span class='inlinecode'>. . . .</span>, that&#39;s a placeholder which we will fill up more and more during this blog post:</span><br />
<br />
<pre>
desc &#39;Setup DTail&#39;;
task &#39;dtail&#39;, group =&gt; &#39;frontends&#39;,
   sub {
      my $restart = FALSE;

      file &#39;/etc/rc.d/dserver&#39;:
        content =&gt; template(&#39;./etc/rc.d/dserver.tpl&#39;),
        owner =&gt; &#39;root&#39;,
        group =&gt; &#39;wheel&#39;,
        mode =&gt; &#39;755&#39;,
        on_change =&gt; sub { $restart = TRUE };

        .
        .
        .
        .

      service &#39;dserver&#39; =&gt; &#39;restart&#39; if $restart;
      service &#39;dserver&#39;, ensure =&gt; &#39;started&#39;;
   };
</pre>
<br />
<h2 style='display: inline'>Configure it</h2><br />
<br />
<span>Now, DTail is fully installed but still needs to be configured. Grab the default config file from GitHub ...</span><br />
<br />
<pre>
$ doas mkdir /etc/dserver
$ curl https://raw.githubusercontent.com/mimecast/dtail/master/samples/dtail.json.sample |
    doas tee /etc/dserver/dtail.json
</pre>
<br />
<span>... and then edit it and adjust <span class='inlinecode'>LogDir</span> in the <span class='inlinecode'>Common</span> section to <span class='inlinecode'>/var/log/dserver</span>. The result will look like this:</span><br />
<br />
<pre>
  "Common": {
    "LogDir": "/var/log/dserver",
    "Logger": "Fout",
    "LogRotation": "Daily",
    "CacheDir": "cache",
    "SSHPort": 2222,
    "LogLevel": "Info"
  }
</pre>
<br />
<h3 style='display: inline'>Rexification</h3><br />
<br />
<span>That&#39;s as simple as adding the following to the Rex task:</span><br />
<br />
<pre>
file &#39;/etc/dserver&#39;,
  ensure =&gt; &#39;directory&#39;;

file &#39;/etc/dserver/dtail.json&#39;,
  content =&gt; template(&#39;./etc/dserver/dtail.json.tpl&#39;),
  owner =&gt; &#39;root&#39;,
  group =&gt; &#39;wheel&#39;,
  mode =&gt; &#39;755&#39;,
  on_change =&gt; sub { $restart = TRUE };
</pre>
<br />
<h2 style='display: inline'>Update the key cache for it</h2><br />
<br />
<span>DTail relies on SSH for secure authentication and communication. However, the system user <span class='inlinecode'>_dserver</span> has no permission to read the SSH public keys from the user&#39;s home directories, so the DTail server also checks for available public keys in an alternative path <span class='inlinecode'>/var/run/dserver/cache</span>. </span><br />
<br />
<span>The following script, populating the DTail server key cache, can be run periodically via <span class='inlinecode'>CRON</span>:</span><br />
<br />
<pre>
$ cat &lt;&lt;&#39;END&#39; | doas tee /usr/local/bin/dserver-update-key-cache.sh
#!/bin/ksh

CACHEDIR=/var/run/dserver/cache
DSERVER_USER=_dserver
DSERVER_GROUP=_dserver

echo &#39;Updating SSH key cache&#39;

ls /home/ | while read remoteuser; do
    keysfile=/home/$remoteuser/.ssh/authorized_keys

    if [ -f $keysfile ]; then
        cachefile=$CACHEDIR/$remoteuser.authorized_keys
        echo "Caching $keysfile -&gt; $cachefile"

        cp $keysfile $cachefile
        chown $DSERVER_USER:$DSERVER_GROUP $cachefile
        chmod 600 $cachefile
    fi
done

# Cleanup obsolete public SSH keys
find $CACHEDIR -name \*.authorized_keys -type f |
while read cachefile; do
    remoteuser=$(basename $cachefile | cut -d. -f1)
    keysfile=/home/$remoteuser/.ssh/authorized_keys

    if [ ! -f $keysfile ]; then
        echo &#39;Deleting obsolete cache file $cachefile&#39;
        rm $cachefile
    fi
done

echo &#39;All set...&#39;
END
$ doas chmod 500 /usr/local/bin/dserver-update-key-cache.sh
</pre>
<br />
<span>Note that the script above is a slight variation of the official DTail script. The official DTail one is a <span class='inlinecode'>bash</span> script, but on OpenBSD, there&#39;s <span class='inlinecode'>ksh</span>. I run it once daily by adding it to the <span class='inlinecode'>daily.local</span>:</span><br />
<br />
<pre>
$ echo /usr/local/bin/dserver-update-key-cache.sh | doas tee -a /etc/daily.local
/usr/local/bin/dserver-update-key-cache.sh
</pre>
<br />
<h3 style='display: inline'>Rexification</h3><br />
<br />
<span>That&#39;s done by adding ...</span><br />
<br />
<pre>
file &#39;/usr/local/bin/dserver-update-key-cache.sh&#39;,
  content =&gt; template(&#39;./scripts/dserver-update-key-cache.sh.tpl&#39;),
  owner =&gt; &#39;root&#39;,
  group =&gt; &#39;wheel&#39;,
  mode =&gt; &#39;500&#39;;

append_if_no_such_line &#39;/etc/daily.local&#39;, &#39;/usr/local/bin/dserver-update-key-cache.sh&#39;;
</pre>
<br />
<span>... to the Rex task!</span><br />
<br />
<h2 style='display: inline'>Start it</h2><br />
<br />
<span>Now, it&#39;s time to enable and start the DTail server:</span><br />
<br />
<pre>
$ sudo rcctl enable dserver
$ sudo rcctl start dserver
$ tail -f /var/log/dserver/*.log
INFO|1022-090634|Starting scheduled job runner after 2s
INFO|1022-090634|Starting continuous job runner after 2s
INFO|1022-090644|24204|stats.go:53|2|11|7|||MAPREDUCE:STATS|currentConnections=0|lifetimeConnections=0
INFO|1022-090654|24204|stats.go:53|2|11|7|||MAPREDUCE:STATS|currentConnections=0|lifetimeConnections=0
INFO|1022-090719|Starting server|DTail 4.1.0 Protocol 4.1 Have a lot of fun!
INFO|1022-090719|Generating private server RSA host key
INFO|1022-090719|Starting server
INFO|1022-090719|Binding server|0.0.0.0:2222
INFO|1022-090719|Starting scheduled job runner after 2s
INFO|1022-090719|Starting continuous job runner after 2s
INFO|1022-090729|86050|stats.go:53|2|11|7|||MAPREDUCE:STATS|currentConnections=0|lifetimeConnections=0
INFO|1022-090739|86050|stats.go:53|2|11|7|||MAPREDUCE:STATS|currentConnections=0|lifetimeConnect
.
.
.
Ctr+C
</pre>
<br />
<span>As we don&#39;t want to wait until tomorrow, let&#39;s populate the key cache manually:</span><br />
<br />
<pre>
$ doas /usr/local/bin/dserver-update-key-cache.sh
Updating SSH key cache
Caching /home/_dserver/.ssh/authorized_keys -&gt; /var/cache/dserver/_dserver.authorized_keys
Caching /home/admin/.ssh/authorized_keys -&gt; /var/cache/dserver/admin.authorized_keys
Caching /home/failunderd/.ssh/authorized_keys -&gt; /var/cache/dserver/failunderd.authorized_keys
Caching /home/git/.ssh/authorized_keys -&gt; /var/cache/dserver/git.authorized_keys
Caching /home/paul/.ssh/authorized_keys -&gt; /var/cache/dserver/paul.authorized_keys
Caching /home/rex/.ssh/authorized_keys -&gt; /var/cache/dserver/rex.authorized_keys
All set...
</pre>
<br />
<h2 style='display: inline'>Use it</h2><br />
<br />
<span>The DTail server is now ready to serve connections. You can use any DTail commands, such as <span class='inlinecode'>dtail</span>, <span class='inlinecode'>dgrep</span>, <span class='inlinecode'>dmap</span>, <span class='inlinecode'>dcat</span>, <span class='inlinecode'>dtailhealth</span>, to do so. Checkout out all the usage examples on the official DTail page.</span><br />
<br />
<span>I have installed DTail server this way on my personal OpenBSD frontends <span class='inlinecode'>blowfish</span>, and <span class='inlinecode'>fishfinger</span>, and the following command connects as user <span class='inlinecode'>rex</span> to both machines and greps the file <span class='inlinecode'>/etc/fstab</span> for the string <span class='inlinecode'>local</span>:</span><br />
<br />
<pre>
❯ ./dgrep -user rex -servers blowfish.buetow.org,fishfinger.buetow.org --regex local /etc/fstab
CLIENT|earth|WARN|Encountered unknown host|{blowfish.buetow.org:2222 0xc0000a00f0 0xc0000a61e0 [blowfish.buetow.org]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9ZnF/LAk14SgqCzk38yENVTNfqibcluMTuKx1u53cKSp2xwHWzy0Ni5smFPpJDIQQljQEJl14ZdXvhhjp1kKHxJ79ubqRtIXBlC0PhlnP8Kd+mVLLHYpH9VO4rnaSfHE1kBjWkI7U6lLc6ks4flgAgGTS5Bb7pLAjwdWg794GWcnRh6kSUEQd3SftANqQLgCunDcP2Vc4KR9R78zBmEzXH/OPzl/ANgNA6wWO2OoKKy2VrjwVAab6FW15h3Lr6rYIw3KztpG+UMmEj5ReexIjXi/jUptdnUFWspvAmzIl6kwzzF8ExVyT9D75JRuHvmxXKKjyJRxqb8UnSh2JD4JN [23.88.35.144]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9ZnF/LAk14SgqCzk38yENVTNfqibcluMTuKx1u53cKSp2xwHWzy0Ni5smFPpJDIQQljQEJl14ZdXvhhjp1kKHxJ79ubqRtIXBlC0PhlnP8Kd+mVLLHYpH9VO4rnaSfHE1kBjWkI7U6lLc6ks4flgAgGTS5Bb7pLAjwdWg794GWcnRh6kSUEQd3SftANqQLgCunDcP2Vc4KR9R78zBmEzXH/OPzl/ANgNA6wWO2OoKKy2VrjwVAab6FW15h3Lr6rYIw3KztpG+UMmEj5ReexIjXi/jUptdnUFWspvAmzIl6kwzzF8ExVyT9D75JRuHvmxXKKjyJRxqb8UnSh2JD4JN 0xc0000a2180}
CLIENT|earth|WARN|Encountered unknown host|{fishfinger.buetow.org:2222 0xc0000a0150 0xc000460110 [fishfinger.buetow.org]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNiikdL7+tWSN0rCaw1tOd9aQgeUFgb830V9ejkyJ5h93PKLCWZSMMCtiabc1aUeUZR//rZjcPHFLuLq/YC+Y3naYtGd6j8qVrcfG8jy3gCbs4tV9SZ9qd5E24mtYqYdGlee6JN6kEWhJxFkEwPfNlG+YAr3KC8lvEAE2JdWvaZavqsqMvHZtAX3b25WCBf2HGkyLZ+d9cnimRUOt+/+353BQFCEct/2mhMVlkr4I23CY6Tsufx0vtxx25nbFdZias6wmhxaE9p3LiWXygPWGU5iZ4RSQSImQz4zyOc9rnJeP1rwGk0OWDJhdKNXuf0kIPdzMfwxv2otgY32/DJj6L [46.23.94.99]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNiikdL7+tWSN0rCaw1tOd9aQgeUFgb830V9ejkyJ5h93PKLCWZSMMCtiabc1aUeUZR//rZjcPHFLuLq/YC+Y3naYtGd6j8qVrcfG8jy3gCbs4tV9SZ9qd5E24mtYqYdGlee6JN6kEWhJxFkEwPfNlG+YAr3KC8lvEAE2JdWvaZavqsqMvHZtAX3b25WCBf2HGkyLZ+d9cnimRUOt+/+353BQFCEct/2mhMVlkr4I23CY6Tsufx0vtxx25nbFdZias6wmhxaE9p3LiWXygPWGU5iZ4RSQSImQz4zyOc9rnJeP1rwGk0OWDJhdKNXuf0kIPdzMfwxv2otgY32/DJj6L 0xc0000a2240}
Encountered 2 unknown hosts: &#39;blowfish.buetow.org:2222,fishfinger.buetow.org:2222&#39;
Do you want to trust these hosts?? (y=yes,a=all,n=no,d=details): a
CLIENT|earth|INFO|STATS:STATS|cgocalls=11|cpu=8|connected=2|servers=2|connected%=100|new=2|throttle=0|goroutines=19
CLIENT|earth|INFO|Added hosts to known hosts file|/home/paul/.ssh/known_hosts
REMOTE|blowfish|100|7|fstab|31bfd9d9a6788844.h /usr/local ffs rw,wxallowed,nodev 1 2
REMOTE|fishfinger|100|7|fstab|093f510ec5c0f512.h /usr/local ffs rw,wxallowed,nodev 1 2
</pre>
<br />
<span>Running it the second time, and given that you trusted the keys the first time, it won&#39;t prompt you for the host keys anymore:</span><br />
<br />
<pre>
❯ ./dgrep -user rex -servers blowfish.buetow.org,fishfinger.buetow.org --regex local /etc/fstab
REMOTE|blowfish|100|7|fstab|31bfd9d9a6788844.h /usr/local ffs rw,wxallowed,nodev 1 2
REMOTE|fishfinger|100|7|fstab|093f510ec5c0f512.h /usr/local ffs rw,wxallowed,nodev 1 2
</pre>
<br />
<h2 style='display: inline'>Conclusions</h2><br />
<br />
<span>It&#39;s a bit of manual work, but it&#39;s ok on this small scale! I shall invest time in creating an official OpenBSD port, though. That would render most of the manual steps obsolete, as outlined in this post!</span><br />
<br />
<span>Check out the following for more information:</span><br />
<br />
<a class='textlink' href='https://dtail.dev'>https://dtail.dev</a><br />
<a class='textlink' href='https://github.com/mimecast/dtail'>https://github.com/mimecast/dtail</a><br />
<a class='textlink' href='https://www.rexify.org'>https://www.rexify.org</a><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-10-30-installing-dtail-on-openbsd.html'>2022-10-30 Installing DTail on OpenBSD (You are currently reading this)</a><br />
<a class='textlink' href='./2022-03-06-the-release-of-dtail-4.0.0.html'>2022-03-06 The release of DTail 4.0.0</a><br />
<a class='textlink' href='./2021-04-22-dtail-the-distributed-log-tail-program.html'>2021-04-22 DTail - The distributed log tail program</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>After a bad night's sleep</title>
        <link href="gemini://foo.zone/gemfeed/2022-09-30-after-a-bad-nights-sleep.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-09-30-after-a-bad-nights-sleep.gmi</id>
        <updated>2022-09-30T09:53:23+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Everyone has it once in a while: A bad night's sleep. Here I attempt to list valuable tips on how to deal with it.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>After a bad night&#39;s sleep</h1><br />
<br />
<span class='quote'>Published at 2022-09-30T09:53:23+03:00; Updated at 2022-10-12</span><br />
<br />
<pre>
               z
                z
                 Z
       .--.  Z Z
      / _(c\   .-.     __
     | / /  &#39;-;   \&#39;-&#39;`  `\______
     \_\/&#39;/ __/ )  /  )   |      \--,
     | \`""`__-/ .&#39;--/   /--------\  \
      \\`  ///-\/   /   /---;-.    &#39;-&#39;
jgs                (________\  \
                             &#39;-&#39;
</pre>
<br />
<span>Everyone has it once in a while: A bad night&#39;s sleep. Here I attempt to list valuable tips on how to deal with it.</span><br />
<br />
<h2 style='display: inline'>Don&#39;t take the day off.</h2><br />
<br />
<span>Don&#39;t take a day off after not sleeping enough the previous night. That would be wasting the holiday allowance. It wouldn&#39;t be possible to enjoy my free time anyway, so why not just work? There&#39;s still a way for an IT Engineer to be productive (sometimes even more) with half or less of the concentration power available!</span><br />
<br />
<h2 style='display: inline'>Start work early</h2><br />
<br />
<span>Probably I am already awake early and am unable to fall asleep again. My strategy here is to "attack" the day: Start work early and finish early. The early bird will also encounter fewer distractions from colleagues.</span><br />
<br />
<h2 style='display: inline'>Sweat the small stuff</h2><br />
<br />
<span>There&#39;s never a shortage of small items to hook off my list. Most of these items don&#39;t require my full concentration power, and I will be happy to get them off my list so that the next day, after a good night&#39;s sleep, I can immerse myself again in focused, deep work with all concentration powers at hand.</span><br />
<br />
<span>Examples of "small work items" are:</span><br />
<br />
<ul>
<li>Tidying up the workspace.</li>
<li>Installing pending computer software updates.</li>
<li>Going through the work backlog: Create new tickets, close obsolete ones, and roughly pre-plan upcoming work.</li>
<li>Finishing off the easy tickets from the current sprint.</li>
<li>Going through any tedious paperwork.</li>
<li>Catch up with the journal and mark off all trivial action items.</li>
</ul><br />
<h2 style='display: inline'>Enter the flow state</h2><br />
<br />
<span>I find it easy to enter the "flow state" after a bad night&#39;s sleep. All I need to do is to put on some ambient music (preferably instrumental chill house) and start to work on a not-too-difficult ticket.</span><br />
<br />
<span>Usually, the "flow state" is associated with deep-focused work, but deep-focused work isn&#39;t easily possible under sleep deprivation. It&#39;s still possible to be in the flow by working on more manageable tasks and leaving the difficult ones for the next day.</span><br />
<br />
<h2 style='display: inline'>Reschedule meetings</h2><br />
<br />
<span>I find engaging in discussions and demanding meetings challenging after a lousy night&#39;s sleep. I still attend the sessions I am invited to as "only" a participant, but I prefer to reschedule all meetings I am the primary driver of.</span><br />
<br />
<span>This, unfortunately, also includes interviews. Interviews require full concentration power. So for interviews, I would find a colleague to step in for me or ask to reschedule the interview altogether. Everything else wouldn&#39;t make it justice and would waste everyone&#39;s time!</span><br />
<br />
<h2 style='display: inline'>Invent</h2><br />
<br />
<span>The mind works differently under sleep deprivation: It&#39;s easier to invent new stuff as it&#39;s easier to have a look at things from different perspectives. Until an hour ago, I didn&#39;t know yet what I would be blogging about for this month, and then I just started writing this, and it took me only half an hour to write the first draft of this blog post!</span><br />
<br />
<h2 style='display: inline'>Fast</h2><br />
<br />
<span>I don&#39;t eat breakfast, and I don&#39;t eat lunch on these days. I only have dinner. Not eating means my mind doesn&#39;t get foggy, and I keep up the work momentum. This is called intermittent fasting, which not only generally helps to keep the weight under control and boosts the concentration power. Furthermore, intermittent fasting is healthy. You should include it in your routine, even after a good night&#39;s sleep.</span><br />
<br />
<h2 style='display: inline'>Stretch</h2><br />
<br />
<span>I won&#39;t have enough energy for strenuous physical exercise on those days, but a 30 to a 60-minute stretching session can make the day. Stretching will even hurt less under sleep deprivation! The stretching could also be substituted with a light Yoga session.</span><br />
<br />
<h2 style='display: inline'>Walk</h2><br />
<br />
<span>Walking is healthy, and the time can be used to listen to interesting podcasts. The available concentration power might not be enough for more sophisticated audio literature. I will have enough energy for one or two daily walks (~10k steps for the day in total). Sometimes, I listen to music during walks. I also try to catch the bright sunlight.</span><br />
<br />
<h2 style='display: inline'>Red Bull</h2><br />
<br />
<span>I don&#39;t think that Red Bull is a healthy drink. But once in a while, a can in the early afternoon brings wonders, and productivity will skyrocket. Other than Red Bull, drink a lot of water throughout the day. Don&#39;t forget to drink the sugar-free version; otherwise, your intermittent fast will be broken.</span><br />
<br />
<h2 style='display: inline'>Power nap</h2><br />
<br />
<span>I don&#39;t know how to "enforce" a nap, but sometimes I manage to power nap, and it helps wonders. A 30-minute nap sometimes brings me back to normal. If you don&#39;t tend to fast as you are too hungry, it helps to try to nap approximately 30 minutes after eating something.</span><br />
<br />
<h2 style='display: inline'>Don&#39;t take anything personally.</h2><br />
<br />
<span>It&#39;s much more challenging to keep the mind "under control" in this state. Every annoyance can potentially upset, which could reflect on the work colleagues. It is wise to attempt to go with a positive attitude into the day, always smile and be polite to the family and colleagues at work. Don&#39;t let anything drop out to the people next; they don&#39;t deserve it as they didn&#39;t do anything wrong! Also, remember, it can&#39;t be controlled at all. It&#39;s time to let go of the annoyances for the day.</span><br />
<br />
<h2 style='display: inline'>Meditate</h2><br />
<br />
<span>To keep the good vibe, it helps to meditate for 10 minutes. Meditation must nothing be fancy. It can be just lying on the sofa and observing your thoughts as they come and go. Don&#39;t judge your thoughts, as that could put you in a negative mood. It&#39;s not necessary to sit in an uncomfortable Yoga pose, and it is not required to chant "Ohhmmmmm".</span><br />
<br />
<h2 style='display: inline'>Write things down</h2><br />
<br />
<span>Sometimes something requiring more concentration power demands time. This is where it helps to write a note in a journal and return to it another day. This doesn&#39;t mean slacking off but managing the rarely available concentration power for the day. I might repeat myself: Today, sweat all the small stuff. Tomorrow, do the deep-focused work on that crucial project again.</span><br />
<br />
<span>It&#39;s easier to forget things on those days, so everything should be written down so that it can be worked off later. Things written down will not be overlooked!</span><br />
<br />
<h2 style='display: inline'>Social media</h2><br />
<br />
<span>I wouldn&#39;t say I like checking social media, as it can consume a lot of time and can become addictive. But once in a while, I want to catch up with my "networks". After a bad night&#39;s sleep, it&#39;s the perfect time to check your social media. Once done, you don&#39;t have to do it anymore for the next couple of days!</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Gemtexter 1.1.0 - Let's Gemtext again</title>
        <link href="gemini://foo.zone/gemfeed/2022-08-27-gemtexter-1.1.0-lets-gemtext-again.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-08-27-gemtexter-1.1.0-lets-gemtext-again.gmi</id>
        <updated>2022-08-27T18:25:57+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I proudly announce that I've released Gemtexter version `1.1.0`. What is Gemtexter? It's my minimalist static site generator for Gemini Gemtext, HTML and Markdown written in GNU Bash.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Gemtexter 1.1.0 - Let&#39;s Gemtext again</h1><br />
<br />
<span class='quote'>Published at 2022-08-27T18:25:57+01:00</span><br />
<br />
<pre>
-=[ typewriter ]=-  1/98

       .-------.
      _|~~ ~~  |_
    =(_|_______|_)=
      |:::::::::|
      |:::::::[]|
      |o=======.|
 jgs  `"""""""""`
</pre>
<br />
<span>I proudly announce that I&#39;ve released Gemtexter version <span class='inlinecode'>1.1.0</span>. What is Gemtexter? It&#39;s my minimalist static site generator for Gemini Gemtext, HTML and Markdown written in GNU Bash.</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/gemtexter'>https://codeberg.org/snonux/gemtexter</a><br />
<br />
<span>It has been around a year since I released the first version <span class='inlinecode'>1.0.0</span>. Although, there aren&#39;t any groundbreaking changes, there have been a couple of smaller commits and adjustments. I was quite surprised that I received a bunch of feedback and requests about Gemtexter so it means that I am not the only person in the universe actually using it.</span><br />
<br />
<h2 style='display: inline'>What&#39;s new?</h2><br />
<br />
<h3 style='display: inline'>Automatic check for GNU version requirements</h3><br />
<br />
<span>Gemtexter relies on the GNU versions of the tools <span class='inlinecode'>grep</span>, <span class='inlinecode'>sed</span> and <span class='inlinecode'>date</span> and it also requires the Bash shell in version 5 at least. That&#39;s now done in the <span class='inlinecode'>check_dependencies()</span> function:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#000000">check_dependencies ()</font></b> {
    <i><font color="#9A1900"># At least, Bash 5 is required</font></i>
    <b><font color="#0000FF">local</font></b> -i <font color="#009900">required_version</font><font color="#990000">=</font><font color="#993399">5</font>
    <font color="#009900">IFS</font><font color="#990000">=.</font> <b><font color="#0000FF">read</font></b> -ra version <font color="#990000">&lt;&lt;&lt;</font> <font color="#FF0000">"$BASH_VERSION"</font>
    <b><font color="#0000FF">if</font></b> <font color="#990000">[</font> <font color="#FF0000">"${version[0]}"</font> -lt <font color="#009900">$required_version</font> <font color="#990000">];</font> <b><font color="#0000FF">then</font></b>
        log ERROR <font color="#FF0000">"ERROR, </font><font color="#CC33CC">\"</font><font color="#FF0000">bash</font><font color="#CC33CC">\"</font><font color="#FF0000"> must be at least at major version $required_version!"</font>
        <b><font color="#0000FF">exit</font></b> <font color="#993399">2</font>
    <b><font color="#0000FF">fi</font></b>

    <i><font color="#9A1900"># These must be the GNU versions of the commands</font></i>
    <b><font color="#0000FF">for</font></b> tool <b><font color="#0000FF">in</font></b> <font color="#009900">$DATE</font> <font color="#009900">$SED</font> <font color="#009900">$GREP</font><font color="#990000">;</font> <b><font color="#0000FF">do</font></b>
        <b><font color="#0000FF">if</font></b> <font color="#990000">!</font> <font color="#009900">$tool</font> --version <font color="#990000">|</font> grep -q GNU<font color="#990000">;</font> <b><font color="#0000FF">then</font></b>
            log ERROR <font color="#FF0000">"ERROR, </font><font color="#CC33CC">\"</font><font color="#FF0000">$tool</font><font color="#CC33CC">\"</font><font color="#FF0000"> command is not the GNU version, please install!"</font>
            <b><font color="#0000FF">exit</font></b> <font color="#993399">2</font>
        <b><font color="#0000FF">fi</font></b>
    <b><font color="#0000FF">done</font></b>
}
</pre>
<br />
<span>Especially macOS users didn&#39;t read the <span class='inlinecode'>README</span> carefully enough to install GNU Grep, GNU Sed and GNU Date before using Gemtexter.</span><br />
<br />
<h3 style='display: inline'>Backticks now produce <span class='inlinecode'>inline code blocks</span> in the HTML output</h3><br />
<br />
<span>The Gemtext format doesn&#39;t support inline code blocks, but Gemtexter now produces <span class='inlinecode'>inline code blocks</span> (means, small code fragments can be placed in the middle of a paragraph) in the HTML output when the code block is enclosed with Backticks. There were no adjustments required for the Markdown output format, because Markdown supports it already out of the box.</span><br />
<br />
<h3 style='display: inline'>Cache for Atom feed generation</h3><br />
<br />
<span>The Bash is not the most performant language. Gemtexter already takes a couple of seconds only to generate the Atom feed for around two hand full of articles on my slightly underpowered Surface Go 2 Linux tablet. Therefore, I introduced a cache, so that subsequent Atom feed generation runs finish much quicker. The cache uses a checksum of the Gemtext <span class='inlinecode'>.gmi</span> file to decide whether anything of the content has changed or not.</span><br />
<br />
<h3 style='display: inline'>Input filter support</h3><br />
<br />
<span>Once your capsule reaches a certain size, it can become annoying to re-generate everything if you only want to preview the HTML or Markdown output of one single content file. The following will add a filter to only generate the files matching a regular expression:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#990000">.</font>/gemtexter --generate <font color="#FF0000">'.*hello.*'</font>
</pre>
<br />
<h3 style='display: inline'>Revamped <span class='inlinecode'>git</span> support</h3><br />
<br />
<span>The Git support has been completely rewritten. It&#39;s now more reliable and faster too. Have a look at the <span class='inlinecode'>README</span> for more information.</span><br />
<br />
<h3 style='display: inline'>Addition of <span class='inlinecode'>htmlextras</span> and web font support</h3><br />
<br />
<span>The <span class='inlinecode'>htmlextras</span> folder now contains all extra files required for the HTML output format such as cascading style sheet (CSS) files and web fonts.</span><br />
<br />
<h3 style='display: inline'>Sub-section support</h3><br />
<br />
<span>It&#39;s now possible to define sub-sections within a Gemtexter capsule. For the HTML output, each sub-section can use its own CSS and web font definitions. E.g.:</span><br />
<br />
<a class='textlink' href='https://foo.zone'>The foo.zone main site</a><br />
<a class='textlink' href='https://foo.zone/notes'>The notes sub-section (with different fonts)</a><br />
<br />
<h3 style='display: inline'>More</h3><br />
<br />
<span>Additionally, there were a couple of bug fixes, refactorings and overall improvements in the documentation made. </span><br />
<br />
<span>Overall I think it&#39;s a pretty solid <span class='inlinecode'>1.1.0</span> release without anything groundbreaking (therefore no major version jump). But I am happy about it.</span><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2023-03-25-gemtexter-2.0.0-lets-gemtext-again-2.html'>2023-03-25 Gemtexter 2.0.0 - Let&#39;s Gemtext again²</a><br />
<a class='textlink' href='./2022-08-27-gemtexter-1.1.0-lets-gemtext-again.html'>2022-08-27 Gemtexter 1.1.0 - Let&#39;s Gemtext again (You are currently reading this)</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all</a><br />
<a class='textlink' href='./2021-04-24-welcome-to-the-geminispace.html'>2021-04-24 Welcome to the Geminispace</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Let's Encrypt with OpenBSD and Rex</title>
        <link href="gemini://foo.zone/gemfeed/2022-07-30-lets-encrypt-with-openbsd-and-rex.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-07-30-lets-encrypt-with-openbsd-and-rex.gmi</id>
        <updated>2022-07-30T12:14:31+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I was amazed at how easy it is to automatically generate and update Let's Encrypt certificates with OpenBSD.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Let&#39;s Encrypt with OpenBSD and Rex</h1><br />
<br />
<span class='quote'>Published at 2022-07-30T12:14:31+01:00</span><br />
<br />
<pre>
                                               /    _    \
  The Hebern Machine                            \ ." ". /
                                  ___            /     \
                              ..""   ""..       |   O   |
                             /           \      |       |
                            /             \     |       |
                          ---------------------------------
                        _/  o     (O)     o   _            |
                      _/                    ." ".          |
                    I/    _________________/     \         |
                  _/I   ."                        |        |
          =====  /  I  /                         /         |
     =====  | | |   \ |       _________________."          |
=====  | |  | | |   /  \     /  _|_|__|_|_          __     |
  | |  | |  | | |   \   "._."  /  o    o  \       ."  ".   |
  |  --|  --|  -|   /          \         _/      /      \  |
   \____\____\__|   \  ______   |       /       |        | |
               --------      ---       /        |        | |
              ( )        (O)          /          \      /  |
               -----------------------            ".__."   |
               _|__________________________________________|_
              /                                              \
             /________________________________________________\
                                 ASCII Art by John Savard
</pre>
<br />
<span>I was amazed at how easy it is to automatically generate and update Let&#39;s Encrypt certificates with OpenBSD.</span><br />
<br />
<h2 style='display: inline'>What&#39;s Let&#39;s Encrypt?</h2><br />
<br />
<span class='quote'>Let&#39;s Encrypt is a non-profit certificate authority run by Internet Security Research Group that provides X.509 certificates for Transport Layer Security (TLS) encryption at no charge. It is the world&#39;s largest certificate authority, used by more than 265 million websites, with the goal of all websites being secure and using HTTPS.</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Let&#39;s_Encrypt'>Source: Wikipedia</a><br />
<br />
<span>In short, it gives away TLS certificates for your website - for free! The catch is, that the certificates are only valid for three months. So it is better to automate certificate generation and renewals.</span><br />
<br />
<h2 style='display: inline'>Meet <span class='inlinecode'>acme-client</span></h2><br />
<br />
<span><span class='inlinecode'>acme-client</span> is the default Automatic Certifcate Management Environment (ACME) client on OpenBSD and part of the OpenBSD base system. </span><br />
<br />
<span>When invoked, the client first checks whether certificates actually require to be generated.</span><br />
<br />
<ul>
<li>It first checks whether a certificate already exists; if not, it will attempt to generate a new one.</li>
<li>If the certificate already exists but expires within the next 30 days, it will renew it.</li>
<li>Otherwise, <span class='inlinecode'>acme-client</span> won&#39;t do anything.</li>
</ul><br />
<span>Oversimplified, the following steps are undertaken by <span class='inlinecode'>acme-client</span> for generating a new certificate:</span><br />
<br />
<ul>
<li>Reading its config file <span class='inlinecode'>/etc/acme-client.conf</span> for a list of hosts (and their alternative names) to generate certificates. So it means you can also have certificates for arbitrary subdomains!</li>
<li>Automatic generation of the private certificate part (the certificate key) and the certificate signing request (CSR) to <span class='inlinecode'>/etc/ssl/...</span>.</li>
<li>Requesting Let&#39;s Encrypt to sign the certificate. This also includes providing a set of temporary files requested by Let&#39;s Encrypt in the next step for verification.</li>
<li>Let&#39;s Encrypt then will contact the hostname for the certificate through a particular URL (e.g. <span class='inlinecode'>http://foo.zone/.well-known/acme-challenge/...</span>) to verify that the requester is the valid owner of the host.</li>
<li>Let&#39;s Encrypt generates a certificate, which then is downloaded to <span class='inlinecode'>/etc/ssl/...</span>.</li>
</ul><br />
<h2 style='display: inline'>Configuration</h2><br />
<br />
<span>There is some (but easy) configuration required to make that all work on OpenBSD.</span><br />
<br />
<h3 style='display: inline'>acme-client.conf</h3><br />
<br />
<span>This is how my <span class='inlinecode'>/etc/acme-client.conf</span> looks like (I copied a template from <span class='inlinecode'>/etc/examples/acme-client.conf</span> to <span class='inlinecode'>/etc/acme-client.conf</span> and added my domains to the bottom:</span><br />
<br />
<pre>
#
# $OpenBSD: acme-client.conf,v 1.4 2020/09/17 09:13:06 florian Exp $
#
authority letsencrypt {
    api url "https://acme-v02.api.letsencrypt.org/directory"
    account key "/etc/acme/letsencrypt-privkey.pem"
}

authority letsencrypt-staging {
    api url "https://acme-staging-v02.api.letsencrypt.org/directory"
    account key "/etc/acme/letsencrypt-staging-privkey.pem"
}

authority buypass {
    api url "https://api.buypass.com/acme/directory"
    account key "/etc/acme/buypass-privkey.pem"
    contact "mailto:me@example.com"
}

authority buypass-test {
    api url "https://api.test4.buypass.no/acme/directory"
    account key "/etc/acme/buypass-test-privkey.pem"
    contact "mailto:me@example.com"
}

domain buetow.org {
    alternative names { www.buetow.org paul.buetow.org }
    domain key "/etc/ssl/private/buetow.org.key"
    domain full chain certificate "/etc/ssl/buetow.org.fullchain.pem"
    sign with letsencrypt
}

domain dtail.dev {
    alternative names { www.dtail.dev }
    domain key "/etc/ssl/private/dtail.dev.key"
    domain full chain certificate "/etc/ssl/dtail.dev.fullchain.pem"
    sign with letsencrypt
}

domain foo.zone {
    alternative names { www.foo.zone }
    domain key "/etc/ssl/private/foo.zone.key"
    domain full chain certificate "/etc/ssl/foo.zone.fullchain.pem"
    sign with letsencrypt
}

domain irregular.ninja {
    alternative names { www.irregular.ninja }
    domain key "/etc/ssl/private/irregular.ninja.key"
    domain full chain certificate "/etc/ssl/irregular.ninja.fullchain.pem"
    sign with letsencrypt
}

domain snonux.land {
    alternative names { www.snonux.land }
    domain key "/etc/ssl/private/snonux.land.key"
    domain full chain certificate "/etc/ssl/snonux.land.fullchain.pem"
    sign with letsencrypt
}
</pre>
<br />
<h3 style='display: inline'>httpd.conf</h3><br />
<br />
<span>For ACME to work, you will need to configure the HTTP daemon so that the "special" ACME requests from Let&#39;s Encrypt are served correctly. I am using the standard OpenBSD <span class='inlinecode'>httpd</span> here. These are the snippets I use for the <span class='inlinecode'>foo.zone</span> host in <span class='inlinecode'>/etc/httpd.conf</span> (of course, you need a similar setup for all other hosts as well):</span><br />
<br />
<pre>
server "foo.zone" {
  listen on * port 80
  location "/.well-known/acme-challenge/*" {
    root "/acme"
    request strip 2
  }
  location * {
    block return 302 "https://$HTTP_HOST$REQUEST_URI"
  }
}

server "foo.zone" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/foo.zone.fullchain.pem"
    key "/etc/ssl/private/foo.zone.key"
  }
  location * {
    root "/htdocs/gemtexter/foo.zone"
    directory auto index
  }
}
</pre>
<br />
<span>As you see, plain HTTP only serves the ACME challenge path. Otherwise, it redirects the requests to TLS. The TLS section then attempts to use the Let&#39;s Encrypt certificates.</span><br />
<br />
<span>It is worth noticing that <span class='inlinecode'>httpd</span> will start without the certificates being present. This will cause a certificate error when you try to reach the HTTPS endpoint, but it helps to bootstrap Let&#39;s Encrypt. As you saw in the config snippet above, Let&#39;s Encrypt only requests the plain HTTP endpoint for the verification process, so HTTPS doesn&#39;t need to be operational yet at this stage. But once the certificates are generated, you will have to reload or restart <span class='inlinecode'>httpd</span> to use any new certificate.</span><br />
<br />
<h3 style='display: inline'>CRON job</h3><br />
<br />
<span>You could now run <span class='inlinecode'>doas acme-client foo.zone</span> to generate the certificate or to renew it. Or you could automate it with CRON.</span><br />
<br />
<span>I have created a script <span class='inlinecode'>/usr/local/bin/acme.sh</span> for that for all of my domains:</span><br />
<br />
<pre>
#!/bin/sh

function handle_cert {
    host=$1
    # Create symlink, so that relayd also can read it.
    crt_path=/etc/ssl/$host
    if [ -e $crt_path.crt ]; then
        rm $crt_path.crt
    fi
    ln -s $crt_path.fullchain.pem $crt_path.crt
    # Requesting and renewing certificate.
    /usr/sbin/acme-client -v $host
}

has_update=no
handle_cert www.buetow.org
if [ $? -eq 0 ]; then
    has_update=yes
fi
handle_cert www.paul.buetow.org
if [ $? -eq 0 ]; then
    has_update=yes
fi
handle_cert www.tmp.buetow.org
if [ $? -eq 0 ]; then
    has_update=yes
fi
handle_cert www.dtail.dev
if [ $? -eq 0 ]; then
    has_update=yes
fi
handle_cert www.foo.zone
if [ $? -eq 0 ]; then
    has_update=yes
fi
handle_cert www.irregular.ninja
if [ $? -eq 0 ]; then
    has_update=yes
fi
handle_cert www.snonux.land
if [ $? -eq 0 ]; then
    has_update=yes
fi

# Pick up the new certs.
if [ $has_update = yes ]; then
    /usr/sbin/rcctl reload httpd
    /usr/sbin/rcctl reload relayd
    /usr/sbin/rcctl restart smtpd
fi
</pre>
<br />
<span>And added the following line to <span class='inlinecode'>/etc/daily.local</span> to run the script once daily so that certificates will be renewed fully automatically:</span><br />
<br />
<pre>
/usr/local/bin/acme.sh
</pre>
<br />
<span>I am receiving a daily output via E-Mail like this now:</span><br />
<br />
<pre>
Running daily.local:
acme-client: /etc/ssl/buetow.org.fullchain.pem: certificate valid: 80 days left
acme-client: /etc/ssl/paul.buetow.org.fullchain.pem: certificate valid: 80 days left
acme-client: /etc/ssl/tmp.buetow.org.fullchain.pem: certificate valid: 80 days left
acme-client: /etc/ssl/dtail.dev.fullchain.pem: certificate valid: 80 days left
acme-client: /etc/ssl/foo.zone.fullchain.pem: certificate valid: 80 days left
acme-client: /etc/ssl/irregular.ninja.fullchain.pem: certificate valid: 80 days left
acme-client: /etc/ssl/snonux.land.fullchain.pem: certificate valid: 79 days left
</pre>
<br />
<h2 style='display: inline'>relayd.conf and smtpd.conf</h2><br />
<br />
<span>Besides <span class='inlinecode'>httpd</span>, <span class='inlinecode'>relayd</span> (mainly for Gemini) and <span class='inlinecode'>smtpd</span> (for mail, of course) also use TLS certificates. And as you can see in <span class='inlinecode'>acme.sh</span>, the services are reloaded or restarted (<span class='inlinecode'>smtpd</span> doesn&#39;t support reload) whenever a certificate is generated or updated.</span><br />
<br />
<h2 style='display: inline'>Rexification</h2><br />
<br />
<span>I didn&#39;t write all these configuration files by hand. As a matter of fact, everything is automated with the Rex configuration management system.</span><br />
<br />
<a class='textlink' href='https://www.rexify.org'>https://www.rexify.org</a><br />
<br />
<span>At the top of the <span class='inlinecode'>Rexfile</span> I define all my hosts:</span><br />
<br />
<pre>
our @acme_hosts = qw/buetow.org paul.buetow.org tmp.buetow.org dtail.dev foo.zone irregular.ninja snonux.land/;
</pre>
<br />
<h3 style='display: inline'>General ACME client configuration</h3><br />
<br />
<span>ACME will be installed into the frontend group of hosts. Here, blowfish is the primary, and twofish is the secondary OpenBSD box.</span><br />
<br />
<pre>
group frontends =&gt; &#39;blowfish.buetow.org&#39;, &#39;twofish.buetow.org&#39;;
</pre>
<br />
<span>This is my Rex task for the general ACME configuration:</span><br />
<br />
<pre>
desc &#39;Configure ACME client&#39;;
task &#39;acme&#39;, group =&gt; &#39;frontends&#39;,
  sub {
    file &#39;/etc/acme-client.conf&#39;,
      content =&gt; template(&#39;./etc/acme-client.conf.tpl&#39;,
        acme_hosts =&gt; \@acme_hosts,
        is_primary =&gt; $is_primary),
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;;

    file &#39;/usr/local/bin/acme.sh&#39;,
      content =&gt; template(&#39;./scripts/acme.sh.tpl&#39;,
        acme_hosts =&gt; \@acme_hosts,
        is_primary =&gt; $is_primary),
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;744&#39;;

    file &#39;/etc/daily.local&#39;,
      ensure =&gt; &#39;present&#39;,
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;;

    append_if_no_such_line &#39;/etc/daily.local&#39;, &#39;/usr/local/bin/acme.sh&#39;;
  };
</pre>
<br />
<span>And there is also a Rex task just to run the ACME script remotely:</span><br />
<br />
<pre>
desc &#39;Invoke ACME client&#39;;
task &#39;acme_invoke&#39;, group =&gt; &#39;frontends&#39;,
  sub {
    say run &#39;/usr/local/bin/acme.sh&#39;;
  };

</pre>
<br />
<span>Furthermore, this snippet (also at the top of the Rexfile) helps to determine whether the current server is the primary server (all hosts will be without the <span class='inlinecode'>www.</span> prefix) or the secondary server (all hosts will be with the <span class='inlinecode'>www.</span> prefix):</span><br />
<br />
<pre>
# Bootstrapping the FQDN based on the server IP as the hostname and domain
# facts aren&#39;t set yet due to the myname file in the first place.
our $fqdns = sub {
  my $ipv4 = shift;
  return &#39;blowfish.buetow.org&#39; if $ipv4 eq &#39;23.88.35.144&#39;;
  return &#39;twofish.buetow.org&#39; if $ipv4 eq &#39;108.160.134.135&#39;;
  Rex::Logger::info("Unable to determine hostname for $ipv4", &#39;error&#39;);
  return &#39;HOSTNAME-UNKNOWN.buetow.org&#39;;
};

# To determine whether the server is the primary or the secondary.
our $is_primary = sub {
  my $ipv4 = shift;
  $fqdns-&gt;($ipv4) eq &#39;blowfish.buetow.org&#39;;
};
</pre>
<br />
<span>The following is the <span class='inlinecode'>acme-client.conf.tpl</span> Rex template file used for the automation. You see that the <span class='inlinecode'>www.</span> prefix isn&#39;t sent for the primary server. E.g. <span class='inlinecode'>foo.zone</span> will be served by the primary server (in my case, a server located in Germany) and <span class='inlinecode'>www.foo.zone</span> by the secondary server (in my case, a server located in Japan):</span><br />
<br />
<pre>
#
# $OpenBSD: acme-client.conf,v 1.4 2020/09/17 09:13:06 florian Exp $
#
authority letsencrypt {
	api url "https://acme-v02.api.letsencrypt.org/directory"
	account key "/etc/acme/letsencrypt-privkey.pem"
}

authority letsencrypt-staging {
	api url "https://acme-staging-v02.api.letsencrypt.org/directory"
	account key "/etc/acme/letsencrypt-staging-privkey.pem"
}

authority buypass {
	api url "https://api.buypass.com/acme/directory"
	account key "/etc/acme/buypass-privkey.pem"
	contact "mailto:me@example.com"
}

authority buypass-test {
	api url "https://api.test4.buypass.no/acme/directory"
	account key "/etc/acme/buypass-test-privkey.pem"
	contact "mailto:me@example.com"
}

&lt;%
  our $primary = $is_primary-&gt;($vio0_ip);
  our $prefix = $primary ? &#39;&#39; : &#39;www.&#39;;
%&gt;

&lt;% for my $host (@$acme_hosts) { %&gt;
domain &lt;%= $prefix.$host %&gt; {
	domain key "/etc/ssl/private/&lt;%= $prefix.$host %&gt;.key"
	domain full chain certificate "/etc/ssl/&lt;%= $prefix.$host %&gt;.fullchain.pem"
	sign with letsencrypt
}
&lt;% } %&gt;

</pre>
<br />
<span>And this is the <span class='inlinecode'>acme.sh.tpl</span>:</span><br />
<br />
<pre>
#!/bin/sh

&lt;%
  our $primary = $is_primary-&gt;($vio0_ip);
  our $prefix = $primary ? &#39;&#39; : &#39;www.&#39;;
-%&gt;

function handle_cert {
    host=$1
    # Create symlink, so that relayd also can read it.
    crt_path=/etc/ssl/$host
    if [ -e $crt_path.crt ]; then
        rm $crt_path.crt
    fi
    ln -s $crt_path.fullchain.pem $crt_path.crt
    # Requesting and renewing certificate.
    /usr/sbin/acme-client -v $host
}

has_update=no
&lt;% for my $host (@$acme_hosts) { -%&gt;
handle_cert &lt;%= $prefix.$host %&gt;
if [ $? -eq 0 ]; then
    has_update=yes
fi
&lt;% } -%&gt;

# Pick up the new certs.
if [ $has_update = yes ]; then
    /usr/sbin/rcctl reload httpd
    /usr/sbin/rcctl reload relayd
    /usr/sbin/rcctl restart smtpd
fi
</pre>
<br />
<h3 style='display: inline'>Service rexification </h3><br />
<br />
<span>These are the Rex tasks setting up <span class='inlinecode'>httpd</span>, <span class='inlinecode'>relayd</span> and <span class='inlinecode'>smtpd</span> services:</span><br />
<br />
<pre>
desc &#39;Setup httpd&#39;;
task &#39;httpd&#39;, group =&gt; &#39;frontends&#39;,
  sub {
    append_if_no_such_line &#39;/etc/rc.conf.local&#39;, &#39;httpd_flags=&#39;;

    file &#39;/etc/httpd.conf&#39;,
      content =&gt; template(&#39;./etc/httpd.conf.tpl&#39;,
        acme_hosts =&gt; \@acme_hosts,
        is_primary =&gt; $is_primary),
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;,
      on_change =&gt; sub { service &#39;httpd&#39; =&gt; &#39;restart&#39; };

    service &#39;httpd&#39;, ensure =&gt; &#39;started&#39;;
  };

desc &#39;Setup relayd&#39;;
task &#39;relayd&#39;, group =&gt; &#39;frontends&#39;,
  sub {
    append_if_no_such_line &#39;/etc/rc.conf.local&#39;, &#39;relayd_flags=&#39;;

    file &#39;/etc/relayd.conf&#39;,
      content =&gt; template(&#39;./etc/relayd.conf.tpl&#39;,
        ipv6address =&gt; $ipv6address,
        is_primary =&gt; $is_primary),
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;600&#39;,
      on_change =&gt; sub { service &#39;relayd&#39; =&gt; &#39;restart&#39; };

    service &#39;relayd&#39;, ensure =&gt; &#39;started&#39;;
  };

desc &#39;Setup OpenSMTPD&#39;;
task &#39;smtpd&#39;, group =&gt; &#39;frontends&#39;,
  sub {
    Rex::Logger::info(&#39;Dealing with mail aliases&#39;);
    file &#39;/etc/mail/aliases&#39;,
      source =&gt; &#39;./etc/mail/aliases&#39;,
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;,
      on_change =&gt; sub { say run &#39;newaliases&#39; };

    Rex::Logger::info(&#39;Dealing with mail virtual domains&#39;);
    file &#39;/etc/mail/virtualdomains&#39;,
      source =&gt; &#39;./etc/mail/virtualdomains&#39;,
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;,
      on_change =&gt; sub { service &#39;smtpd&#39; =&gt; &#39;restart&#39; };

    Rex::Logger::info(&#39;Dealing with mail virtual users&#39;);
    file &#39;/etc/mail/virtualusers&#39;,
      source =&gt; &#39;./etc/mail/virtualusers&#39;,
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;,
      on_change =&gt; sub { service &#39;smtpd&#39; =&gt; &#39;restart&#39; };

    Rex::Logger::info(&#39;Dealing with smtpd.conf&#39;);
    file &#39;/etc/mail/smtpd.conf&#39;,
      content =&gt; template(&#39;./etc/mail/smtpd.conf.tpl&#39;,
        is_primary =&gt; $is_primary),
      owner =&gt; &#39;root&#39;,
      group =&gt; &#39;wheel&#39;,
      mode =&gt; &#39;644&#39;,
      on_change =&gt; sub { service &#39;smtpd&#39; =&gt; &#39;restart&#39; };

    service &#39;smtpd&#39;, ensure =&gt; &#39;started&#39;;
  };

</pre>
<br />
<span>This is the <span class='inlinecode'>httpd.conf.tpl</span>:</span><br />
<br />
<pre>
&lt;%
  our $primary = $is_primary-&gt;($vio0_ip);
  our $prefix = $primary ? &#39;&#39; : &#39;www.&#39;;
%&gt;

# Plain HTTP for ACME and HTTPS redirect
&lt;% for my $host (@$acme_hosts) { %&gt;
server "&lt;%= $prefix.$host %&gt;" {
  listen on * port 80
  location "/.well-known/acme-challenge/*" {
    root "/acme"
    request strip 2
  }
  location * {
    block return 302 "https://$HTTP_HOST$REQUEST_URI"
  }
}
&lt;% } %&gt;

# Gemtexter hosts
&lt;% for my $host (qw/foo.zone snonux.land/) { %&gt;
server "&lt;%= $prefix.$host %&gt;" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/&lt;%= $prefix.$host %&gt;.fullchain.pem"
    key "/etc/ssl/private/&lt;%= $prefix.$host %&gt;.key"
  }
  location * {
    root "/htdocs/gemtexter/&lt;%= $host %&gt;"
    directory auto index
  }
}
&lt;% } %&gt;

# DTail special host
server "&lt;%= $prefix %&gt;dtail.dev" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/&lt;%= $prefix %&gt;dtail.dev.fullchain.pem"
    key "/etc/ssl/private/&lt;%= $prefix %&gt;dtail.dev.key"
  }
  location * {
    block return 302 "https://github.dtail.dev$REQUEST_URI"
  }
}

# Irregular Ninja special host
server "&lt;%= $prefix %&gt;irregular.ninja" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/&lt;%= $prefix %&gt;irregular.ninja.fullchain.pem"
    key "/etc/ssl/private/&lt;%= $prefix %&gt;irregular.ninja.key"
  }
  location * {
    root "/htdocs/irregular.ninja"
    directory auto index
  }
}

# buetow.org special host.
server "&lt;%= $prefix %&gt;buetow.org" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/&lt;%= $prefix %&gt;buetow.org.fullchain.pem"
    key "/etc/ssl/private/&lt;%= $prefix %&gt;buetow.org.key"
  }
  block return 302 "https://paul.buetow.org"
}

server "&lt;%= $prefix %&gt;paul.buetow.org" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/&lt;%= $prefix %&gt;paul.buetow.org.fullchain.pem"
    key "/etc/ssl/private/&lt;%= $prefix %&gt;paul.buetow.org.key"
  }
  block return 302 "https://foo.zone/contact-information.html"
}

server "&lt;%= $prefix %&gt;tmp.buetow.org" {
  listen on * tls port 443
  tls {
    certificate "/etc/ssl/&lt;%= $prefix %&gt;tmp.buetow.org.fullchain.pem"
    key "/etc/ssl/private/&lt;%= $prefix %&gt;tmp.buetow.org.key"
  }
  root "/htdocs/buetow.org/tmp"
  directory auto index
}
</pre>
<br />
<span>and this the <span class='inlinecode'>relayd.conf.tpl</span>:</span><br />
<br />
<pre>
&lt;%
  our $primary = $is_primary-&gt;($vio0_ip);
  our $prefix = $primary ? &#39;&#39; : &#39;www.&#39;;
%&gt;

log connection

tcp protocol "gemini" {
    tls keypair &lt;%= $prefix %&gt;foo.zone
    tls keypair &lt;%= $prefix %&gt;buetow.org
}

relay "gemini4" {
    listen on &lt;%= $vio0_ip %&gt; port 1965 tls
    protocol "gemini"
    forward to 127.0.0.1 port 11965
}

relay "gemini6" {
    listen on &lt;%= $ipv6address-&gt;($hostname) %&gt; port 1965 tls
    protocol "gemini"
    forward to 127.0.0.1 port 11965
}
</pre>
<br />
<span>And last but not least, this is the <span class='inlinecode'>smtpd.conf.tpl</span>:</span><br />
<br />
<pre>
&lt;%
  our $primary = $is_primary-&gt;($vio0_ip);
  our $prefix = $primary ? &#39;&#39; : &#39;www.&#39;;
%&gt;

pki "buetow_org_tls" cert "/etc/ssl/&lt;%= $prefix %&gt;buetow.org.fullchain.pem"
pki "buetow_org_tls" key "/etc/ssl/private/&lt;%= $prefix %&gt;buetow.org.key"

table aliases file:/etc/mail/aliases
table virtualdomains file:/etc/mail/virtualdomains
table virtualusers file:/etc/mail/virtualusers

listen on socket
listen on all tls pki "buetow_org_tls" hostname "&lt;%= $prefix %&gt;buetow.org"
#listen on all

action localmail mbox alias &lt;aliases&gt;
action receive mbox virtual &lt;virtualusers&gt;
action outbound relay

match from any for domain &lt;virtualdomains&gt; action receive
match from local for local action localmail
match from local for any action outbound
</pre>
<br />
<h2 style='display: inline'>All pieces together</h2><br />
<br />
<span>For the complete <span class='inlinecode'>Rexfile</span> example and all the templates, please look at the Git repository:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/rexfiles'>https://codeberg.org/snonux/rexfiles</a><br />
<br />
<span>Besides ACME, other things, such as DNS servers, are also rexified. The following command will run all the Rex tasks and configure everything on my frontend machines automatically:</span><br />
<br />
<pre>
rex commons
</pre>
<br />
<span>The <span class='inlinecode'>commons</span> is a group of tasks I specified which combines a set of common tasks I always want to execute on all frontend machines. This also includes the ACME tasks mentioned in this article!</span><br />
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>ACME and Let&#39;s Encrypt greatly help reduce recurring manual maintenance work (creating and renewing certificates). Furthermore, all the certificates are free of cost! I love to use OpenBSD and Rex to automate all of this.</span><br />
<br />
<span>OpenBSD suits perfectly here as all the tools are already part of the base installation. But I like underdogs. Rex is not as powerful and popular as other configuration management systems (e.g. Puppet, Chef, SALT or even Ansible). It is more of an underdog, and the community is small.</span><br />
<br />
<span>Why re-inventing the wheel? I love that a <span class='inlinecode'>Rexfile</span> is just a Perl DSL. Also, OpenBSD comes with Perl in the base system. So no new programming language had to be added to my mix for the configuration management system. Also, the <span class='inlinecode'>acme.sh</span> shell script is not a Bash but a standard Bourne shell script, so I didn&#39;t have to install an additional shell as OpenBSD does not come with the Bash pre-installed.</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Sweating the small stuff - Tiny projects of mine</title>
        <link href="gemini://foo.zone/gemfeed/2022-06-15-sweating-the-small-stuff.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-06-15-sweating-the-small-stuff.gmi</id>
        <updated>2022-06-15T08:47:44+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This blog post is a bit different from the others. It consists of multiple but smaller projects worth mentioning. I got inspired by Julia Evan's 'Tiny programs' blog post and the side projects of The Sephist, so I thought I would also write a blog posts listing a couple of small projects of mine:</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Sweating the small stuff - Tiny projects of mine</h1><br />
<br />
<span class='quote'>Published at 2022-06-15T08:47:44+01:00; Updated at 2022-06-18</span><br />
<br />
<pre>
         _
        /_/_      .&#39;&#39;&#39;.
     =O(_)))) ...&#39;     `.
 jgs    \_\              `.    .&#39;&#39;&#39;
                           `..&#39;
</pre>
<br />
<span>This blog post is a bit different from the others. It consists of multiple but smaller projects worth mentioning. I got inspired by Julia Evan&#39;s "Tiny programs" blog post and the side projects of The Sephist, so I thought I would also write a blog posts listing a couple of small projects of mine:</span><br />
<br />
<a class='textlink' href='https://jvns.ca/blog/2022/03/08/tiny-programs/'>Tiny programs</a><br />
<a class='textlink' href='https://thesephist.com/projects/'>The Sephist&#39;s project list</a><br />
<br />
<span>Working on tiny projects is a lot of fun as you don&#39;t need to worry about any standards or code reviews and you decide how and when you work on it. There aren&#39;t restrictions regarding technologies used. You are likely the only person working on these tiny projects and that means that there is no conflict with any other developers. This is complete freedom :-).</span><br />
<br />
<span>But before going through the tiny projects let&#39;s take a paragraph for the <span class='inlinecode'>1y</span> anniversary retrospective.</span><br />
<br />
<h2 style='display: inline'><span class='inlinecode'>1y</span> anniversary</h2><br />
<br />
<span>It has been one year since I started posting regularly (at least once monthly) on this blog again. It has been a lot of fun (and work) doing so for various reasons:</span><br />
<br />
<ul>
<li>I practice English writing (I am not a native speaker). I am far from being a novelist, but this blog helps improves my writing skills. I also tried out tools like Grammarly.com and Languagetool.org and also worked with <span class='inlinecode'>:spell</span> in Vim or the LibreOffice checker. This post was checked with the <span class='inlinecode'>write-better</span> Node application. </li>
<li>I force myself to "finish" some kind of project worth writing about every month. If its not a project, then its still a topic which requires research and deep thinking. Producing 2k words of text can actually be challenging.</li>
<li>It&#39;s fun to rely on KISS (keep it simple &amp; stupid) tools. E.g. use of Gemtexter and not WordPress, use of Vim instead of an office suite or a rich web editor.</li>
</ul><br />
<span>Retrospectively, these have been the most popular blog posts of mine over the last year:</span><br />
<br />
<a class='textlink' href='./2021-09-12-keep-it-simple-and-stupid.html'>Keep it simple and stupid</a><br />
<a class='textlink' href='./2022-04-10-creative-universe.html'>Creative universe</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>Bash Golf series</a><br />
<a class='textlink' href='./2021-12-26-how-to-stay-sane-as-a-devops-person.html'>How to stay sane as a DevOps person</a><br />
<a class='textlink' href='./2022-05-27-perl-is-still-a-great-choice.html'>Perl is still a great choice</a><br />
<br />
<span>But now, let&#39;s continue with the small projects worth mentioning :-)</span><br />
<br />
<h2 style='display: inline'>Static photo album generator</h2><br />
<br />
<span><span class='inlinecode'>photoalbum.sh</span> is a minimal static HTML photo album generator. I use it to drive "The Irregular Ninja" site and for some ad-hoc (personal) albums to share photos with the family and friends.</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/photoalbum'>https://codeberg.org/snonux/photoalbum</a><br />
<br />
<h3 style='display: inline'>The Irregular Ninja</h3><br />
<br />
<span>Photography is one of my casual hobbies. I love to capture interesting perspectives and motifs. I love to walk new streets and neighbourhoods I never walked before so I can capture those unexpected motifs, colours and moments. Unfortunately, because of time constraints (and sometime weather constraints), I do that on a pretty infrequent basis.</span><br />
<br />
<a href='./2022-06-15-sweating-the-small-stuff/ninja.jpg'><img src='./2022-06-15-sweating-the-small-stuff/ninja.jpg' /></a><br />
<br />
<span>More than 10 years ago I wrote the bespoke small static photo album generator in Bash <span class='inlinecode'>photoalbum.sh</span> which I recently refactored to a modern Bash coding style and also freshened up the Cascading Style Sheets. Last but not least, the new domain name <span class='inlinecode'>irregular.ninja</span> has been registered.</span><br />
<br />
<span>The thumbnails are presented in a random order and there are also random CSS effects for each preview. There&#39;s also a simple background blur for each page generated. And that&#39;s all in less than 300 lines of Bash code! The script requires ImageMagick (available for all common Linux and *BSD distributions) to be installed.</span><br />
<br />
<span>As you can see, there is a lot of randomization and irregularity going on. Thus, the name "Irregular Ninja" was born.</span><br />
<br />
<a class='textlink' href='https://irregular.ninja'>https://irregular.ninja</a><br />
<br />
<span>I only use a digital compact camera or a smartphone to take the photos. I don&#39;t like the idea of carrying around a big camera with me "just in case" so I keep it small and simple. The best camera is the camera you have with you. :-)</span><br />
<br />
<span>I hope you like this photo site. It&#39;s worth checking it out again around once every other month!</span><br />
<br />
<h2 style='display: inline'>Random journal page extractor</h2><br />
<br />
<span>I bullet journal. I write my notes into a Leuchtturm paper notebook. Once full, I am scanning it to a PDF file and archive it. As of writing this, I am at journal #7 (each from 123 up to 251 pages in A5). It means that there is a lot of material already.</span><br />
<br />
<span>Once in a while I want to revisit older notes and ideas. For that I have written a simple Bash script <span class='inlinecode'>randomjournalpage.sh</span> which randomly picks a PDF file from a folder and extracts 42 pages from it at a random page offset and opens them in a PDF viewer (Evince in this case, as I am a GNOME user). </span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/randomjournalpage'>https://codeberg.org/snonux/randomjournalpage</a><br />
<br />
<span>There&#39;s also a weekly <span class='inlinecode'>CRON</span> job on my servers to send me a reminder that I might want to read in my old journals again. My laptop also runs this script each time it boots and saves the output to a NextCloud folder. From there, it&#39;s synchronized to the NextCloud server so I can pick it up from there with my smartphone later when I am "on the road".</span><br />
<br />
<h2 style='display: inline'>Global uptime records statistic generator</h2><br />
<br />
<span><span class='inlinecode'>guprecords</span> is a Perl script which reads multiple <span class='inlinecode'>uprecord</span> files (produced by <span class='inlinecode'>uptimed</span> - a widely available daemon for recording server uptimes) and generates uptime statistics of multiple hosts combined. I keep all the record files of all my personal computers in a Git repository (I even keep the records of the boxes I don&#39;t own or use anymore) and there&#39;s already quite a collection of it. It looks like this:</span><br />
<br />
<pre>
❯ perl ~/git/guprecords/src/guprecords --indir=./stats/ --count=20 --all
Pos |            System |               Kernel |        Uptime |                Boot time
  1 |               sun | FreeBSD 10.1-RELEA.. | 502d 03:29:19 | Sun Aug 16 15:56:40 2015
  2 |            vulcan | Linux 3.10.0-1160... | 313d 13:19:39 | Sun Jul 25 18:32:25 2021
  3 |             uugrn | FreeBSD 10.2-RELEASE | 303d 15:19:35 | Tue Dec 22 21:33:07 2015
  4 |             uugrn | FreeBSD 11.0-RELEA.. | 281d 14:38:04 | Fri Oct 21 15:22:02 2016
  5 |         deltavega | Linux 3.10.0-957.2.. | 279d 11:15:00 | Sun Jun 30 11:42:38 2019
  6 |            vulcan | Linux 3.10.0-957.2.. | 279d 11:12:14 | Sun Jun 30 11:43:41 2019
  7 |         deltavega | Linux 3.10.0-1160... | 253d 04:42:22 | Sat Apr 24 13:34:34 2021
  8 |             host0 | FreeBSD 6.2-RELEAS.. | 240d 02:23:23 | Wed Jan 31 20:34:46 2007
  9 |             uugrn | FreeBSD 11.1-RELEA.. | 202d 21:12:41 | Sun May  6 18:06:17 2018
 10 |           tauceti |  Linux 3.2.0-4-amd64 | 197d 18:45:40 | Mon Dec 16 19:47:54 2013
 11 |             pluto | Linux 2.6.32-5-amd64 | 185d 11:53:04 | Wed Aug  1 07:34:10 2012
 12 |               sun | FreeBSD 10.3-RELEA.. | 164d 22:31:55 | Sat Jul 22 18:47:21 2017
 13 |            vulcan | Linux 3.10.0-1160... | 161d 07:08:43 | Sun Feb 14 10:05:38 2021
 14 |               sun | FreeBSD 10.3-RELEA.. | 158d 21:18:36 | Sat Jan 27 10:18:57 2018
 15 |             uugrn | FreeBSD 11.1-RELEA.. | 157d 20:57:24 | Fri Nov  3 05:02:54 2017
 16 |         tauceti-f |  Linux 3.2.0-3-amd64 | 150d 04:12:38 | Mon Sep 16 09:02:58 2013
 17 |           tauceti |  Linux 3.2.0-4-amd64 | 149d 09:21:43 | Mon Aug 11 09:47:50 2014
 18 |             pluto |  Linux 3.2.0-4-amd64 | 142d 02:57:31 | Mon Sep  8 01:59:02 2014
 19 |         tauceti-f |  Linux 3.2.0-3-amd64 | 132d 22:46:26 | Mon May  6 11:11:35 2013
 20 |       keppler-16b |        Darwin 13.4.0 | 131d 08:17:12 | Thu Jun 11 10:44:25 2015
</pre>
<br />
<span>It can also sum up all uptimes for each host to generate a total per host uptime top list:</span><br />
<br />
<pre>
❯ perl ~/git/guprecords/src/guprecords --indir=./stats/ --count=20 --total
Pos |            System |               Kernel |        Uptime |
  1 |            uranus | Linux 5.4.17-200.f.. | 1419d 19:05:39 |
  2 |               sun | FreeBSD 10.1-RELEA.. | 1363d 11:41:14 |
  3 |            vulcan | Linux 3.10.0-1160... | 1262d 20:27:48 |
  4 |             uugrn | FreeBSD 10.2-RELEASE | 1219d 15:10:16 |
  5 |         deltavega | Linux 3.10.0-957.2.. | 1115d 06:33:55 |
  6 |             pluto | Linux 2.6.32-5-amd64 | 1086d 10:44:05 |
  7 |           tauceti |  Linux 3.2.0-4-amd64 | 846d 12:58:21 |
  8 |         tauceti-f |  Linux 3.2.0-3-amd64 | 625d 07:16:39 |
  9 |             host0 | FreeBSD 6.2-RELEAS.. | 534d 19:50:13 |
 10 |       keppler-16b |        Darwin 13.4.0 | 448d 06:15:00 |
 11 |         tauceti-e |  Linux 3.2.0-4-amd64 | 415d 18:14:13 |
 12 |              moon |        Darwin 18.7.0 | 326d 11:21:42 |
 13 |          callisto | Linux 4.0.4-303.fc.. | 303d 12:18:24 |
 14 |     alphacentauri | FreeBSD 10.1-RELEA.. | 300d 20:15:00 |
 15 |             earth | Linux 5.13.14-200... | 289d 08:05:05 |
 16 |          makemake | Linux 5.11.9-200.f.. | 286d 21:53:03 |
 17 |            london |  Linux 3.2.0-4-amd64 | 258d 15:10:38 |
 18 |          fishbone | OpenBSD 4.1       .. | 223d 05:55:26 |
 19 |       sagittarius |        Darwin 15.6.0 | 198d 23:53:59 |
 20 |              mars |  Linux 3.2.0-4-amd64 | 190d 05:44:21 |
</pre>
<br />
<a class='textlink' href='https://codeberg.org/snonux/guprecords'>https://codeberg.org/snonux/guprecords</a><br />
<br />
<span>This all is of no real practical use but fun!</span><br />
<br />
<h2 style='display: inline'>Server configuration management</h2><br />
<br />
<span>The <span class='inlinecode'>rexfiles</span> project contains all Rex files for my (personal) server setup automation. A <span class='inlinecode'>Rexfile</span> is written in a Perl DSL run by the Rex configuration management system. It&#39;s pretty much KISS and that&#39;s why I love it. It suits my personal needs perfectly. </span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/rexfiles'>https://codeberg.org/snonux/rexfiles</a><br />
<a class='textlink' href='https://www.rexify.org'>https://www.rexify.org</a><br />
<br />
<span>This is an E-Mail I posted to the Rex mailing list:</span><br />
<br />
<span class='quote'>Hi there! I was searching for a simple way to automate my personal OpenBSD setup. I found that configuration management systems like Puppet, Salt, Chef, etc.. were too bloated for my personal needs. So for a while I was configuring everything by hand. At one point I got fed up and started writing Shell scripts. But that was not the holy grail so that I looked at Ansible. I found that Ansible had some dependencies on Python on the target machine when you want to use all the features. Furthermore, I am not really familiar with Python. But then I remembered that there was also Rex. It&#39;s written in my beloved Perl. Also, OpenBSD comes with Perl in the base system out of the box which makes it integrate better than all my scripts (automation and also scripts deployed via the automation to the system) are all in the same language. Rex may not have all the features like other configuration management systems, but its easy to work-around or extend when you know Perl. Thanks!</span><br />
<br />
<h2 style='display: inline'>Fancy SSH execution loop</h2><br />
<br />
<span><span class='inlinecode'>rubyfy</span> is a fancy SSH loop wrapper written in Ruby for running shell commands on multiple remote servers at once. I also forked this project for work (under a different name) where I added even more features such as automatic server discovery. It&#39;s used by many colleagues on a frequent basis. Here are some examples:</span><br />
<br />
<pre>
# Run command &#39;hostname&#39; on server foo.example.com
./rubyfy.rb -c &#39;hostname&#39; &lt;&lt;&lt; foo.example.com

# Run command &#39;id&#39; as root (via sudo) on all servers listed in the list file
# Do it on 10 servers in parallel
./rubyfy.rb --parallel 10 --root --command &#39;id&#39; &lt; serverlist.txt

# Run a fancy script in background on 50 servers in parallel
./rubyfy.rb -p 50 -r -b -c &#39;/usr/local/scripts/fancy.zsh&#39; &lt; serverlist.txt

# Grep for specific process on both servers and write output to ./out/grep.txt
echo {foo,bar}.example.com | ./rubyfy.rb -p 10 -c &#39;pgrep -lf httpd&#39; -n grep.txt

# Reboot server only if file /var/run/maintenance.lock does NOT exist!
echo foo.example.com |
./rubyfy.rb --root --command reboot --precondition /var/run/maintenance.lock
</pre>
<br />
<a class='textlink' href='https://codeberg.org/snonux/rubyfy'>https://codeberg.org/snonux/rubyfy</a><br />
<br />
<h2 style='display: inline'>A KISS dynamic DNS solution</h2><br />
<br />
<span><span class='inlinecode'>dyndns</span> is a tiny shell script which implements "your" own DynDNS service. It relies on SSH access to the authoritative DNS server and the <span class='inlinecode'>nsupdate</span> command. There is really no need to use any of the "other" free DynDNS services out there.</span><br />
<br />
<span>Syntax (this must run from the client connecting to the DNS server through SSH): </span><br />
<br />
<pre>
ssh dyndns@dyndnsserver /path/to/dyndns-update \
    your.host.name. TYPE new-entry TIMEOUT
</pre>
<br />
<span>This is a real world example: </span><br />
<br />
<pre>
ssh dyndns@dyndnsserver /path/to/dyndns-update \
  local.buetow.org. A 137.226.50.91 30
</pre>
<br />
<a class='textlink' href='https://codeberg.org/snonux/dyndns'>https://codeberg.org/snonux/dyndns</a><br />
<br />
<h2 style='display: inline'>CPU information gatherer for Linux</h2><br />
<br />
<span>This is a tiny GNU Awk script for Linux which displays information about the CPU. All what it does is presenting <span class='inlinecode'>/proc/cpuinfo</span> in an easier to read way. The output is somewhat more compact than the standard <span class='inlinecode'>lscpu</span> command you find commonly on Linux distributions.</span><br />
<br />
<pre>
❯ ./cpuinfo
cpuinfo (c) 1.0.2 Paul Buetow

 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz GenuineIntel 12288 KB cache

p = 001 Physical processors
c = 004 Cores
s = 008 Siblings (Hyper-Threading enabled if s != c)
v = 008 [v = p*c*(s != c ? 2 : 1)] Total logical CPUs
 Hyper-Threading is enabled

0003000 MHz each core
0012000 MHz total
0005990 Bogomips each processor (including virtual)
0023961 Bogomips total
</pre>
<br />
<a class='textlink' href='https://codeberg.org/snonux/cpuinfo'>https://codeberg.org/snonux/cpuinfo</a><br />
<br />
<h2 style='display: inline'>Show differences of two files over the network</h2><br />
<br />
<span>This is a shell wrapper to use the standard diff tool over the network to compare a file between two computers. It uses NetCat for the network part and also encrypts all traffic using OpenSSL. This is how its used:</span><br />
<br />
<span>1. Open two terminal windows and login to two different hosts (you could use ClusterSSH or <span class='inlinecode'>tmux</span> here). 2. Run on the first host <span class='inlinecode'>netdiff otherhost.example.org /file/to/diff.txt</span> and run on the second host <span class='inlinecode'>netdiff firsthost.example.org /file/to/diff.txt</span>. 3. You then will see the file differences.</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/netdiff'>https://codeberg.org/snonux/netdiff</a><br />
<br />
<h2 style='display: inline'>Delay sending out E-Mails with Mutt</h2><br />
<br />
<span>This is a shell script for the Mutt email client for delaying sending out E-Mails. For example, you want to write an email on Saturday but don&#39;t want to bother the recipient earlier than Monday. It relies on CRON.</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/muttdelay'>https://codeberg.org/snonux/muttdelay</a><br />
<br />
<h2 style='display: inline'>Graphical UI for sending text messages</h2><br />
<br />
<span><span class='inlinecode'>jsmstrade</span> is a minimalistic graphical Java swing client for sending SMS messages over the SMStrade service.</span><br />
<br />
<a href='./2022-06-15-sweating-the-small-stuff/jsmstrade.png'><img src='./2022-06-15-sweating-the-small-stuff/jsmstrade.png' /></a><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/jsmstrade'>https://codeberg.org/snonux/jsmstrade</a><br />
<a class='textlink' href='https://smstrade.de'>https://smstrade.de</a><br />
<br />
<h2 style='display: inline'>IPv6 and IPv4 connectivity testing site</h2><br />
<br />
<span><span class='inlinecode'>ipv6test</span> is a quick and dirty Perl CGI script for testing whether your browser connects via IPv4 or IPv6. It requires you to setup three sub-domains: One reachable only via IPv4 (e.g. <span class='inlinecode'>test4.ipv6.buetow.org</span>), another reachable only via IPv6 (e.g. <span class='inlinecode'>test6.ipv6.buetow.org</span>) and the main one reachable through both protocols (e.g. <span class='inlinecode'>ipv6.buetow.org</span>).</span><br />
<br />
<span>I don&#39;t have it running on any of my servers at the moment. This means that there is no demo to show now. Sorry!</span><br />
<br />
<h2 style='display: inline'>List open Jira tickets in the terminal</h2><br />
<br />
<span><span class='inlinecode'>japi</span> s a small Perl script for listing open Jira issues. It might be broken by now as the Jira APIs may have changed. Sorry! But feel free to fork and modernize it. :-)</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/jsmstrade'>https://codeberg.org/snonux/jsmstrade</a><br />
<span> </span><br />
<h2 style='display: inline'>Debian running on "your" Android phone</h2><br />
<br />
<span>Debroid is a tutorial and a set of scripts to install and to run a Debian <span class='inlinecode'>chroot</span> on an Android phone.</span><br />
<br />
<a class='textlink' href='./2015-12-05-run-debian-on-your-phone-with-debroid.html'>Check out my previous post about it</a><br />
<br />
<span>I am not using Debroid anymore as I have switched to Termux now.</span><br />
<br />
<a class='textlink' href='https://termux.com'>https://termux.com</a><br />
<br />
<h2 style='display: inline'>Perl service framework</h2><br />
<br />
<span>PerlDaemon is a minimal daemon for Linux and other Unix like operating systems programmed in Perl. It is a minimal but pretty functional and fairly generic service framework. This means that it does not do anything useful other than providing a framework for starting, stopping, configuring and logging. To do something useful, a module (written in Perl) must be provided.</span><br />
<br />
<a class='textlink' href='./2011-05-07-perl-daemon-service-framework.html'>Checkout my previous post about it</a><br />
<br />
<h2 style='display: inline'>More</h2><br />
<br />
<span>There are more projects on my Codeberg page but they aren&#39;t as tiny as the ones mentioned in this post or aren&#39;t finished yet so I won&#39;t bother listing them here. However, there also a few more scripts used frequently by me (not publicly accessible (yet?)) which I would like to mention here:</span><br />
<br />
<h3 style='display: inline'>Work time tracker</h3><br />
<br />
<span><span class='inlinecode'>worktime.rb</span>, for example, is a command line Ruby script I use to track my time spent working. This is to make sure that I don&#39;t overwork (in particular useful when working from home). It also generates some daily and weekly stats and carries over work time (surpluses or minuses) to the next work day, week or even year.</span><br />
<br />
<span>It has some special features such as tracking time for self-improvement/development, days off and time spent at the lunch break and time spent on Pet Projects.</span><br />
<br />
<span>An example weekly report looks like this (I often don&#39;t track my lunch time but what I do instead I stop the work timer when I go out for lunch and start the work timer once back at the desk):</span><br />
<br />
<pre>
     Mon 20211213 50: work:5.92h
     Tue 20211214 50: work:7.47h lunch:0.50h pet:0.42h
     Wed 20211215 50: work:8.86h pet:0.50h
     Thu 20211216 50: work:8.02h pet:0.50h
     Fri 20211217 50: work:9.81h
   * Sat 20211218 50: work:0.00h selfdevelopment:1.00h
   * Sun 20211219 50: work:2.08h pet:1.00h selfdevelopment:-2.08h
================================================
 balance:0.06h work:42.15h lunch:0.50h pet:2.42h selfdevelopment:-1.08h buffer:8.38h
</pre>
<br />
<span>All I do when I start work is to run the <span class='inlinecode'>wtlogin</span> command and after finishing work to run the <span class='inlinecode'>wtlogout</span> command. My shell will remind me when I work without having logged in. It uses a simple JSON database which is editable with <span class='inlinecode'>wtedit</span> (this opens the JSON in Vim). The report shown above can be generated with <span class='inlinecode'>wtreport</span>. Any out-of-bounds reporting can be added with the <span class='inlinecode'>wtadd</span> command.</span><br />
<br />
<h3 style='display: inline'>Password and document store</h3><br />
<br />
<span><span class='inlinecode'>geheim.rb</span> is my personal password and document store ("geheim" is the German word for secret). It&#39;s written in Ruby and heavily relies on Git, FZF (for search), Vim and standard encryption algorithms. Other than the standard <span class='inlinecode'>pass</span> Unix password manager, <span class='inlinecode'>geheim</span> also encrypts the file names and password titles.</span><br />
<br />
<span>The tool is command line driven but also provides an interactive shell when invoked with <span class='inlinecode'>geheim shell</span>. It also works on my Android phone via Termux so I have all my documents and passwords always with me. </span><br />
<br />
<h3 style='display: inline'>Backup procedure</h3><br />
<br />
<span><span class='inlinecode'>backup</span> is a Bash script which does run once daily (or every time on boot) on my home FreeBSD NAS server and performs backup related tasks such as creating a local backup of my remote NextCloud instance, creating encrypted (incremental) ZFS snapshots of everything what&#39;s stored on the NAS and synchronizes (via <span class='inlinecode'>rsync</span>) backups to a remote cloud storage. It also can synchronize backups to a local external USB drive.</span><br />
<br />
<a class='textlink' href='./2016-04-03-offsite-backup-with-zfs.html'>Check out my offsite backup series</a><br />
<br />
<h2 style='display: inline'>konpeito.media</h2><br />
<br />
<span>Here&#39;s a bonus...</span><br />
<br />
<pre>
                                                           ▄ █ ▄  ▄ █ ▄  ▄ █ ▄
                                                           ▄▀█▀▄  ▄▀█▀▄  ▄▀█▀▄
  ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                            ▀      ▀      ▀
 █   ▄▄     ▄▄   █
 █  █  █▀▀▀█  █  █  █   ▄▀  ▄▀▀▀▀▄  █▄    █ █▀▀▀▀▀▄  ▄▀▀▀▀▄  █ ▀▀▀█▀▀▀ ▄▀▀▀▀▄
 █   ▀▀▀▀▀▀▀▀▀   █  █ ▄█   █      █ █ ▀▄  █ █▄▄▄▄▄▀ █▄▄▄▄▄▄█ █    █   █      █
 █ ▄▀▀▀▀▀▀▀▀▀▀▀▄ █  █▀  ▀▄ ▀▄    ▄▀ █   ▀▄█ █       ▀▄    ▄  █    █   ▀▄    ▄▀
 ▀▄█▄█▄▄▄▄▄▄▄█▄█▄▀  ▀     ▀  ▀▀▀▀   ▀     ▀ ▀         ▀▀▀▀   ▀    ▀     ▀▀▀
</pre>
<br />
<span>*THIS ISN&#39;T MY PROJECT* but I found KONPEITO an interesting Gemini capsule. It&#39;s a quarterly released Low-Fi music mix tape distributed only through Gemini (and not the web). </span><br />
<br />
<a class='textlink' href='gemini://konpeito.media'>gemini://konpeito.media</a><br />
<br />
<span>If you wonder what Gemini is:</span><br />
<br />
<a class='textlink' href='./2021-04-24-welcome-to-the-geminispace.html'>Welcome to the Geminispae</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Perl is still a great choice</title>
        <link href="gemini://foo.zone/gemfeed/2022-05-27-perl-is-still-a-great-choice.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-05-27-perl-is-still-a-great-choice.gmi</id>
        <updated>2022-05-27T07:50:12+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Perl (the Practical Extraction and Report Language) is a battle-tested, mature, multi-paradigm dynamic programming language. Note that it's not called PERL, neither P.E.R.L. nor Pearl. 'Perl' is the name of the language and `perl` the name of the interpreter or the interpreter command.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Perl is still a great choice</h1><br />
<br />
<span class='quote'>Published at 2022-05-27T07:50:12+01:00; Updated at 2023-01-28</span><br />
<br />
<a href='./2022-05-27-perl-is-still-a-great-choice/regular_expressions.png'><img alt='Comic source: XKCD' title='Comic source: XKCD' src='./2022-05-27-perl-is-still-a-great-choice/regular_expressions.png' /></a><br />
<br />
<span>Perl (the Practical Extraction and Report Language) is a battle-tested, mature, multi-paradigm dynamic programming language. Note that it&#39;s not called PERL, neither P.E.R.L. nor Pearl. "Perl" is the name of the language and <span class='inlinecode'>perl</span> the name of the interpreter or the interpreter command.</span><br />
<br />
<span>Unfortunately (it makes me sad), Perl&#39;s popularity has been declining over the last years as Google trends shows:</span><br />
<br />
<a href='./2022-05-27-perl-is-still-a-great-choice/googletrendsperl.jpg'><img src='./2022-05-27-perl-is-still-a-great-choice/googletrendsperl.jpg' /></a><br />
<br />
<span>So why is that? Once the de-facto standard super-glue language for the web nowadays seems to have a bad reputation. Often, people state:</span><br />
<br />
<ul>
<li>Perl is a write-only language. Nobody can read Perl code.</li>
<li>Perl? Isn&#39;t it abandoned? It&#39;s still at version 5!</li>
<li>Why use Perl as there are better alternatives?</li>
<li>Why all the sigils? It looks like an exploding ASCII factory!!</li>
</ul><br />
<h2 style='display: inline'>Write-only language</h2><br />
<br />
<span>Is Perl really a write-only language? You have to understand that Perl 5 was released in 1994 (28 years ago as of this writing) and when we refer to Perl we usually mean Perl 5. That&#39;s many years, and there are many old scripts not following the modern Perl best practices (as they didn&#39;t exist yet). So yes, legacy scripts may be difficult to read. Japanese may be difficult to read too if you don&#39;t know Japanese, though.</span><br />
<br />
<span>To come back to the question: Is Perl a write-only language? I don&#39;t think so. Like in any other language, you have to apply best practices in order to keep your code maintainable. Some other programming languages enforce best practices, but that makes these languages less expressive. Perl follows the principles "there is more than one way to do it" (aka TIMTOWDI) and "making easy things easy and hard things possible".</span><br />
<br />
<span>Perl gives the programmer more flexibility in how to do things, and this results in a stronger learning curve than for lesser expressive languages like for example Go or Python. But, like in everything in life, common sense has to be applied. You should not take TIMTOWDI to the extreme in a production piece of code. In my personal opinion, it is also more satisfying to program in an expressive language.</span><br />
<br />
<span>Some good books on "good" Perl I can recommend are:</span><br />
<br />
<a class='textlink' href='http://modernperlbooks.com'>Modern Perl</a><br />
<a class='textlink' href='https://hop.perl.plover.com'>Higher Order Perl</a><br />
<br />
<span>Due to Perl&#39;s expressiveness you will find a lot of obscure code in the interweb in form of obfuscation, fancy email signatures (JAPHs), art, polyglots and even poetry in Perl syntax. But that&#39;s not what you will find in production code. That&#39;s only people having fun with the language which is different to "getting things done". The expressiveness is a bonus. It makes the Perl programmers love Perl.</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Just_another_Perl_hacker'>JAPH</a><br />
<a class='textlink' href='http://www.cpan.org/misc/japh'>http://www.cpan.org/misc/japh</a><br />
<a class='textlink' href='https://www.perlmonks.org/index.pl?next=20;node_id=1590'>Perl Poetry</a><br />
<br />
<span>Even I personally have written some poetry in Perl and experimented with a polyglot script:</span><br />
<br />
<a class='textlink' href='./2008-06-26-perl-poetry.html'>My very own Perl Poetry</a><br />
<a class='textlink' href='./2014-03-24-the-fibonacci.pl.c-polyglot.html'>A Perl-Raku-C polyglot generating the Fibonacci sequence</a><br />
<br />
<span>This all doesn&#39;t mean that you can&#39;t "get things done" with Perl. Quite the opposite is the case. Perl is a very pragmatic programming language and is suitable very well for rapid prototyping and any kind of small to medium-sized scripts and programs. You can write large enterprise scale application in Perl too, but that wasn&#39;t the original intend of why Perl was invented (more on that later).</span><br />
<br />
<h2 style='display: inline'>Is Perl abandoned?</h2><br />
<br />
<span>As I pointed out in the previous section, Perl 5 is around for quite some time without any new major version released. This can lead to the impression that development is not progressing and that the project is abandoned. Nothing can be further from the truth. Perl 5.000 was released in 1994 and the latest version (as of this writing) Perl 5.34.1 was released two months ago in 2022. You can check the version history on Wikipedia. You will notice releases being made regularly:</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Perl_5_version_history'>Perl 5 version history</a><br />
<br />
<span>As you can see, Perl 5 is under active development. I can also recommend to have a look at the following book, it summarizes all new Perl features which showed up after Perl v5.10:</span><br />
<br />
<a class='textlink' href='https://perlschool.com/books/perl-new-features/'>Perl New Features by Joshua McAdams and brian d foy</a><br />
<br />
<span>Actually, Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter&#39;s name was officially changed to Raku in October 2019 as the differences between Perl 5 and Perl 6 were too groundbreaking. Raku would be a different topic (mostly out of scope of this blog article) but I at least wanted it to mention here. In my opinion, Raku is the "most powerful" programming language out there (I recently started learning it and intend to use it for some of my future personal programming projects):</span><br />
<br />
<a class='textlink' href='https://raku.org'>The Raku Programming Language</a><br />
<br />
<span>So it means that Perl and Raku now exist in parallel. They influence each other, but are different programming languages now. So why not just all use Raku instead of Perl? There are still a couple of reasons of why to choose Perl over Raku:</span><br />
<br />
<ul>
<li>Many programmers already know Perl and many scripts are already written in Perl. It&#39;s possible to call Perl code from Raku (either inline or as a library) and it is also possible to auto-convert Perl code into Raku code, but that&#39;s either a workaround or involves some kind of additional work.</li>
<li>Perl 5 comes with a great backwards compatibility. Perl scripts from 5.000 will generally still work on a recent version of Perl. New features usually have to be enabled via a so-called "use pragmas". For example, in order to enable sub signatures, <span class='inlinecode'>use signatures;</span> has to be specified.</li>
<li>Perl is pre-installed almost everywhere. Fancy running a quick one-off script? In almost all cases, there&#39;s no need to install Perl first - it&#39;s already there on almost any Linux or *BSD or Unix or other Unix like operating system!</li>
<li>Perl has been ported to "zillions" of platforms. One day I found myself on a VMS box. Perl doesn&#39;t come installed by default on VMS, but the admin installed Perl there already. The whole operating system was very strange to me, but I was able to write "shell scripts" in Perl and became productive pretty quickly on VMS without knowing almost anything about VMS :-).</li>
<li>Perl is reliable. It has been proven itself "millions" of times, over and over again. Large enterprises, such as booking.com, heavily rely on Perl. Did you know that the package manager of the OpenBSD operating system is programmed in Perl, too?</li>
<li>Perl is a great language to program in (given that you follow the modern best practices). Don&#39;t get confused when Perl is doing some things differently than other programming languages.</li>
</ul><br />
<a class='textlink' href='https://perldoc.perl.org/feature'>Perl feature pragmas</a><br />
<a class='textlink' href='https://www.OpenBSD.org'>The OpenBSD Operating System</a><br />
<a class='textlink' href='https://news.ycombinator.com/item?id=23360338'>Why does OpenBSD still include Perl in its base installation?</a><br />
<br />
<span>The renaming of Perl 6 to Raku has now opened the door for a future Perl 7. As far as I understand, Perl 7 will be Perl 5 but with modern features enabled by default (e.g. pragmas <span class='inlinecode'>use strict;</span>,  <span class='inlinecode'>use warnings;</span>, <span class='inlinecode'>use signatures;</span> and so on. Also, the hope is that a Perl 7 with modern standards will attract more beginners. There aren&#39;t many Perl jobs out there nowadays. That&#39;s mostly due to Perl&#39;s bad (bad for no real reasons) reputation.</span><br />
<br />
<span class='quote'>Update 2022-12-10: A reader pointed out, that <span class='inlinecode'>use v5.36;</span> already turns strict, warnings and signatures pragmas automatically on! </span><br />
<br />
<a class='textlink' href='https://www.perl.com/article/announcing-perl-7/'>Announcing Perl 7</a><br />
<a class='textlink' href='http://blogs.perl.org/users/psc/2022/05/what-happened-to-perl-7.html'>What happened to Perl 7? (maybe have to use <span class='inlinecode'>use v7;</span>)</a><br />
<br />
<span class='quote'>Update 2022-12-10: A reader pointed out, that Perl 7 needs to provide a big improvement to earn and keep the attention for a major version bump.</span><br />
<br />
<span class='quote'>Update 2023-01-28: Meanwhile, I was also reading brian d foy&#39;s Perl New Feature book. It nicely presents all new features added to Perl since <span class='inlinecode'>v5.10</span>.</span><br />
<br />
<a class='textlink' href='https://www.leanpub.com/perl_new_features'>Perl New Features</a><br />
<br />
<h2 style='display: inline'>Why use Perl as there are better alternatives?</h2><br />
<br />
<span>Here, common sense must be applied. I don&#39;t believe there is anything like "the perfect" programming language. Everyone has got his preferred (or a set of preferred) programming language to chose from. All programming languages come with their own set of strengths and weaknesses. These are the strengths making Perl shine, and you (technically) don&#39;t need to bother to look for "better" alternatives:</span><br />
<br />
<ul>
<li>Perl is better than Shell/AWK/SED scripts. There&#39;s a point where shell scripts become fairly complex. The next step-up is to switch to Perl. There are many different versions of shells and AWK and SED interpreters. Do you always know which versions (<span class='inlinecode'>mawk</span>, <span class='inlinecode'>nawk</span>, <span class='inlinecode'>gawk</span>, <span class='inlinecode'>sed</span>, <span class='inlinecode'>gsed</span>, <span class='inlinecode'>grep</span>, <span class='inlinecode'>ggrep</span>...) are currently installed? These commands aren&#39;t fully compatible to each other. However, there is only one Perl 5. Simply: Perl is faster, more powerful, more expressive than any shell script can ever be, and it is also extendible through CPAN. Perl can directly talk to databases, which shell scripts can&#39;t.</li>
<li>Perl code tends to be compact so that it&#39;s much better suitable for "shell scripting" and quick "one-liners" than other languages. In my own experience: Ruby and Python code tends to blow up quickly. It doesn&#39;t mean that Ruby and Python are not suitable for this task, but I think Perl does much better.</li>
<li>Perl 5 has proven itself for decades and is a very stable/robust language. It is a battle-tested and mature as something can ever become.</li>
<li>Perl is the reference standard for regular expressions. Even so much that there is a PCRE library (Perl Compatible Regular Expressions) used by many other languages now. Perl fully integrates regular expression syntax into the language, which doesn&#39;t feel like an odd add-on like in most other languages.</li>
<li>Perl 5 is the master of text processing (well, maybe after Raku now. But you might not have the latest Raku available everywhere). The chief objective of developing the language was for text processing, and this is where Perl (Practical extraction and report language) really shines.</li>
<li>Perl is a "deep" language. That means Perl got a lot of features and syntactic sugar and magic. Depending on the perspective, this could be interpreted as a downside too. But IMHO mastery of a "deep" language brings big rewards. The code can be very compact, and it is fun to code in it.</li>
<li>Perl is the only language I know which can do "taint checking". Running a script in taint mode makes Perl sanitize all external input and that&#39;s a great security feature. Ruby used to have this feature too, but it got removed (as I understand there were some problems with the implementation not completely safe and it was easier just to remove it from the language than to fix it).</li>
</ul><br />
<span>About the first point, using Perl for better "shell" scripts was actually the original intend of why Perl was invented in the first place.</span><br />
<br />
<a class='textlink' href='https://nostarch.com/perloneliners'>Perl one-liners</a><br />
<a class='textlink' href='http://regex.info/book.html'>Mastering Regular Expressions</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Taint_checking'>Taint checking</a><br />
<br />
<span>Here are some reasons why not to chose Perl and look for "better" alternatives:</span><br />
<br />
<ul>
<li>If performance is your main objectives, then Perl might not be the language to use. Perl is a dynamic interpreted language, and it will generally never be as fast as statically typed languages compiled to native binaries (e.g. C/C++/Rust/Haskell) or statically typed languages run in a VM with JIT (e.g. Java) or gradually typed languages run in a VM (e.g. Raku) or languages like Golang (statically typed, compiled to a binary but still with a runtime in the binary). Perl might be still faster than the other language listed here in certain circumstances (e.g. faster startup time than Java or faster regular expressions engine), but usually it&#39;s not. It&#39;s not a problem of Perl, it&#39;s a problem of all dynamic scripting languages including Python, Ruby, ....</li>
<li>Don&#39;t use Perl (just yet) if you want to code object-oriented. Perl supports OOP, but it feels clunky and odd to use (blessed references to any data types are objects) and doesn&#39;t support real encapsulation out of the box. There are many (many) extensions available on CPAN to make OOP better, but that&#39;s totally fragmented. The most popular extension, Moose, comes with a huge dependency tree. But wait for Perl 7. It will maybe come with a new object system (an object system inspired by Raku).</li>
<li>It&#39;s possible to write large programs in Perl (make difficult things possible), but it might not be the best choice here. This also leads back to the clunky object system Perl has. You could write your projects in a procedural or functional style (Perl perfectly fits here), but OOP seems to be the gold standard for large projects nowadays. Functional programming requires a different mindset, and pure procedural programming lacks abstractions.</li>
<li>Apply common sense. What is the skill set your team has? What&#39;s already widely used and supported at work? Which languages comes with the best modules for the things you want to work on? Maybe Python is the answer (better machine learning modules). Maybe Perl is the better choice (better Bioinformatic modules). Perhaps Ruby is already the de-facto standard at work and everyone knows at least a little Ruby (as it happened to be at my workplace) and Ruby is "good enough" for all the tasks already. But that&#39;s not a hindrance to throw in a Perl one-liner once in a while :P.</li>
</ul><br />
<a class='textlink' href='https://github.com/Ovid/Cor'>Cor - Bringing modern OOP to the Perl Core</a><br />
<br />
<h2 style='display: inline'>Why all the sigils? It looks like an exploding ASCII factory!!</h2><br />
<br />
<span>The sigils <span class='inlinecode'>$ @ % &amp;</span> (where Perl is famously known for) serve a purpose. They seem confusing at first, but they actually make the code better readable. <span class='inlinecode'>$scalar</span> is a scalar variable (holding a single value), <span class='inlinecode'>@array</span> is an array (holding a list of values), <span class='inlinecode'>%hash</span> holds a list of key-value pairs and <span class='inlinecode'>&amp;sub</span> is for subroutines. A given variable <span class='inlinecode'>$ref</span> can also hold reference to something. <span class='inlinecode'>@$arrayref</span> dereferences a reference to an array, <span class='inlinecode'>%$hashref</span> to a hash, <span class='inlinecode'>$scalarref</span> to a scalar, <span class='inlinecode'>&amp;$subref</span> dereferences a referene to a subroutine, etc. That can be encapsulated as deep as you want. (This paragraph only scratched the surface here of what Perl can do, and there is a lot of syntactic sugar not mentioned here).</span><br />
<br />
<span>In most other programming languages, you won&#39;t know instantly what&#39;s the "basic type" of a given variable without looking at the variable declaration or the variable name (If named intelligently, e.g. a variable name containing a list of cats is <span class='inlinecode'>cat_list</span>). Even Ruby makes some use of sigils (<span class='inlinecode'>@</span>, <span class='inlinecode'>@@</span> and <span class='inlinecode'>{body}lt;/span>), but that&#39;s for a different purpose than in Perl (in Ruby it is about object scope, class scope and global scope). Raku uses all the sigils Perl uses plus an additional bunch of twigils, e.g. <span class='inlinecode'>$.foo</span> for a scalar object variable with public accessors, <span class='inlinecode'>$!foo</span> for a private scalar object variable, <span class='inlinecode'>@.foo</span>, <span class='inlinecode'>@!foo</span>, <span class='inlinecode'>%.foo</span>, <span class='inlinecode'>%!foo</span> and so on. Sigils (and twigils) are very convenient once you get used to them. Don&#39;t let them scare you off - they are there to help you!</span><br />
<br />
<a class='textlink' href='https://www.perl.com/article/on-sigils/'>https://www.perl.com/article/on-sigils/</a><br />
<br />
<h2 style='display: inline'>Where do I personally still use perl?</h2><br />
<br />
<ul>
<li>I use Rexify for my OpenBSD server automation. Rexify is a configuration management system developed in Perl with similar features to Ansible but less bloated. It suits my personal needs perfectly.</li>
<li>I have written a couple of smaller to medium-sized Perl scripts which I (mostly) still use regularly. You can find them on my Codeberg page.</li>
<li>My day-to-day workflow heavily relies on "ack-grep". Ack is a tool developed in Perl aimed at programmers and can be used for quick searches on source code at the command line.</li>
<li>I aim to leave my OpenBSD servers as "vanilla" as possible (trying to rely only on the standard/base installation without installing additional software from the packaging system or ports tree). All my scripts are written either Bourne shell or in Perl here. So there is no need to install additional interpreters.</li>
<li>Here and there, I drop a Perl one-liner in order to get stuff done (work and personally). A wise Perl Monk would say: "One one-liner a day keeps the troubles away".</li>
</ul><br />
<span>Btw.: Did you know that the first version of PHP was a set of Perl snippets? Only later, PHP became an independent programming language.</span><br />
<br />
<a class='textlink' href='https://www.perl.org'>https://www.perl.org</a><br />
<br />
<span class='quote'>Update 2022-12-17: The following is another related post. I don&#39;t agree to the statement made there, that Python code tends to be shorter than Perl code, though!</span><br />
<br />
<a class='textlink' href='https://stackoverflow.blog/2022/07/06/why-perl-is-still-relevant-in-2022/'>Why Perl is still relevant in 2022</a><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2023-05-01-unveiling-guprecords:-uptime-records-with-raku.html'>2023-05-01 Unveiling <span class='inlinecode'>guprecords.raku</span>: Global Uptime Records with Raku</a><br />
<a class='textlink' href='./2022-05-27-perl-is-still-a-great-choice.html'>2022-05-27 Perl is still a great choice (You are currently reading this)</a><br />
<a class='textlink' href='./2011-05-07-perl-daemon-service-framework.html'>2011-05-07 Perl Daemon (Service Framework)</a><br />
<a class='textlink' href='./2008-06-26-perl-poetry.html'>2008-06-26 Perl Poetry</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Creative universe</title>
        <link href="gemini://foo.zone/gemfeed/2022-04-10-creative-universe.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-04-10-creative-universe.gmi</id>
        <updated>2022-04-10T10:09:11+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I have been participating in an annual work-internal project contest (we call it Pet Project contest) since I moved to London and switched jobs to my current employer. I am very happy to say that I won a 'silver' prize last week here 🎆. Over the last couple of years I have been a finalist in this contest six times and won some kind of prize five times. Some of my projects were also released as open source software. One had a magazine article published, and for another one I wrote an article on my employer's engineering blog. If you have followed all my posts on this blog (the one you are currently reading), then you have probably figured out what these projects were:</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Creative universe</h1><br />
<br />
<span class='quote'>Published at 2022-04-10T10:09:11+01:00; Updated at 2022-04-18</span><br />
<br />
<pre>
 .              +   .                .   . .     .  .
                   .                    .       .     *
  .       *                        . . . .  .   .  + .
            "You Are Here"            .   .  +  . . .
.                 |             .  .   .    .    . .
                  |           .     .     . +.    +  .
                 \|/            .       .   . .
        . .       V          .    * . . .  .  +   .
           +      .           .   .      +
                            .       . +  .+. .
  .                      .     . + .  . .     .      .
           .      .    .     . .   . . .        ! /
      *             .    . .  +    .  .       - O -
          .     .    .  +   . .  *  .       . / |
               . + .  .  .  .. +  .
.      .  .  .  *   .  *  . +..  .            *
 .      .   . .   .   .   . .  +   .    .            +
                                         - the universe
</pre>
<br />
<h2 style='display: inline'>Prelude</h2><br />
<br />
<span>I have been participating in an annual work-internal project contest (we call it Pet Project contest) since I moved to London and switched jobs to my current employer. I am very happy to say that I won a "silver" prize last week here 🎆. Over the last couple of years I have been a finalist in this contest six times and won some kind of prize five times. Some of my projects were also released as open source software. One had a magazine article published, and for another one I wrote an article on my employer&#39;s engineering blog. If you have followed all my posts on this blog (the one you are currently reading), then you have probably figured out what these projects were:</span><br />
<br />
<a class='textlink' href='./2021-04-22-dtail-the-distributed-log-tail-program.html'>DTail - The distributed log tail program</a><br />
<a class='textlink' href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux.html'>Realistic load testing with I/O Riot for linux</a><br />
<br />
<span>Note that my latest silver prize project isn&#39;t open source software and because of that there is no public material I can refer to. Maybe the next one again?</span><br />
<br />
<span>I want to point out that I never won the "gold" prize and it&#39;s the first time I won "silver", though. I believe, looking at the company&#39;s contest history, I am the employee with the most consecutive successful project submissions (my streak broke as I didn&#39;t participate last year) and am also the one with the highest successful project count in total. Sorry if this all sounds a bit self-promotional, but I think it is something to be proud of. Consistency beats a one-off success.</span><br />
<br />
<span>I often put endless hours and sometimes sleepless nights into such projects and all of that in my own time. I, an engineer whose native tongue is not English, also have to present such a project in front of the CEO, CTO and CPO, the Chief Scientist, the founders of the company, and, if it is not enough, to all other staff of the company too. I usually also demonstrate a working prototype live on a production grid during the presentation. 😓</span><br />
<br />
<span>So why would I sign up myself for such side projects? Isn&#39;t it a lot of stress and extra work? Besides the prize in form of money (you can not count on that, you may win or you may not win something) and recognition, there are also other motivational points:</span><br />
<br />
<ul>
<li>I want to learn new technologies or to deepen my knowledge of a given technology. I want to have a personal benefit from the project, even when I don&#39;t win any prize. So when the company is offering a contest, why not use it as a motivational trampoline? It&#39;s good to have a hard deadline for a project. And the project will also benefit the company in some way. So it&#39;s a win-win.</li>
<li>I love the idea of combining several old things into a new thing. You can call this creativity. At work, we call this sometimes Lego: Building new things from given blocks. But I also love to add something new and unique to the mix, something that didn&#39;t exist as a Lego block before and could not be built by using only the already existing blocks.</li>
</ul><br />
<h2 style='display: inline'>How to be creative</h2><br />
<br />
<span>How did I manage to be creative with all these Pet Projects? Unfortunately, there is no step-by-step guide I could point you to. But what I want to do in this blog post is share my personal experience so far.</span><br />
<br />
<h3 style='display: inline'>Know which problem you want to solve</h3><br />
<br />
<span>There must be a problem to be solved or a thing to be improved. It makes no sense to have a project without a goal. A problem might be obvious to you, and you don&#39;t even need to think about it. In that case, you are all set, and you can immerse yourself with the problem.</span><br />
<br />
<span>If, however, you don&#39;t know what problem you want to solve: Do you really need to be creative? All problems are solved anyway, correct? In that case, just go on with your work. As you immerse yourself with your daily work, you will find a project naturally after a while. I don&#39;t believe you should artificially find a project. It should come naturally to you. You should have an interest in the problem domain and a strong desire to find a proper solution for the problem. Artificially created projects come with the catch that you might give up on it rather sooner than later due to lack of motivation and desire.</span><br />
<br />
<h3 style='display: inline'>Immerse / deep dive</h3><br />
<br />
<span>If you want to be creative in a field, you must know a lot about it. The more you know about it, the more dots you can connect. When you are learning a new technology or if you are thinking about a tough problem, do it thoroughly. Don&#39;t let anything distract you. Read books, watch lectures, listen to podcasts or audiobooks about the topic, talk to other people working on similar topics. Immerse yourself for multiple hours per day, multiple days per week, multiple weeks and maybe even months. Create your own inner universe.</span><br />
<br />
<span>But once a day is over, shut your thoughts down. Hit the off-switch. Stop thinking about this problem for the remainder of the day. This can be difficult, as you didn&#39;t solve the problem- or didn&#39;t understand everything of the new technology yet, and you really want to get to the point. But be strict to yourself and stop thinking about it for a while.</span><br />
<br />
<span>You must understand that you are more than just your conscious thoughts. Your brain does a lot of work in the background that you aren&#39;t aware of consciously. What happens when you stop consciously thinking about a problem is that your brain continues processing it. You might have experienced the "AHA"-effect, where suddenly you had an idea out of nowhere (e.g. during a walk, in the shower, or in the morning when you woke up)? This is your conscious self downloading a result from the background thread of your brain. You can elevate this effect by immersing with the problem immensely before giving your conscious self a break.</span><br />
<br />
<span>Sometimes, depending on how deeply you were immersed, you may need to let the problem go for a couple of days (e.g. over a weekend) before you can download a new insight.</span><br />
<br />
<h3 style='display: inline'>Always have a notebook with you</h3><br />
<br />
<span>Wherever you go, ensure that you always have something to take notes with you. Once you have an idea from nowhere (or from your unconscious but volatile brain), you really want to write it down to persistent storage. It doesn&#39;t matter what kind of note-taking device you use here. It can be a paper journal, or it can be your smartphone. </span><br />
<br />
<span>My advice is to have a separate section where you put your notes of all of your ideas. At home or in the office, I write everything in my paper journal. When I am not at home, I use a digital note-taking app on my phone. Later, I copy the digital notes from it into a project-specific section of my paper journal.</span><br />
<br />
<span>I prefer taking notes on paper, as it gives you more freedom of how to structure it. You can use any colour, and you can also quickly create diagrams without the use of any complex computer program.</span><br />
<br />
<h3 style='display: inline'>When you didn&#39;t sleep enough</h3><br />
<br />
<span>I noticed while being sleep-deprived I am (obviously) unable to concentrate so much, and it is difficult to be immersed in a focused way. But on the other hand, I am a lot more creative compared to when I am not sleep-deprived. Then, my brain suddenly presents me with connections I have not thought of before. Here, I usually write any idea I have down on a sheet of paper or in my journal, so I can pick it up later. I then often continue to philosophise about a possible solution. Sometimes to the absurd, and sometimes to something pretty useful.</span><br />
<br />
<span>I am not saying that you should skip sleep. By all means, if you can sleep, then sleep. But there are some days when you don&#39;t manage to sleep (e.g. think too much about a project and didn&#39;t manage to hit the off switch). This is, where you can take advantage of your current state of mind. Disclaimer: Skipping sleep damages your health. So, please don&#39;t try this out on purpose. But in case you had a bad night, remember this trick.</span><br />
<br />
<h3 style='display: inline'>Have regular breaks and relax</h3><br />
<br />
<span>Have regular breaks. Don&#39;t skip your lunch break. Best, have a walk during lunchtime. And after work, do some kind of workout or visit a sports class. Do something completely unrelated to work before going to sleep (e.g. visit a parallel universe and read a Science Fiction novel). In short: Totally hit the off-switch after your work for the day is finished. You will be much more energised and motivated the next time you open your work laptop.</span><br />
<br />
<a class='textlink' href='../other-resources.html'>I personally love to read Science Fiction novels</a><br />
<br />
<span>I skip breakfast and lunch during the week. This means that on average, I intermittent fast on average 18-20 hours daily. It may sound odd to most people (who don&#39;t intermittent fast), but in a fasted state, I can be even more focused, thus helping me immerse myself in something even more. Not having breakfast and lunch also gives me back some time for other things (e.g. a nice walk, where I listen to podcasts or audiobooks or practise using my camera (street photography)). I relax my routine during the week ends, where I may enjoy a meal at any given time of the day.</span><br />
<br />
<span>It also helps a lot eat healthy. Healthy food makes your brain work more efficiently. But I won&#39;t go into more details here, as nothing is as contradictory as the health and food industry. Conduct your own research. Your opinion may be different from mine anyway, and everyone&#39;s body reacts to certain foods differently. What for one person works may not work for another person. But be aware that you will find a lot of wrong and also conflicting information on the internet. So always use multiple resources for your research.</span><br />
<br />
<h3 style='display: inline'>Upside-down approach</h3><br />
<br />
<span>It&#39;s easy to fall into the habit of "boxed" thinking, but creativity is exactly the opposite. Once in a while, make yourself think "Is A really required to do B?". Many assumptions are believed to be true. But are they really? A concrete example: "At work we only use the programming language L and framework F" and therefore, it is the standard we must use.</span><br />
<br />
<span>Another way to think about it is "Is there an alternative way to accomplish the desired result? What if there were no programming language L and framework F? What would I do instead?". Maybe you would use programming language X to implement your own domain-specific language, which does what framework F would have done but in exactly the way you want to + much more flexible than F! And maybe language X would be much better suitable than L to implement a DSL anyway. Conclusion: It never hurts to verify your assumptions.</span><br />
<br />
<span>Often, you will also find solutions to problems you never intended to solve and find new problems you never imagined to actually exist. That might not be a bad thing, but it might sidetrack you on your path to finding a solution for a particular problem. So be careful not to get sidetracked too much. In this case, just save a note for later reference (maybe your next Pet Project?) somewhere and go on with your actual problem.</span><br />
<br />
<span>Don&#39;t be afraid to think about weird and unconventional solutions. Sometimes, the most unconventional solution is the best solution to a problem. Also, try to keep to the basics. The best solutions are KISS.</span><br />
<br />
<a class='textlink' href='./2021-09-12-keep-it-simple-and-stupid.html'>Keep it simple and stupid</a><br />
<br />
<span>A small additional trick: you can train yourself to generate new and unconventional ideas. Just write down 20 random ideas every day. It doesn&#39;t matter what the ideas are about and whether they are useful or not. The purpose of this exercise is to make your brain think about something new and unconventional. These can be absurd ideas such as "Jump out of the window naked in the morning in order to wake up faster". Of course, you would never do that, but at least you had an idea and made your brain generate something.</span><br />
<br />
<h3 style='display: inline'>Don&#39;t be busy all the time</h3><br />
<br />
<span>Especially as a DevOps Engineer, you could be busy all the time with small, but frequent, ad hoc tasks. Don&#39;t lose yourself here. Yes, you should pay attention to your job and those tasks, but you should also make some room for creativity. Don&#39;t schedule meeting after ad hoc work after meeting after Jira ticket work after another Jira ticket. There should also be some "free" space in your calendar.</span><br />
<br />
<span>Use the "free" time to play around with your tech stack. Try out new options, explore the system metrics, explore new tools, etc. Dividends will pay off with new ideas, which you would have never come up with if you were "just busy" like a machine.</span><br />
<br />
<span>Sometimes, I pick a Unix manual page of a random command and start reading it. I have a bash helper function which will pick one for me:</span><br />
<br />
<pre>
❯ where learn
learn () {
  man $(ls /bin /sbin /usr/bin /usr/sbin 2&gt;/dev/null | shuf -n 1) |
    sed -n "/^NAME/ { n;p;q }"
}
❯ learn
       perltidy - a perl script indenter and reformatter
❯ learn
       timedatectl - Control the system time and date
</pre>
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>This all summarises advice I have, really.  I hope this was interesting and helpful for you.</span><br />
<br />
<span>I have one more small tip: I never published a blog post the same day I wrote it. After finishing writing it, I always wait for a couple of days. In all cases so far, I had an additional idea to add or to fine tune the blog post.</span><br />
<br />
<span>Another article I found interesting and relevant is</span><br />
<br />
<a class='textlink' href='https://thesephist.com/posts/paradise/'>Creative Paradise by The Sephist</a><br />
<br />
<span>Relevant books I can recommend are:</span><br />
<br />
<ul>
<li>Consciousness: A Very Short Introduction; Susan Blackmore; Oxford Uiversity Press</li>
<li>Deep Work; Cal Newport; Piatkus</li>
<li>So Good They Can&#39;t Ignore You; Cal Newport; Business Plus</li>
<li>The Off Switch; Mark Cropley; Virgin Books</li>
<li>Ultralearning; Scott Young; Thorsons</li>
</ul><br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>The release of DTail 4.0.0</title>
        <link href="gemini://foo.zone/gemfeed/2022-03-06-the-release-of-dtail-4.0.0.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-03-06-the-release-of-dtail-4.0.0.gmi</id>
        <updated>2022-03-06T18:11:39+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I have recently released DTail 4.0.0 and this blog post goes through all the new goodies. If you want to jump directly to DTail, do it here (there are nice animated gifs which demonstrates the usage pretty well):</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>The release of DTail 4.0.0</h1><br />
<br />
<span class='quote'>Published at 2022-03-06T18:11:39+00:00</span><br />
<br />
<pre>
                              ,_---~~~~~----._
                        _,,_,*^____      _____``*g*\"*,
  ____ _____     _ _   / __/ /&#39;     ^.  /      \ ^@q   f
 |  _ \_   _|_ _(_) |   @f | @))    |  | @))   l  0 _/
 | | | || |/ _` | | |  \`/   \~____ / __ \_____/    \
 | |_| || | (_| | | |   |           _l__l_           I
 |____/ |_|\__,_|_|_|   }          [______]           I
                        ]            | | |            |
                        ]             ~ ~             |
                        |                            |
                         |                           |
</pre>
<br />
<span>I have recently released DTail 4.0.0 and this blog post goes through all the new goodies. If you want to jump directly to DTail, do it here (there are nice animated gifs which demonstrates the usage pretty well):</span><br />
<br />
<a class='textlink' href='https://dtail.dev'>https://dtail.dev</a><br />
<br />
<h2 style='display: inline'>So, what&#39;s new in 4.0.0?</h2><br />
<br />
<h3 style='display: inline'>Rewritten logging</h3><br />
<br />
<span>For DTail 4, logging has been completely rewritten. The new package name is "internal/io/dlog". I rewrote the logging because DTail is a special case here: There are logs processed by DTail, there are logs produced by the DTail server itself, there are logs produced by a DTail client itself, there are logs only logged by a DTail client, there are logs only logged by the DTail server, and there are logs logged by both, server and client. There are also different logging levels and outputs involved.</span><br />
<br />
<span>As you can imagine, it becomes fairly complex. There is no ready Go off-shelf logging library which suits my needs and the logging code in DTail 3 was just one big source code file with global variables and it wasn&#39;t sustainable to maintain anymore. So why not rewrite it for profit and fun? </span><br />
<br />
<span>There&#39;s a are new log level structure now (The log level now can be specified with the "-logLevel" command line flag):</span><br />
<br />
<pre>
// Available log levels.
const (
	None    level = iota
	Fatal   level = iota
	Error   level = iota
	Warn    level = iota
	Info    level = iota
	Default level = iota
	Verbose level = iota
	Debug   level = iota
	Devel   level = iota
	Trace   level = iota
	All     level = iota
)
</pre>
<br />
<span>DTail also supports multiple log outputs (e.g. to file or to stdout). More are now easily pluggable with the new logging package. The output can also be "enriched" (default) or "plain" (read more about that further below).</span><br />
<br />
<h3 style='display: inline'>Configurable terminal color codes</h3><br />
<br />
<span>A complaint I received from the users of DTail 3 were the terminal colors used for the output. Under some circumstances (terminal configuration) it made the output difficult to read so that users defaulted to "--noColor" (disabling colored output completely). I toke it by heart and also rewrote the color handling. It&#39;s now possible to configure the foreground and background colors and an attribute (e.g. dim, bold, ...).</span><br />
<br />
<span>The example "dtail.json" configuration file represents the default (now, more reasonable default) color codes used, and it is free to the user to customize them:</span><br />
<br />
<pre>
{
  "Client": {
    "TermColorsEnable": true,
    "TermColors": {
      "Remote": {
        "DelimiterAttr": "Dim",
        "DelimiterBg": "Blue",
        "DelimiterFg": "Cyan",
        "RemoteAttr": "Dim",
        "RemoteBg": "Blue",
        "RemoteFg": "White",
        "CountAttr": "Dim",
        "CountBg": "Blue",
        "CountFg": "White",
        "HostnameAttr": "Bold",
        "HostnameBg": "Blue",
        "HostnameFg": "White",
        "IDAttr": "Dim",
        "IDBg": "Blue",
        "IDFg": "White",
        "StatsOkAttr": "None",
        "StatsOkBg": "Green",
        "StatsOkFg": "Black",
        "StatsWarnAttr": "None",
        "StatsWarnBg": "Red",
        "StatsWarnFg": "White",
        "TextAttr": "None",
        "TextBg": "Black",
        "TextFg": "White"
      },
      "Client": {
        "DelimiterAttr": "Dim",
        "DelimiterBg": "Yellow",
        "DelimiterFg": "Black",
        "ClientAttr": "Dim",
        "ClientBg": "Yellow",
        "ClientFg": "Black",
        "HostnameAttr": "Dim",
        "HostnameBg": "Yellow",
        "HostnameFg": "Black",
        "TextAttr": "None",
        "TextBg": "Black",
        "TextFg": "White"
      },
      "Server": {
        "DelimiterAttr": "AttrDim",
        "DelimiterBg": "BgCyan",
        "DelimiterFg": "FgBlack",
        "ServerAttr": "AttrDim",
        "ServerBg": "BgCyan",
        "ServerFg": "FgBlack",
        "HostnameAttr": "AttrBold",
        "HostnameBg": "BgCyan",
        "HostnameFg": "FgBlack",
        "TextAttr": "AttrNone",
        "TextBg": "BgBlack",
        "TextFg": "FgWhite"
      },
      "Common": {
        "SeverityErrorAttr": "AttrBold",
        "SeverityErrorBg": "BgRed",
        "SeverityErrorFg": "FgWhite",
        "SeverityFatalAttr": "AttrBold",
        "SeverityFatalBg": "BgMagenta",
        "SeverityFatalFg": "FgWhite",
        "SeverityWarnAttr": "AttrBold",
        "SeverityWarnBg": "BgBlack",
        "SeverityWarnFg": "FgWhite"
      },
      "MaprTable": {
        "DataAttr": "AttrNone",
        "DataBg": "BgBlue",
        "DataFg": "FgWhite",
        "DelimiterAttr": "AttrDim",
        "DelimiterBg": "BgBlue",
        "DelimiterFg": "FgWhite",
        "HeaderAttr": "AttrBold",
        "HeaderBg": "BgBlue",
        "HeaderFg": "FgWhite",
        "HeaderDelimiterAttr": "AttrDim",
        "HeaderDelimiterBg": "BgBlue",
        "HeaderDelimiterFg": "FgWhite",
        "HeaderSortKeyAttr": "AttrUnderline",
        "HeaderGroupKeyAttr": "AttrReverse",
        "RawQueryAttr": "AttrDim",
        "RawQueryBg": "BgBlack",
        "RawQueryFg": "FgCyan"
      }
    }
  },
  ...
}
</pre>
<br />
<span>You notice the different sections - these are different contexts:</span><br />
<br />
<ul>
<li>Remote: Color configuration for all log lines sent remotely from the server to the client. </li>
<li>Client: Color configuration for all lines produced by a DTail client by itself (e.g. status information).</li>
<li>Server: Color configuration for all lines produced by the DTail server by itself and sent to the client (e.g. server warnings or errors)</li>
<li>MaprTable: Color configuration for the map-reduce table output.</li>
<li>Common: Common color configuration used in various places (e.g. when it&#39;s not clear what&#39;s the current context of a line).</li>
</ul><br />
<span>When you do so, make sure that you check your "dtail.json" against the JSON schema file. This is to ensure that you don&#39;t configure an invalid color accidentally (requires "jsonschema" to be installed on your computer). Furthermore, the schema file is also a good reference for all possible colors available:</span><br />
<br />
<pre>
jsonschema -i dtail.json schemas/dtail.schema.json
</pre>
<br />
<h3 style='display: inline'>Serverless mode</h3><br />
<br />
<span>All DTail commands can now operate on log files (and other text files) directly without any DTail server running. So there isn&#39;t a need anymore to install a DTail server when you are on the target server already anyway, like the following example shows:</span><br />
<br />
<pre>
% dtail --files /var/log/foo.log
</pre>
<br />
<span>or</span><br />
<br />
<pre>
% dmap --files /var/log/foo.log --query &#39;from TABLE select .... outfile result.csv&#39;
</pre>
<br />
<span>The way it works in Go code is that a connection to a server is managed through an interface and in serverless mode DTail calls through that interface to the server code directly without any TCP/IP and SSH connection made in the background. This means, that the binaries are a bit larger (also ship with the code which normally would be executed by the server) but the increase of binary size is not much.</span><br />
<br />
<h3 style='display: inline'>Shorthand flags</h3><br />
<br />
<span>The "--files" from the previous example is now redundant. As a shorthand, It is now possible to do the following instead:</span><br />
<br />
<pre>
% dtail /var/log/foo.log
</pre>
<br />
<span>Of course, this also works with all other DTail client commands (dgrep, dcat, ... etc).</span><br />
<br />
<h3 style='display: inline'>Spartan (aka plain) mode</h3><br />
<br />
<span>There&#39;s a plain mode, which makes DTail only print out the "plain" text of the files operated on (without any DTail specific enriched output). E.g.:</span><br />
<br />
<pre>
% dcat --plain /etc/passwd &gt; /etc/test
% diff /etc/test /etc/passwd  # Same content, no diff
</pre>
<br />
<span>This might be useful if you wanted to post-process the output. </span><br />
<br />
<h3 style='display: inline'>Standard input pipe</h3><br />
<br />
<span>In serverless mode, you might want to process your data in a pipeline. You can do that now too through an input pipe:</span><br />
<br />
<pre>
% dgrep --plain --regex &#39;somethingspecial&#39; /var/log/foo.log |
    dmap --query &#39;from TABLE select .... outfile result.csv&#39;
</pre>
<br />
<span>Or, use any other "standard" tool:</span><br />
<br />
<pre>
% awk &#39;.....&#39; &lt; /some/file | dtail ....
</pre>
<br />
<h3 style='display: inline'>New command dtailhealth</h3><br />
<br />
<span>Prior to DTail 4, there was a flag for the "dtail" command to check the health of a remote DTail server (for use with monitoring system such as Nagios). That has been moved out to a separate binary to reduce complexity of the "dtail" command. The following checks whether DTail is operational on the current machine (you could also check a remote instance of DTail server, just adjust the server address).</span><br />
<br />
<pre>
% cat check_dtail.sh
#!/bin/sh

exec /usr/local/bin/dtailhealth --server localhost:2222
</pre>
<br />
<h3 style='display: inline'>Improved documentation</h3><br />
<br />
<span>Some features, such as custom log formats and the map-reduce query language, are now documented. Also, the examples have been updated to reflect the new features added. This also includes the new animated example Gifs (plus documentation how they were created).</span><br />
<br />
<span>I must admit that not all features are documented yet:</span><br />
<br />
<ul>
<li>Server side scheduled map-reduce queries</li>
<li>Server side continuous map-reduce queries</li>
<li>Some more docs about terminal color customization</li>
<li>Some more docs about log levels</li>
</ul><br />
<span>That will be added in one of the future releases. </span><br />
<br />
<h3 style='display: inline'>Integration testing suite</h3><br />
<br />
<span>DTail comes already with some unit tests, but what&#39;s new is a full integration testing suite which covers all common use cases of all the commands (dtail, dcat, dgrep, dmap) with a server backend and also in serverless mode.</span><br />
<br />
<span>How are the tests implemented? All integration tests are simply unit tests in the "./integrationtests" folder. They must be explicitly activated with:</span><br />
<br />
<pre>
% export DTAIL_INTEGRATION_TEST_RUN_MODE=yes
</pre>
<br />
<span>Once done, first compile all commands, and then run the integration tests:</span><br />
<br />
<pre>
% make
.
.
.
% go clean -testcache
% go test -race -v ./integrationtests
</pre>
<br />
<h3 style='display: inline'>Improved code</h3><br />
<br />
<span>Not that the code quality of DTail has been bad (I have been using Go vet and Go lint for previous releases and will keep using these), but this time I had new tools (such as SonarQube and BlackDuck) in my arsenal to:</span><br />
<br />
<ul>
<li>Reduce the complexity of a couple of functions (splitting code up into several smaller functions)</li>
<li>Avoid repeating code (this version of DTail doesn&#39;t use Go generics yet, though).</li>
</ul><br />
<span>Other than that, a lot of other code has been refactored as I saw fit.</span><br />
<br />
<h3 style='display: inline'>Use of memory pools</h3><br />
<br />
<span>DTail makes excessive use of string builder and byte buffer objects. For performance reasons, those are now re-used from memory pools.</span><br />
<br />
<h2 style='display: inline'>What&#39;s next</h2><br />
<br />
<span>DTail 5 won&#39;t be released any time soon I guess, but some 4.x.y releases will follow this year fore sure. I can think of:</span><br />
<br />
<ul>
<li>New (but backwards compatible) features which don&#39;t require a new major version bump (some features have been requested at work internally).</li>
<li>Even more improved documentation.</li>
<li>Dependency updates.</li>
</ul><br />
<span>I use usually DTail at work, but I have recently installed it on my personal OpenBSD machines too. I might write a small tutorial here (and I might also add the rc scripts as examples to one of the next DTail releases).</span><br />
<br />
<span>I am a bit busy at the moment with two other pet projects of mine (one internal work-project, and one personal one, the latter you will read about in the next couple of months). If you have ideas (or even a patch), then please don&#39;t hesitate to contact me (either via E-Mail or a request at GitHub).</span><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-10-30-installing-dtail-on-openbsd.html'>2022-10-30 Installing DTail on OpenBSD</a><br />
<a class='textlink' href='./2022-03-06-the-release-of-dtail-4.0.0.html'>2022-03-06 The release of DTail 4.0.0 (You are currently reading this)</a><br />
<a class='textlink' href='./2021-04-22-dtail-the-distributed-log-tail-program.html'>2021-04-22 DTail - The distributed log tail program</a><br />
<br />
<span>Thanks!</span><br />
<br />
<span>Paul</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Computer operating systems I use(d)</title>
        <link href="gemini://foo.zone/gemfeed/2022-02-04-computer-operating-systems-i-use.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-02-04-computer-operating-systems-i-use.gmi</id>
        <updated>2022-02-04T09:58:22+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This is a list of Operating Systems I currently use. This list is in no particular order and also will be updated over time. The very first operating system I used was MS-DOS (mainly for games) and the very first Unix like operating system I used was SuSE Linux 5.3. My first smartphone OS was Symbian on a clunky Sony Ericsson device.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Computer operating systems I use(d)</h1><br />
<br />
<span class='quote'>Published at 2022-02-04T09:58:22+00:00; Updated at 2022-02-18</span><br />
<br />
<pre>
              /(        )`
              \ \___   / |
              /- _  `-/  &#39;
             (/\/ \ \   /\
             / /   | `    \
             O O   ) /    |
             `-^--&#39;`&lt;     &#39;
            (_.)  _  )   /
             `.___/`    /
               `-----&#39; /
  &lt;----.     __ / __   \
  &lt;----|====O)))==) \) /====
  &lt;----&#39;    `--&#39; `.__,&#39; \
               |        |
                \       /
           ______( (_  / \______
  (FL)   ,&#39;  ,-----&#39;   |        \
         `--{__________)        \/   "Berkeley Unix Daemon"
</pre>
<br />
<span>This is a list of Operating Systems I currently use. This list is in no particular order and also will be updated over time. The very first operating system I used was MS-DOS (mainly for games) and the very first Unix like operating system I used was SuSE Linux 5.3. My first smartphone OS was Symbian on a clunky Sony Ericsson device.</span><br />
<br />
<h2 style='display: inline'>Fedora Linux</h2><br />
<br />
<span>Fedora Linux is the operating system I use on my primary (personal) laptop. It&#39;s a ThinkPad X1 Carbon Gen. 9. Lenovo which comes along with official Lenovo Linux support. I already noticed hardware firmware updates being installed directly through Fedora from Lenovo. Fedora is a real powerhouse, cutting-edge and reasonably stable at the same time. It&#39;s baked by Red Hat.</span><br />
<br />
<span>I also use Fedora on my Microsoft Surface Go 2 convertible tablet. Fedora works quite OK (and much better than Windows) on this device. It&#39;s also the perfect travel companion.</span><br />
<br />
<span>I use the GNOME Desktop on my Fedora boxes. I have memorized and customized a bunch of keyboard shortcuts. But the fact that I mostly work in the terminal (with tmux) makes the Desktop environment I use only secondary.</span><br />
<br />
<h2 style='display: inline'>EndeavourOS</h2><br />
<br />
<span>I installed EndeavourOS on my (older) ThinkPad X240 to try out an Arch based Linux distribution. I also could have installed plain Arch, but I don&#39;t see the point when there is EndeavourOS. EndeavourOS is as close as you can get to the plain Arch experience but with an easy installer. I am not saying that it&#39;s difficult to install plain Arch but it&#39;s, unless you are new to Linux and want to learn about the installation procedure, just waste of time in my humble opinion. Give Linux From Scratch a shot instead if you really want to learn about Linux.</span><br />
<br />
<a class='textlink' href='https://www.linuxfromscratch.org/'>https://www.linuxfromscratch.org/</a><br />
<br />
<span>On EndeavourOS, I use the Xfce desktop environment which feels very snappy and fast on the X240 (which I purchased back in 2014). Usually, I have my X240 standing right next to my work laptop and use it for playing music (mainly online radio streams), for personal note taking and occasional emailing and instant messaging.</span><br />
<br />
<span>As this is a rolling Linux distribution there are a lot of software updates coming through every day. Sometimes, it only takes a minute until the next version of a package is available. Honestly, I find that a bit annoying to constantly catch up with all the updates. As for now I will live with it and/or automate it a bit more. It&#39;ll be OK if it breaks occasionally, as this is not my primary laptop anyway. </span><br />
<br />
<span>Arch Linux and EndeavourOS are community distributions. This means, that there is no big corporation in the backyard lurking around. They won&#39;t give you the firmware updates for cutting edge hardware out of the box, though, but they are still a very good choice for hobbyist and also for older hardware where future firmware updates are less likely to happen.</span><br />
<br />
<span>I am very happy with the package availability through the official repository and AUR.</span><br />
<br />
<a class='textlink' href='https://endeavouros.com/'>https://endeavouros.com/</a><br />
<br />
<h2 style='display: inline'>FreeBSD</h2><br />
<br />
<span>I have run FreeBSD in many occasions. Right after SuSE Linux, FreeBSD (around 4.x) was the second open source system I used in my life on regular basis. I didn&#39;t even go to university yet then I started using it :-). Also, a former employer of mine even allowed me to install FreeBSD on my main workstation (which I actually did and used it for a couple of years). </span><br />
<br />
<span>I remember it used to be a pain bootstrapping Java for FreeBSD due to the lack of pre-compiled binary packages. You had first to enable the Linux compatibility layer, then install Linux Java, and then compile FreeBSD Java with the bootstrapped Linux Java (yes, Java is mainly programmed in C++, but for some reason compiling Java for FreeBSD also required an installation of Java). Nowadays, there are ready OpenJDK binary packages you could install. So things have improved a lot since.</span><br />
<br />
<span>FreeBSD always had a place somewhere in my life:</span><br />
<br />
<ul>
<li>On a Desktop PC (personal and work)</li>
<li>On a Laptop</li>
<li>On a webserver, FTP server, DNS server, mail server</li>
<li>On a server offering FreeBSD jails to customers for rent</li>
<li>As an experiment running Debian GNU/kFreeBSD inside of jails</li>
</ul><br />
<span>Debian GNU/kFreeBSD is now dead (same is my experiment)...</span><br />
<br />
<a class='textlink' href='https://www.debian.org/ports/kfreebsd-gnu/'>https://www.debian.org/ports/kfreebsd-gnu/</a><br />
<br />
<span>...but I still have saved and old uname output :-):</span><br />
<br />
<pre>
[root@saturn /usr/jail/serv14/etc] # jexec 21 bash
root@rhea:/ # uname -a
GNU/kFreeBSD rhea.buetow.org 8.0-RELEASE-p5 FreeBSD 8.0-RELEASE-p5 #2: Sat Nov 27 13:10:09 CET
  2010 root@saturn.buetow.org:/usr/obj/usr/srcs/freebsd.src8/src/sys/SERV10 x86 64 amd64 Intel(R)
  Core(TM) i7 CPU 920 @ 2.67GHz GNU/kFreeBSD
</pre>
<br />
<span>Currently, I use FreeBSD on my personal NAS server. The server is a regular PC with a bunch of hard drives and a ZFS RAIDZ (with 4x2TB drives) + a couple of external backup drives.</span><br />
<br />
<a class='textlink' href='https://www.FreeBSD.org'>https://www.FreeBSD.org</a><br />
<br />
<h2 style='display: inline'>CentOS 7</h2><br />
<br />
<span>While CentOS 8 is already out of support, I still use CentOS 7 (which will receive security updates until 2024). CentOS 7 runs in a cloud VM and is the home to my personal NextCloud and Wallabag installations. You probably know already NextCloud. About Wallabag: It is a great free and open source alternative to Pocket (for reading articles from the web offline later). Yes, you can pay for a Wallabag subscription, but you can also host it for free on your own server.</span><br />
<br />
<a class='textlink' href='https://nextcloud.com'>NextCloud</a><br />
<a class='textlink' href='https://www.wallabag.it/en'>Wallabag</a><br />
<br />
<span>The reason I use Linux and not *BSD at the moment for these services is Docker. With Docker, it&#39;s so easy-peasy to get these up and running. I will have to switch to another OS before CentOS 7 runs out of support, though. It might be CentOS Stream, Rocky Linux, or, more likely, I will use FreeBSD. On FreeBSD there isn&#39;t Docker, but what can be done is to create a self-contained Jail for each of the web-apps. </span><br />
<br />
<span>I have been using FreeBSD Jails for LAMP stacks before I started using CentOS. The reason why I switched to CentOS (it was still CentOS 6 at that time) in the first place was, that I wanted to try out something new.</span><br />
<br />
<a class='textlink' href='https://www.centos.org'>https://www.centos.org</a><br />
<br />
<h2 style='display: inline'>OpenBSD</h2><br />
<br />
<span>I use two small OpenBSD "cloud" boxes for my "public facing internet front-ends". The services I run here are:</span><br />
<br />
<ul>
<li>HTTP server (serving this site via https://foo.zone)</li>
<li>Gemini server (serving this site via gemini://foo.zone)</li>
<li>MTA server (for receiving E-Mails to my hosts)</li>
<li>Authorative DNS server (for all of my "domains")</li>
<li>Some personal/private git repositories (accessible only via SSH)</li>
</ul><br />
<span>OpenBSD is a complete operating system. I love it due to it&#39;s "simplicity" and "correctness" and the good documentation (I love the manual pages in particular). OpenBSD is also known for its innovations in security. I must admin, though, that most Unix like operating system would be secure enough for my personal needs and that I don&#39;t really need to use OpenBSD here. But nevertheless, I think it&#39;s the ideal operating system for what I am using it for.</span><br />
<br />
<span>The only softwares which were not part of the base system and I had to install additionally were the Gemini server (vger) and Git, which both were available as pre-compiled OpenBSD binary packages. So, besides of these two packages, it is indeed a pretty complete operating system for my use case.</span><br />
<br />
<a class='textlink' href='https://www.openbsd.org'>https://www.openbsd.org</a><br />
<br />
<h2 style='display: inline'>macOS (proprietary)</h2><br />
<br />
<span>I have to use a MacBook Pro with macOS for work. What else can I say but that this would have never been my personal choice. At least macOS is a UNIX under the hood and comes with a decent terminal and there are plenty of terminal apps available via Brew. Some of the inner workings of macOS were actually forked from the FreeBSD project. </span><br />
<br />
<a class='textlink' href='https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/BSD/BSD.html'>developer.apple.com: BSD in macOS/Darwin</a><br />
<br />
<span>I find the macOS UI rather confusing.</span><br />
<br />
<h2 style='display: inline'>LineageOS (mobile)</h2><br />
<br />
<span>At some point I got fed up with big tech, like Google and Samsung (or Apple, but personally I don&#39;t use Apple), spying on me. So I purchased a Google phone (a midrange Pixel phone) and installed LineageOS, a free and open source distribution of Android, on it. I don&#39;t have anything from Google installed on it (not even the play store, I install my apps from F-Droid). It&#39;s my daily driver since mid 2021 now. </span><br />
<br />
<span>So far the experience is not great but good. The main culprits are not having Google Maps, Google Gboard and the camera app. The latter lacks some features on LineageOS (e.g. No wide angle lens support). Also, I can&#39;t use my banking apps anymore. Sometimes apps crash for no apparent reason(s) but I get around it so far. I shouldn&#39;t spend so much time on my smartphone anyway! And the whole point of switching to LineageOS was to get away of big tech and therefore I should not complain :-). What I do like is that 95% the things I used to do on a proprietary mobile phone also can be done with LineageOS.</span><br />
<br />
<a class='textlink' href='./2021-08-01-on-being-pedantic-about-open-source.html'>Read also "The Midle Way" section of this blog post regarding smartphones.</a><br />
<br />
<span>There&#39;s also the excellent Termux app in the F-Droid store, which transforms the phone into a small Linux handheld device. I am able to run all of my Linux/Unix terminal apps with it.</span><br />
<br />
<a class='textlink' href='https://lineageos.org/'>https://lineageos.org/</a><br />
<a class='textlink' href='https://termux.com/'>https://termux.com/</a><br />
<br />
<h2 style='display: inline'>Samsung&#39;s Stock Android (mobile proprietary)</h2><br />
<br />
<span>Unfortunatley, I still have to keep my proprietary Android phone around. Sometimes, I really need to use some proprietary apps which are only available form the Google play store and also require the Google services installed on the phone. I don&#39;t carry this phone around all the time and I only use it intentionally for very specific use cases. I think this is the best compromise I can make.</span><br />
<br />
<h2 style='display: inline'>iOS (mobile proprietary)</h2><br />
<br />
<span>I have to use an iPhone for work. I like the hardware but I hate the OS (you can also call it spyOS), but it&#39;s the necessarries evil, unfortunately. Apple is even worse than Google here (despite claiming for themselves to produce the most secure phone(s)). I don&#39;t have it with me all the time or switched off when I don&#39;t need it. I also find iOS quite unintuitive to use.</span><br />
<br />
<span>Being on-call for work means to to be reachable 24/7. This implies that the phone is carried around all the time (in an switched-on state). 1984 is now.</span><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Nineteen_Eighty-Four'>https://en.wikipedia.org/wiki/Nineteen_Eighty-Four</a><br />
<br />
<h2 style='display: inline'>Other OSes</h2><br />
<br />
<h3 style='display: inline'>InfinyTime (smartwatch)</h3><br />
<br />
<span>I use it on my PineTime smartwatch. Other than checking the time and my step count, I really don&#39;t do anything else fancy with it (yet). </span><br />
<br />
<a class='textlink' href='https://www.pine64.org/pinetime/'>https://www.pine64.org/pinetime/</a><br />
<a class='textlink' href='https://infinitime.io/'>https://infinitime.io/</a><br />
<br />
<h3 style='display: inline'>motionEyeOS</h3><br />
<br />
<span>I usually install an army of RaspberryPi 3&#39;s in my house before I travel for a prolonged amount of time. All Pi&#39;s are equipped with an camera and have motionEyeOS (Linux based video surveillance system) installed. There&#39;s a neat Android app in the F-Droid store which let&#39;s me keep an eye on everything. I make the Pi&#39;s accessible from the internet via reverse SSH tunnels through one of my frontend servers.</span><br />
<br />
<a class='textlink' href='https://github.com/ccrisan/motioneyeos'>https://github.com/ccrisan/motioneyeos</a><br />
<br />
<h3 style='display: inline'>Kobo OS (proprietary)</h3><br />
<br />
<span>I use a Kobo Forma as my e-reader device. I have started to switch off the Wifi and to only sideload DRM free ePubs on it. Even offline, it&#39;s a fully capable reader device. I wouldn&#39;t like the Kobo to call home to Rakuten. I would love to replace it one day with an open source e-reader alternative like the PineNote. There are also some interesting attempts installing postmarketOS Linux on Kobo devices. The latter boots already, but is far from being usable as a normal e-reader.</span><br />
<br />
<a class='textlink' href='https://www.pine64.org/pinenote/'>The PineNote</a><br />
<a class='textlink' href='https://liliputing.com/2021/07/kobo-clara-hd-becomes-an-e-ink-linux-tablet-with-the-help-of-postmarketos.html'>Kobo Clara HD becomes an e-ink Linux tablet</a><br />
<br />
<span>But as a fall-back, someone could still use the good old dead tree format!</span><br />
<br />
<h3 style='display: inline'>Android TV (proprietary)</h3><br />
<br />
<span>An Android TV box is used for watching movies and series on Netflix and Amazon Prime video (yes, I am human too and rely once in a while on big tech streaming services). The Android TV box is currently in the process of being replaced by OSMC, though. Most services seem to work fine with OSMC, but didn&#39;t get around tinkering with Netflix and Amazon there yet.</span><br />
<br />
<a class='textlink' href='https://osmc.tv/'>https://osmc.tv/</a><br />
<br />
<h2 style='display: inline'>Other OSes..</h2><br />
<br />
<span>This section is just for the sake of having a complete list of all OSes I used for some significant amount of time. I might not use all of them any more...</span><br />
<br />
<h3 style='display: inline'>NetBSD</h3><br />
<br />
<span>I have been using NetBSD on an old Sun Sparcstation 10 as a student. I also have run NetBSD on a very old ThinkPad with 96MB!!! of RAM (even with X/evilWM). I also installed (but never really used) NetBSD on an HP Jornada 680. But that&#39;s all more than 10 years ago. I haven&#39;t looked at NetBSD for long time. I want to revive it on an "old" ThinkPad T450 of mine which I currently don&#39;t use.</span><br />
<br />
<a class='textlink' href='https://netbsd.org'>https://netbsd.org</a><br />
<br />
<h3 style='display: inline'>Other OSes in use...</h3><br />
<br />
<a class='textlink' href='https://sailfish.org'>SailfishOS - Nice mobile OS, but unfortunately includes proprietary components</a><br />
<a class='textlink' href='https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux'>Red Hat Enterprose Linux - Only for some work stuff</a><br />
<br />
<h3 style='display: inline'>Other OSes not used any more...</h3><br />
<br />
<a class='textlink' href='https://en.opensuse.org/Archive:S.u.S.E._Linux_5.3'>SuSE Linux 5.3 - The first Linux OS I used</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/IRIX'>SGI&#39;s IRIX - On a SGI Onyx 3200</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/MeeGo'>MeeGo - On a Nokia N9</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Microsoft_Windows'>Microsoft Windows</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/MS-DOS'>Microsoft DOS - With and without Windows 3.x</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Symbian'>Symbian - The first smartphone OS I used </a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Wear_OS'>WearOS - On a Google smartwatch</a><br />
<a class='textlink' href='https://www.debian.org'>Debian GNU/Linux - Rock solid, but atm. I prefer Fedora/EndeavourOS</a><br />
<a class='textlink' href='https://www.ubuntu.com'>Ubuntu Linux (based on Debian)</a><br />
<a class='textlink' href='https://www.linuxfromscratch.org/'>Linux from scratch - The best way to learn Linux</a><br />
<a class='textlink' href='https://www.suse.com/products/server/'>SUSE Linux Enterprise - Only for some work stuff</a><br />
<br />
<h3 style='display: inline'>Other OSes I only had a glance at...</h3><br />
<br />
<a class='textlink' href='https://archiveos.org/opensolaris/'>OpenSolaris - Continuation of the open source version of Solaris</a><br />
<a class='textlink' href='https://archlinuxarm.org/'>Arch Linux ARM</a><br />
<a class='textlink' href='https://ecomstation.com/'>eComStation - Continuation of IBM OS/2</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Minix'>MINIX</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/OpenVMS'>OpenVMS</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/OS/2'>IBM OS/2 Warp</a><br />
<a class='textlink' href='https://freedos.org'>FreeDOS - Open source alternative to DOS</a><br />
<a class='textlink' href='https://plan9.io/plan9/'>Plan9 </a><br />
<a class='textlink' href='https://reactos.org/'>ReactOS - A Microsoft Windows open source clone</a><br />
<a class='textlink' href='https://www.debian.org/ports/hurd/'>Debian GNU/Hurd - Debian on the GNU kernel</a><br />
<a class='textlink' href='https://www.debian.org/ports/kfreebsd-gnu/'>Debian GNU/kFreeBSD - Debian on the FreeBSD kernel</a><br />
<a class='textlink' href='https://www.gentoo.org'>Gentoo Linux</a><br />
<a class='textlink' href='https://www.haiku-os.org/'>Haiku - A BeOS open source clone</a><br />
<a class='textlink' href='https://www.oracle.com/solaris/solaris11/'>Sun Solaris (now owned by Oracle)</a><br />
<a class='textlink' href='https://www.puredarwin.org/'>OpenDarwin ("now" PureDarwin) - Open source operating system based on the open parts of macOS</a><br />
<br />
<h3 style='display: inline'>Other OSes which seem interesting...</h3><br />
<br />
<a class='textlink' href='https://asteroidos.org/'>Asteroids OS - Open source smartphone OS</a><br />
<a class='textlink' href='https://www.dragonflybsd.org/'>DragonFly BSD - Fork of FreeBSD 4</a><br />
<a class='textlink' href='http://wiki.postmarketos.org/wiki/Phosh'>Phosh (on postmarketOS) - A true Linux shell for the smartphone</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Welcome to the foo.zone</title>
        <link href="gemini://foo.zone/gemfeed/2022-01-23-welcome-to-the-foo.zone.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-01-23-welcome-to-the-foo.zone.gmi</id>
        <updated>2022-01-23T16:42:04+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I don't count this as a real blog post, but more of an announcement (I aim to write one real post once monthly). From now on, 'foo.zone' is the new address of this site. All other addresses will still forward to it and eventually (based on the traffic still going through) will be deactivated.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Welcome to the foo.zone</h1><br />
<br />
<span class='quote'>Published at 2022-01-23T16:42:04+00:00</span><br />
<br />
<pre>
  __                                  
 / _| ___   ___   _______  _ __   ___ 
| |_ / _ \ / _ \ |_  / _ \| &#39;_ \ / _ \
|  _| (_) | (_) | / / (_) | | | |  __/
|_|  \___/ \___(_)___\___/|_| |_|\___|
                                      
</pre>
<br />
<span>I don&#39;t count this as a real blog post, but more of an announcement (I aim to write one real post once monthly). From now on, "foo.zone" is the new address of this site. All other addresses will still forward to it and eventually (based on the traffic still going through) will be deactivated.</span><br />
<br />
<span>As you can read on Wikipedia, "foo" is, alongside to "bar" and "baz", a metasyntactic variable (you know what I mean if you are a programmer or IT person):</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Metasyntactic_variable'>https://en.wikipedia.org/wiki/Metasyntactic_variable</a><br />
<br />
<h2 style='display: inline'>What is the foo zone?</h2><br />
<br />
<span>It&#39;s my personal internet site and blog. Everything you read on this site is my personal opinion and experience. It&#39;s not intended to be anything professional. If you want my professional background, then go to my LinkedIn profile.</span><br />
<br />
<span>Since I re-booted this blog last year, I struggled to find a good host name for it. I started off with "buetow.org", and later I switched halfway to "snonux.de". Buetow is my last name, and snonux relates to some of my internet nicknames and personal IT projects. I also have a "SnonuxBSD" ASCII-art banner in the motd of my FreeBSD based home-NAS.</span><br />
<br />
<span>For a while, I was thinking about a better host name for this site, meeting the following criteria:</span><br />
<br />
<ul>
<li>Isn&#39;t directly linked to my name or my internet nicknames.</li>
<li>Reflects the "nature" of this site.</li>
<li>Is still pretty generic.</li>
<li>Is "cool".</li>
<li>Is short and easy to remember. </li>
<li>Doesn&#39;t cost millions.</li>
</ul><br />
<span>So I think that foo.zone is the perfect match. It&#39;s a bit geeky, but so is this site. The meta-syntactic variable relates to computer science and programming, so does this site. Other than that, staying in this sphere, it&#39;s a pretty generic name.</span><br />
<br />
<h2 style='display: inline'>To be in the .zone and not in a .surf club</h2><br />
<br />
<span>I was pretty happy finding out that foo.zone was still available for registration. I stumbled across it just yesterday while I was playing around with my new authoritative DNS servers. I was actually quite surprised as usually such short SLDs (second level domains), especially "foo", are all taken already.</span><br />
<br />
<span>As a funny bit, I almost chose "foo.surf" over "foo.zone" as in "surfing this site", but then decided against it as I would have to tell everyone that I am not into water sports so much. Well, on the other hand, I now may have to explain to non-programmers that I am not a fan of the rock band "Foo Fighters". But that will be acceptable, as I don&#39;t expect "normal" people visiting the foo zone as much anyway. If you reached as far, I have to congratulate you. You are not a normal person.</span><br />
<br />
<h2 style='display: inline'>What about my old hosts</h2><br />
<br />
<span>The host buetow.org will stay. However, not as the primary address for this site. I will keep using it for my personal internet infrastructure as well as for most of my E-Mail addresses. I used buetow.org for that over the past 10 years already anyway and that won&#39;t change any time soon. I don&#39;t know what I am going to do with snonux.de in the long run. A .de SLD (for Germany) is pretty cheap, so I might just keep it for now. </span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Bash Golf Part 2</title>
        <link href="gemini://foo.zone/gemfeed/2022-01-01-bash-golf-part-2.gmi" />
        <id>gemini://foo.zone/gemfeed/2022-01-01-bash-golf-part-2.gmi</id>
        <updated>2022-01-01T23:36:15+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This is the second blog post about my Bash Golf series. This series is random Bash tips, tricks and weirdnesses I came across. It's a collection of smaller articles I wrote in an older (in German language) blog, which I translated and refreshed with some new content.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Bash Golf Part 2</h1><br />
<br />
<span class='quote'>Published at 2022-01-01T23:36:15+00:00; Updated at 2022-01-05</span><br />
<br />
<pre>
    &#39;\       &#39;\                   .  .                |&gt;18&gt;&gt;
      \        \              .         &#39; .           |
     O&gt;&gt;      O&gt;&gt;         .                 &#39;o        |
      \       .\. ..   .                              |
      /\    .  /\    . .                              |
     / /   .  / /  .&#39;    .                            |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                        Art by Joan Stark, mod. by Paul Buetow
</pre>
<br />
<span>This is the second blog post about my Bash Golf series. This series is random Bash tips, tricks and weirdnesses I came across. It&#39;s a collection of smaller articles I wrote in an older (in German language) blog, which I translated and refreshed with some new content.</span><br />
<br />
<a class='textlink' href='./2022-01-01-bash-golf-part-2.html'>2022-01-01 Bash Golf Part 2 (You are currently reading this)</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>2021-11-29 Bash Golf Part 1</a><br />
<br />
<h2 style='display: inline'>Redirection</h2><br />
<br />
<span>Let&#39;s have a closer look at Bash redirection. As you might already know that there are 3 standard file descriptors:</span><br />
<br />
<ul>
<li>0 aka stdin (standard input)</li>
<li>1 aka stdout (standard output)</li>
<li>2 aka stderr (standard error output)</li>
</ul><br />
<span>These are most certainly the ones you are using on regular basis. "/proc/self/fd" lists all file descriptors which are open by the current process (in this case: the current Bash shell itself):</span><br />
<br />
<pre>
❯ ls -l /proc/self/fd/
total 0
lrwx------. 1 paul paul 64 Nov 23 09:46 0 -&gt; /dev/pts/9
lrwx------. 1 paul paul 64 Nov 23 09:46 1 -&gt; /dev/pts/9
lrwx------. 1 paul paul 64 Nov 23 09:46 2 -&gt; /dev/pts/9
lr-x------. 1 paul paul 64 Nov 23 09:46 3 -&gt; /proc/162912/fd
</pre>
<br />
<span>The following examples demonstrate two different ways to accomplish the same thing. The difference is that the first command is directly printing out "Foo" to stdout and the second command is explicitly redirecting stdout to its own stdout file descriptor:</span><br />
<br />
<pre>
❯ echo Foo
Foo
❯ echo Foo &gt; /proc/self/fd/0
Foo
</pre>
<br />
<span>Other useful redirections are:</span><br />
<br />
<ul>
<li>Redirect stderr to stdin: "echo foo 2&gt;&amp;1"</li>
<li>Redirect stdin to stderr: "echo foo &gt;&amp;2"</li>
</ul><br />
<span>It is, however, not possible to redirect multiple times within the same command. E.g. the following won&#39;t work. You would expect stdin to be redirected to stderr and then stderr to be redirected to /dev/null. But as the example shows, Foo is still printed out:</span><br />
<br />
<pre>
❯ echo Foo 1&gt;&amp;2 2&gt;/dev/null
Foo
</pre>
<br />
<span class='quote'>Update: A reader sent me an email and pointed out that the order of the redirections is important. </span><br />
<br />
<span>As you can see, the following will not print out anything:</span><br />
<br />
<pre>
❯ echo Foo 2&gt;/dev/null 1&gt;&amp;2
❯
</pre>
<br />
<span>A good description (also pointed out by the reader) can be found here:</span><br />
<br />
<a class='textlink' href='https://wiki.bash-hackers.org/howto/redirection_tutorial#order_of_redirection_ie_file_2_1_vs_2_1_file'>Order of redirection</a><br />
<br />
<span>Ok, back to the original blog post. You can also use grouping here (neither of these commands will print out anything to stdout):</span><br />
<br />
<pre>
❯ { echo Foo 1&gt;&amp;2; } 2&gt;/dev/null
❯ ( echo Foo 1&gt;&amp;2; ) 2&gt;/dev/null
❯ { { { echo Foo 1&gt;&amp;2; } 2&gt;&amp;1; } 1&gt;&amp;2; } 2&gt;/dev/null
❯ ( ( ( echo Foo 1&gt;&amp;2; ) 2&gt;&amp;1; ) 1&gt;&amp;2; ) 2&gt;/dev/null
❯
</pre>
<br />
<span>A handy way to list all open file descriptors is to use the "lsof" command (that&#39;s not a Bash built-in), whereas $ is the process id (pid) of the current shell process:</span><br />
<br />
<pre>
❯ lsof -a -p $ -d0,1,2
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
bash    62676 paul    0u   CHR  136,9      0t0   12 /dev/pts/9
bash    62676 paul    1u   CHR  136,9      0t0   12 /dev/pts/9
bash    62676 paul    2u   CHR  136,9      0t0   12 /dev/pts/9
</pre>
<br />
<span>Let&#39;s create our own descriptor "3" for redirection to a file named "foo":</span><br />
<br />
<pre>
❯ touch foo
❯ exec 3&gt;foo # This opens fd 3 and binds it to file foo.
�� ls -l /proc/self/fd/3
l-wx------. 1 paul paul 64 Nov 23 10:10 \
    /proc/self/fd/3 -&gt; /home/paul/foo
❯ cat foo
❯ echo Bratwurst &gt;&amp;3
❯ cat foo
Bratwurst
❯ exec 3&gt;&amp;- # This closes fd 3.
❯ echo Steak &gt;&amp;3
-bash: 3: Bad file descriptor
</pre>
<br />
<span>You can also override the default file descriptors, as the following example script demonstrates:</span><br />
<br />
<pre>
❯ cat grandmaster.sh
#!/usr/bin/env bash

# Write a file data-file containing two lines
echo Learn You a Haskell &gt; data-file
echo for Great Good &gt;&gt; data-file

# Link fd with fd 6 (saves default stdin)
exec 6&lt;&amp;0

# Overwrite stdin with data-file
exec &lt; data-file

# Read the first two lines from it
declare LINE1 LINE2
read LINE1
read LINE2

# Print them
echo First line: $LINE1
echo Second line: $LINE2

# Restore default stdin and delete fd 6
exec 0&lt;&amp;6 6&lt;&amp;-
</pre>
<br />
<span>Let&#39;s execute it:</span><br />
<br />
<pre>
❯ chmod 750 ./grandmaster.sh
❯ ./grandmaster.sh
First line: Learn You a Haskell
Second line: for Great Good
</pre>
<br />
<h2 style='display: inline'>HERE</h2><br />
<br />
<span>I have mentioned HERE-documents and HERE-strings already in this post. Let&#39;s do some more examples. The following "cat" receives a multi line string from stdin. In this case, the input multi line string is a HERE-document. As you can see, it also interpolates variables (in this case the output of "date" running in a subshell).</span><br />
<br />
<pre>
❯ cat &lt;&lt;END
&gt; Hello World
&gt; It’s $(date)
&gt; END
Hello World
It&#39;s Fri 26 Nov 08:46:52 GMT 2021
</pre>
<br />
<span>You can also write it the following way, but that&#39;s less readable (it&#39;s good for an obfuscation contest):</span><br />
<br />
<pre>
❯ &lt;&lt;END cat
&gt; Hello Universe
&gt; It’s $(date)
&gt; END
Hello Universe
It&#39;s Fri 26 Nov 08:47:32 GMT 2021
</pre>
<br />
<span>Besides of an HERE-document, there is also a so-called HERE-string. Besides of...</span><br />
<br />
<pre>
❯ declare VAR=foo
❯ if echo "$VAR" | grep -q foo; then
&gt; echo &#39;$VAR ontains foo&#39;
&gt; fi
$VAR ontains foo
</pre>
<br />
<span>...you can use a HERE-string like that:</span><br />
<br />
<pre>
❯ if grep -q foo &lt;&lt;&lt; "$VAR"; then
&gt; echo &#39;$VAR contains foo&#39;
&gt; fi
$VAR contains foo
</pre>
<br />
<span>Or even shorter, you can do:</span><br />
<br />
<pre>
❯ grep -q foo &lt;&lt;&lt; "$VAR" &amp;&amp; echo &#39;$VAR contains foo&#39;
$VAR contains foo
</pre>
<br />
<span>You can also use a Bash regex to accomplish the same thing, but the points of the examples so far were to demonstrate HERE-{documents,strings} and not Bash regular expressions:</span><br />
<br />
<pre>
❯ if [[ "$VAR" =~ foo ]]; then echo yay; fi
yay
</pre>
<br />
<span>You can also use it with "read":</span><br />
<br />
<pre>
❯ read a &lt;&lt;&lt; ja
❯ echo $a
ja
❯ read b &lt;&lt;&lt; &#39;NEIN!!!&#39;
❯ echo $b
NEIN!!!
❯ dumdidumstring=&#39;Learn you a Golang for Great Good&#39;
❯ read -a words &lt;&lt;&lt; "$dumdidumstring"
❯ echo ${words[0]}
Learn
❯ echo ${words[3]}
Golang
</pre>
<br />
<span>The following is good for an obfuscation contest too:</span><br />
<br />
<pre>
❯ echo &#39;I like Perl too&#39; &gt; perllove.txt
❯ cat - perllove.txt &lt;&lt;&lt; "$dumdidumstring"
Learn you a Golang for Great Good
I like Perl too
</pre>
<br />
<h2 style='display: inline'>RANDOM</h2><br />
<br />
<span>Random is a special built-in variable containing a different pseudo random number each time it&#39;s used.</span><br />
<br />
<pre>
❯ echo $RANDOM
11811
❯ echo $RANDOM
14997
❯ echo $RANDOM
9104
</pre>
<br />
<span>That&#39;s very useful if you want to randomly delay the execution of your scripts when you run it on many servers concurrently, just to spread the server load (which might be caused by the script run) better.</span><br />
<br />
<span>Let&#39;s say you want to introduce a random delay of 1 minute. You can accomplish it with:</span><br />
<br />
<pre>
❯ cat ./calc_answer_to_ultimate_question_in_life.sh
#!/usr/bin/env bash

declare -i MAX_DELAY=60

random_delay () {
    local -i sleep_for=$((RANDOM % MAX_DELAY))
    echo "Delaying script execution for $sleep_for seconds..."
    sleep $sleep_for
    echo &#39;Continuing script execution...&#39;
}

main () {
    random_delay
    # From here, do the real work. Calculating the answer to
    # the ultimate question can take billions of years....
    : ....
}

main

❯
❯ ./calc_answer_to_ultimate_question_in_life.sh
Delaying script execution for 42 seconds...
Continuing script execution...
</pre>
<br />
<h2 style='display: inline'>set -x and set -e and pipefile</h2><br />
<br />
<span>In my opinion, -x and -e and pipefile are the most useful Bash options. Let&#39;s have a look at them one after another.</span><br />
<br />
<h3 style='display: inline'>-x</h3><br />
<br />
<span>-x prints commands and their arguments as they are executed. This helps to develop and debug your Bash code:</span><br />
<br />
<pre>
❯ set -x
❯ square () { local -i num=$1; echo $((num*num)); }
❯ num=11; echo "Square of $num is $(square $num)"
+ num=11
++ square 11
++ local -i num=11
++ echo 121
+ echo &#39;Square of 11 is 121&#39;
Square of 11 is 121
</pre>
<br />
<span>You can also set it when calling an external script without modifying the script itself:</span><br />
<br />
<pre>
❯ bash -x ./half_broken_script_to_be_debugged.sh
</pre>
<br />
<span>Let&#39;s do that on one of the example scripts we covered earlier:</span><br />
<br />
<pre>
❯ bash -x ./grandmaster.sh
+ bash -x ./grandmaster.sh
+ echo Learn You a Haskell
+ echo for Great Good
+ exec
+ exec
+ declare LINE1 LINE2
+ read LINE1
+ read LINE2
+ echo First line: Learn You a Haskell
First line: Learn You a Haskell
+ echo Second line: for Great Good
Second line: for Great Good
+ exec
❯
</pre>
<br />
<h3 style='display: inline'>-e</h3><br />
<br />
<span>This is a very important option you want to use when you are paranoid. This means, you should always "set -e" in your scripts when you need to make absolutely sure that your script runs successfully (with that I mean that no command should exit with an unexpected status code).</span><br />
<br />
<span>Ok, let&#39;s dig deeper:</span><br />
<br />
<pre>
❯ help set | grep -- -e
      -e  Exit immediately if a command exits with a non-zero status.
</pre>
<br />
<span>As you can see in the following example, the Bash terminates after the execution of "grep" as "foo" is not matching "bar". Therefore, grep exits with 1 (unsuccessfully) and the shell aborts. And therefore, "bar" will  not be printed out anymore:</span><br />
<br />
<pre>
❯ bash -c &#39;set -e; echo hello; grep -q bar &lt;&lt;&lt; foo; echo bar&#39;
hello
❯ echo $?
1
</pre>
<br />
<span>Whereas the outcome changes when the regex matches:</span><br />
<br />
<pre>
❯ bash -c &#39;set -e; echo hello; grep -q bar &lt;&lt;&lt; barman; echo bar&#39;
hello
bar
❯ echo $?
0
</pre>
<br />
<span>So does it mean that grep will always make the shell terminate whenever its exit code isn&#39;t 0? This will render "set -e" quite unusable. Frankly, there are other commands where an exit status other than 0 should not terminate the whole script abruptly. Usually, what you want is to branch your code based on the outcome (exit code) of a command:</span><br />
<br />
<pre>
❯ bash -c &#39;set -e
&gt;    grep -q bar &lt;&lt;&lt; foo
&gt;    if [ $? -eq 0 ]; then
&gt;        echo "matching"
&gt;    else
&gt;        echo "not matching"
&gt;    fi&#39;
❯ echo $?
1
</pre>
<br />
<span>...but the example above won&#39;t reach any of the branches and won&#39;t print out anything, as the script terminates right after grep.</span><br />
<br />
<span>The proper solution is to use grep as an expression in a conditional (e.g. in an if-else statement):</span><br />
<br />
<pre>
❯ bash -c &#39;set -e
&gt;    if grep -q bar &lt;&lt;&lt; foo; then
&gt;        echo "matching"
&gt;    else
&gt;        echo "not matching"
&gt;    fi&#39;
not matching
❯ echo $?
0
❯ bash -c &#39;set -e
&gt;    if grep -q bar &lt;&lt;&lt; barman; then
&gt;        echo "matching"
&gt;    else
&gt;        echo "not matching"
&gt;    fi&#39;
matching
❯ echo $?
0
</pre>
<br />
<span>You can also temporally undo "set -e" if there is no other way:</span><br />
<br />
<pre>
❯ cat ./e.sh
#!/usr/bin/env bash

set -e

foo () {
    local arg="$1"; shift

    if [ -z "$arg" ]; then
        arg=&#39;You!&#39;
    fi
    echo "Hello $arg"
}

bar () {
    # Temporally disable e
    set +e
    local arg="$1"; shift
    # Enable e again.
    set -e

    if [ -z "$arg" ]; then
        arg=&#39;You!&#39;
    fi
    echo "Hello $arg"
}

# Will succeed
bar World
foo Universe
bar

# Will terminate the script
foo

❯ ./e.sh
Hello World
Hello Universe
Hello You!
</pre>
<br />
<span>Why does calling "foo" with no arguments make the script terminate? Because as no argument was given, the "shift" won&#39;t have anything to do as the argument list $@ is empty, and therefore "shift" fails with a non-zero status.</span><br />
<br />
<span>Why would you want to use "shift" after function-local variable assignments? Have a look at my personal Bash coding style guide for an explanation :-):</span><br />
<br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>./2021-05-16-personal-bash-coding-style-guide.html</a><br />
<br />
<h3 style='display: inline'>pipefail</h3><br />
<br />
<span>The pipefail option makes it so that not only the exit code of the last command of the pipe counts regards its exit code but any command of the pipe:</span><br />
<br />
<pre>
❯ help set | grep pipefail -A 2
    pipefail     the return value of a pipeline is the status of
                 the last command to exit with a non-zero status,
                 or zero if no command exited with a non-zero status
</pre>
<br />
<span>The following greps for paul in passwd and converts all lowercase letters to uppercase letters. The exit code of the pipe is 0, as the last command of the pipe (converting from lowercase to uppercase) succeeded:</span><br />
<br />
<pre>
❯ grep paul /etc/passwd | tr &#39;[a-z]&#39; &#39;[A-Z]&#39;
PAUL:X:1000:1000:PAUL BUETOW:/HOME/PAUL:/BIN/BASH
❯ echo $?
0
</pre>
<br />
<span>Let&#39;s look at another example, where "TheRock" doesn&#39;t exist in the passwd file. However, the pipes exit status is still 0 (success). This is so because the last command ("tr" in this case) still succeeded. It is just that it didn&#39;t get any input on stdin to process:</span><br />
<br />
<pre>
❯ grep TheRock /etc/passwd
❯ echo $?
1
❯ grep TheRock /etc/passwd | tr &#39;[a-z]&#39; &#39;[A-Z]&#39;
❯ echo $?
0
</pre>
<br />
<span>To change this behaviour, pipefile can be used. Now, the pipes exit status is 1 (fail), because the pipe contains at least one command (in this case grep) which exited with status 1:</span><br />
<br />
<pre>
❯ set -o pipefail
❯ grep TheRock /etc/passwd | tr &#39;[a-z]&#39; &#39;[A-Z]&#39;
❯ echo $?
1
</pre>
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-01-01-bash-golf-part-2.html'>2022-01-01 Bash Golf Part 2 (You are currently reading this)</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>2021-11-29 Bash Golf Part 1</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all</a><br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>2021-05-16 Personal Bash coding style guide</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>How to stay sane as a DevOps person </title>
        <link href="gemini://foo.zone/gemfeed/2021-12-26-how-to-stay-sane-as-a-devops-person.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-12-26-how-to-stay-sane-as-a-devops-person.gmi</id>
        <updated>2021-12-26T12:02:02+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Log4shell (CVE-2021-44228) made it clear, once again, that working in information technology is not an easy job (especially when you are a DevOps person). I thought it would be interesting to summarize a few techniques to help you to relax.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>How to stay sane as a DevOps person </h1><br />
<br />
<span class='quote'>Published at 2021-12-26T12:02:02+00:00; Updated at 2022-01-12</span><br />
<br />
<pre>
                                     )
                             )      ((     (
                           (        ))     )
                    )       )      //     (
               _   (        __    (     ~-&gt;&gt;
        ,-----&#39; |__,_~~___&lt;&#39;__`)-~__--__-~-&gt;&gt; &lt;
        | //  : | -__   ~__ o)____)),__ - &#39;&gt; &gt;-  &gt;
        | //  : |- \_ \ -\_\ -\ \ \ ~\_  \ -&gt;&gt; - ,  &gt;&gt;
        | //  : |_~_\ -\__\ \~&#39;\ \ \, \__ . -&lt;-  &gt;&gt;
        `-----._| `  -__`-- - ~~ -- ` --~&gt; &gt;
         _/___\_    //)_`//  | ||]
   _____[_______]_[~~-_ (.L_/  ||
  [____________________]&#39; `\_,/&#39;/
    ||| /          |||  ,___,&#39;./
    ||| \          |||,&#39;______|
    ||| /          /|| I==||
    ||| \       __/_||  __||__
-----||-/------`-._/||-o--o---o---
  ~~~~~&#39;
</pre>
<br />
<span>Log4shell (CVE-2021-44228) made it clear, once again, that working in information technology is not an easy job (especially when you are a DevOps person). I thought it would be interesting to summarize a few techniques to help you to relax.</span><br />
<br />
<span>(PS: When I mean DevOps, I also mean Site Reliability Engineers and Sysadmins. I believe SRE, DevOps Engineer and Sysadmin are just synonym titles for the same job).</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Log4Shell'>https://en.wikipedia.org/wiki/Log4Shell</a><br />
<br />
<h2 style='display: inline'>Set clear expectations</h2><br />
<br />
<span>It&#39;s important to set clear expectations. It can be difficult to guess what others expect or don&#39;t expect from you. If you know exactly what you are supposed to do, you can work towards a specific goal and don&#39;t worry about all the other noise so much.</span><br />
<br />
<span>However, if you are in a more senior position, it is expected from you to plan your tasks by yourself to a large degree and also be flexible, so you can react quickly to new situations (e.g. resolving incidents). Also, to a large degree, you have to prioritise your work by yourself. This can overthrow all of your plans. In extreme cases, it can help to share your plans with your team so that everyone is on the same page. Afterwards, be the execution machine. People are happy when they see that stuff gets done. Communicate clearly all critical work you do. This will capture all the technical debt there might be. It does not help in the long run if things are fixed in the background without any visibility. </span><br />
<br />
<span>Due to politeness, many people are not setting clear expectations. I personally may sound sometimes "too German" when setting expectations, but so far nobody complained, and I have even received positive feedback about it.</span><br />
<br />
<h2 style='display: inline'>Always respond to requests but set expectations and boundaries</h2><br />
<br />
<span>There are many temptations to get side-tracked by other projects and/or issues. It is important to set boundaries here. But always answer to all requests as nothing is more frustrating than asking a person and never getting any answer back. This is especially the case when everyone is working form home where people are using tools such as Slack and E-Mail for most of their communications.</span><br />
<br />
<h3 style='display: inline'>Dealing with requests</h3><br />
<br />
<span>If the request is urgent, and you have the capacity to help, probably you should help. If it&#39;s not urgent, maybe ask to pospone the request (e.g. ask to create a ticket, so that someone from your team can work on it later).</span><br />
<br />
<span>If the request is urgent, but you don&#39;t have the knowledge or the capacity to help, try to defer to a colleague who might be able to help. You could also provide some quick tips and hints, so that the requester can resolve the issue by himself. Make it transparent why you might not have the time right now, as this can help the person to review his own priorities or to escalate.  </span><br />
<br />
<h3 style='display: inline'>Escalation is only a tool</h3><br />
<br />
<span>Never make or take an escalation personally. The only forms of escalation should be due to technical issues or lack of resources. An escalation then becomes like a math equation and does not need human resources involved. So de-facto, an escalation is nothing negative, but just a process people can follow to form decision-making. In a good company escalations tend to be an exception, though. Staff knows how to deal with the things by themselves without bothering management too much. </span><br />
<br />
<h2 style='display: inline'>Think positively</h2><br />
<br />
<span>If times are very stressful, think that it could always be worse:</span><br />
<br />
<ul>
<li>Nobody is dying, we are only doing some IT stuff.</li>
<li>Your time after work is your own time, look forward to time with your family or a nice dinner or your favourite sports class.</li>
<li>You probably will never run out of work in the IT sector. So you will always be able to make a living.</li>
<li>Your IT job and life is actually pretty good (compared to a homeless person for example). You are probably part of the world&#39;s top 1% regarding life standard.</li>
</ul><br />
<h2 style='display: inline'>Go slower even if you could go faster</h2><br />
<br />
<span>When working in a team, you may feel that you could get done things faster when you just did everything by yourself. This can be a bit frustrating at times, as you might need to work late hours and also might need to explain things over and over again to others. Also, you could be the one who needs to get things explained over and over again as you are not so familiar with the topic (yet). You will appreciate it if the other person is slowing down for you a bit.</span><br />
<br />
<h3 style='display: inline'>You work in a team</h3><br />
<br />
<span>Security is a team sport. So slow down and make sure that everyone is on track with the goals. You can go full-speed with your very own subtasks, though. Not everyone knows how to use all the tools so well like a full-time DevOps person. As a DevOps person, you are not a security expert, though. Security experts are different people in your company, but DevOps will be the main tribe deploying mitigations (following the security recommendations) and management will be the main tribe coordinating all the efforts. </span><br />
<br />
<span>So even if you think that you can do everything faster by your own, can you really? You probably don&#39;t know what you don&#39;t know about IT security. The more you know about it, the more you know about what you don&#39;t know.</span><br />
<br />
<h3 style='display: inline'>Don&#39;t rush</h3><br />
<br />
<span>Slowing down also helps to prevent errors. Don&#39;t rush your tasks, even if they are urgent. Try to be quick, but don&#39;t rush them. Maybe you are writing a script to mitigate a production issue. You could others peer review that script, for example. Their primary programming language may not be the same (e.g. Golang vs Perl), but they would understand the logic. Or ask another DevOps person from your company with good scripting skills review your mitigation, but he then may lack the domain knowledge of the software you are patching. So in either case, the review will take a bit longer as the reviewer might not be an expert in everything.</span><br />
<br />
<span>So relax, don&#39;t always expect immediate results. Set clear and reasonable timelines for the management about the mitigations. You are not a superhero who has to do everything by yourself. Sometimes, you will miss a deadline. But that will have good reasons. Don&#39;t rush to complete just to meet a deadline. </span><br />
<br />
<a class='textlink' href='./2021-10-22-defensive-devops.html'>Read also "Defensive DevOps" about deploying mitigation scripts.</a><br />
<br />
<h2 style='display: inline'>You are not a superhero</h2><br />
<br />
<span>Always keep that in mind. You can&#39;t solve all problems by your own. Maybe you could, but that would be a lot of additional stress (and this will reflect to your personal life). Also, Superman and Wonder Woman receive much higher salaries than you will ever do ;-).</span><br />
<br />
<span>I have been a superhero multiple times mitigating critical incidents, and I was proud about it in those moments. But actually, I am not proud looking at those retrospectively as for everything there should be other people around who should be able to resolve an incident. No company should rely on a single person, there must always be a substitute. You are not a superhero and as harsh as it sounds, everyone is replaceable. Every superhero can be replaced with another superhero. The only thing it takes to become a superhero is time to get to know the infrastructure and tools very well, paired with work dedication.</span><br />
<br />
<span>This doesn&#39;t mean, that you shouldn&#39;t try your best. But you don&#39;t need to try to be the superhero. Maybe someone else will be the superhero, but that&#39;s OK as long as it&#39;s not always the same person every time. Everyone can have a good day after all. If I could choose between being a superhero or having a good night sleep, I would probably prefer the sleep. </span><br />
<br />
<h3 style='display: inline'>Give away some of your superpowers</h3><br />
<br />
<span>If you are a superhero, try to give away some of your superpowers, so that you can relax in the evening knowing that others (e.g. the current on-call engineers) know how to tackle things. Every member of the team needs to do DevOps (even the team managers, in my humble opinion). Some may be less experienced than others or have other expertises, but to counteract this you could document the recurring tasks so that they are easy to follow (which then later could be either automated away or, even better, fully fixed).</span><br />
<br />
<span>On the other side, if you are a DevOps person, try to sneak into other people&#39;s shoes too. For example, you might not be an expert in Java programming, but a lot of the infrastructure is programmed in Java. This is where usually the Software Developers and Engineers shine. But if you know how to read, debug and even extend Java code too (by learning from the Software Developer superheroes), then your will only benefit from it. </span><br />
<br />
<span>So you are not a superhero. Or, if you are a superhero, then all colleagues should be superheroes too.</span><br />
<br />
<h2 style='display: inline'>Don&#39;t jump on all problems immediately</h2><br />
<br />
<span>In a perfect world, every member of a team comes along with the same strengths and skills. But in reality, everyone is different. </span><br />
<br />
<span>In order to distribute the troubleshooting skills across the team, you should not jump on every problem immediately. Leave some space for others to resolve the issue. This is where the best learning happens. Nobody will learn from you when you solve all problems. People might learn something after you explained what you did, but the takeaways will be minimal compared to when people try to resolve issues by themselves. Always be available for questions which will help your colleagues to steer into the right direction and if you think it helps, give them some tips resolving the issue, even if they didn&#39;t ask for it. Sometimes, engineers are too proud to ask. </span><br />
<br />
<span>The whole paragraph changes when there is an issue you don&#39;t know how to resolve. Jump on it, so you can learn from it. But also ask for advice if you are unsure about it.</span><br />
<br />
<span>If the issue is a very critical one, then you might better off trying to resolve it as fast as possible with your full powers in order to avoid any major damage to the company. This, of course, only works if you know how to resolve it quickly. So, don&#39;t leave others with not much experience yet looking at it. If possible, work with the team to resolve the issue. Unfortunately, solving it with the team is not always the fastest way. So in this particular circumstance, the company may be better off being saved by a single superhero. Make sure that the problem will not occur again or, at least, that others can fix it the next time without Superman flying by.</span><br />
<br />
<h2 style='display: inline'>Force breaks; and shutdown now</h2><br />
<br />
<span>Be strict about your time off. Nowadays, tech workers check their messages also out of office hours and are reachable 24/7. This really should only be the case when you are on-call, to be honest (or if you work for a startup). All other out-of-office time is owned by you and not your employer. You have signed an 40 hour/week and not 7 days/week contract. Of course, there will be always some sort of flexibility and exceptions. You might need to work over the weekend to get a migration done or a problem solved. But to balance it out, you should have other days off as substitutes.</span><br />
<br />
<span>It&#39;s important to shut down your brain from work during your breaks (be strict with your breaks, leave your desk for lunch or for a walk early afternoon and if you aren&#39;t on-call also don&#39;t take your work-phone with you). You will be happier and also much more energized and productive in the afternoon. Also, when you are reachable 24/7, your colleagues will start thinking that you don&#39;t have anything more important to do than work.</span><br />
<br />
<h2 style='display: inline'>Block time every day for personal advance</h2><br />
<br />
<span>It does not matter how many tasks are in your backlog or how many issues are to be tackled. *Always* find time for personal advance. The most issues aren&#39;t critical anyway and can wait a bit. At the end of the day, you will have a nice feeling that you have accomplished something meaningful. This can be an interesting project or learning a new technology you are interested in. Of course, there must be consensus with your manager (unless you do that kind of thing in your personal time of course). </span><br />
<br />
<span>If you are too busy at work and just can&#39;t block time, then maybe it&#39;s time to think about alternatives. But before you do that, probably there is something else you can do. Perhaps you just think you can&#39;t block time, but you would be positively surprised to hear from your manager that he will fully support you. Of course, he won&#39;t agree to you working full-time on your pet projects. But a certain portion of your time should be allocated for personal advance. After all, your employer also want&#39;s you to stay happy so that you don&#39;t look for alternatives. It&#39;s of everyone&#39;s interest that you like your job and stay motivated. The more you are motivated, the more productive you are. The more productive you are, the more valuable you are for the company.</span><br />
<br />
<h2 style='display: inline'>More</h2><br />
<br />
<span>Another blog post worth reading:</span><br />
<br />
<a class='textlink' href='https://unixsheikh.com/articles/how-to-stay-sane-in-todays-world-of-tech.html'>https://unixsheikh.com/articles/how-to-stay-sane-in-todays-world-of-tech.html</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Bash Golf Part 1</title>
        <link href="gemini://foo.zone/gemfeed/2021-11-29-bash-golf-part-1.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-11-29-bash-golf-part-1.gmi</id>
        <updated>2021-11-29T14:06:14+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This is the first blog post about my Bash Golf series. This series is about random Bash tips, tricks and weirdnesses I came across. It's a collection of smaller articles I wrote in an older (in German language) blog, which I translated and refreshed with some new content.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Bash Golf Part 1</h1><br />
<br />
<span class='quote'>Published at 2021-11-29T14:06:14+00:00; Updated at 2022-01-05</span><br />
<br />
<pre>
     &#39;\                   .  .                        |&gt;18&gt;&gt;
       \              .         &#39; .                   |
      O&gt;&gt;         .                 &#39;o                |
       \       .                                      |
       /\    .                                        |
      / /  .&#39;                                         |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                            Art by Joan Stark
</pre>
<br />
<span>This is the first blog post about my Bash Golf series. This series is about random Bash tips, tricks and weirdnesses I came across. It&#39;s a collection of smaller articles I wrote in an older (in German language) blog, which I translated and refreshed with some new content.</span><br />
<br />
<a class='textlink' href='./2022-01-01-bash-golf-part-2.html'>2022-01-01 Bash Golf Part 2</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>2021-11-29 Bash Golf Part 1 (You are currently reading this)</a><br />
<br />
<h2 style='display: inline'>TCP/IP networking</h2><br />
<br />
<span>You probably know the Netcat tool, which is a swiss army knife for TCP/IP networking on the command line. But did you know that the Bash natively supports TCP/IP networking?</span><br />
<br />
<span>Have a look here how that works:</span><br />
<br />
<pre>
❯ cat &lt; /dev/tcp/time.nist.gov/13

59536 21-11-18 08:09:16 00 0 0 153.6 UTC(NIST) *
</pre>
<br />
<span>The Bash treats /dev/tcp/HOST/PORT in a special way so that it is actually establishing a TCP connection to HOST:PORT. The example above redirects the TCP output of the time-server to cat and cat is printing it on standard output (stdout).</span><br />
<br />
<span>A more sophisticated example is firing up an HTTP request. Let&#39;s create a new read-write (rw) file descriptor (fd) 5, redirect the HTTP request string to it, and then read the response back:</span><br />
<br />
<pre>
❯ exec 5&lt;&gt;/dev/tcp/google.de/80
❯ echo -e "GET / HTTP/1.1\nhost: google.de\n\n" &gt;&amp;5
❯ cat &lt;&amp;5 | head
HTTP/1.1 301 Moved Permanently
Location: http://www.google.de/
Content-Type: text/html; charset=UTF-8
Date: Thu, 18 Nov 2021 08:27:18 GMT
Expires: Sat, 18 Dec 2021 08:27:18 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 218
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
</pre>
<br />
<span>You would assume that this also works with the ZSH, but it doesn&#39;t. This is one of the few things which don&#39;t work with the ZSH but in the Bash. There might be plugins you could use for ZSH to do something similar, though.</span><br />
<br />
<h2 style='display: inline'>Process substitution</h2><br />
<br />
<span>The idea here is, that you can read the output (stdout) of a command from a file descriptor:</span><br />
<br />
<pre>
❯ uptime # Without process substitution
 10:58:03 up 4 days, 22:08,  1 user,  load average: 0.16, 0.34, 0.41

❯ cat &lt;(uptime) # With process substitution
 10:58:16 up 4 days, 22:08,  1 user,  load average: 0.14, 0.33, 0.41

❯ stat &lt;(uptime)
  File: /dev/fd/63 -&gt; pipe:[468130]
  Size: 64              Blocks: 0          IO Block: 1024   symbolic link
Device: 16h/22d Inode: 468137      Links: 1
Access: (0500/lr-x------)  Uid: ( 1001/    paul)   Gid: ( 1001/    paul)
Context: unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
Access: 2021-11-20 10:59:31.482411961 +0000
Modify: 2021-11-20 10:59:31.482411961 +0000
Change: 2021-11-20 10:59:31.482411961 +0000
 Birth: -
</pre>
<br />
<span>This example doesn&#39;t make any sense practically speaking, but it clearly demonstrates how process substitution works. The standard output pipe of "uptime" is redirected to an anonymous file descriptor. That fd then is opened by the "cat" command as a regular file.</span><br />
<br />
<span>A useful use case is displaying the differences of two sorted files:</span><br />
<br />
<pre>
❯ echo a &gt; /tmp/file-a.txt
❯ echo b &gt;&gt; /tmp/file-a.txt
❯ echo c &gt;&gt; /tmp/file-a.txt
❯ echo b &gt; /tmp/file-b.txt
❯ echo a &gt;&gt; /tmp/file-b.txt
❯ echo c &gt;&gt; /tmp/file-b.txt
❯ echo X &gt;&gt; /tmp/file-b.txt
❯ diff -u &lt;(sort /tmp/file-a.txt) &lt;(sort /tmp/file-b.txt)
--- /dev/fd/63  2021-11-20 11:05:03.667713554 +0000
+++ /dev/fd/62  2021-11-20 11:05:03.667713554 +0000
@@ -1,3 +1,4 @@
 a
 b
 c
+X
❯ echo X &gt;&gt; /tmp/file-a.txt # Now, both files have the same content again.
❯ diff -u &lt;(sort /tmp/file-a.txt) &lt;(sort /tmp/file-b.txt)
❯
</pre>
<br />
<span>Another example is displaying the differences of two directories:</span><br />
<br />
<pre>
❯ diff -u &lt;(ls ./dir1/ | sort) &lt;(ls ./dir2/ | sort)
</pre>
<br />
<span>More (Bash golfing) examples:</span><br />
<br />
<pre>
❯ wc -l &lt;(ls /tmp/) /etc/passwd &lt;(env)
     24 /dev/fd/63
     49 /etc/passwd
     24 /dev/fd/62
     97 total
❯

❯ while read foo; do
&gt;    echo $foo
&gt; done &lt; &lt;(echo foo bar baz)
foo bar baz
❯
</pre>
<br />
<span>So far, we only used process substitution for stdout redirection. But it also works for stdin. The following two commands result into the same outcome, but the second one is writing the tar data stream to an anonymous file descriptor which is substituted by the "bzip2" command reading the data stream from stdin and compressing it to its own stdout, which then gets redirected to a file:</span><br />
<br />
<pre>
❯ tar cjf file.tar.bz2 foo
❯ tar cjf &gt;(bzip2 -c &gt; file.tar.bz2) foo
</pre>
<br />
<span>Just think a while and see whether you understand fully what is happening here.</span><br />
<br />
<h2 style='display: inline'>Grouping</h2><br />
<br />
<span>Command grouping can be quite useful for combining the output of multiple commands:</span><br />
<br />
<pre>
❯ { ls /tmp; cat /etc/passwd; env; } | wc -l
97
❯ ( ls /tmp; cat /etc/passwd; env; ) | wc -l
97
</pre>
<br />
<span>But wait, what is the difference between curly braces and normal braces? I assumed that the normal braces create a subprocess whereas the curly ones don&#39;t, but I was wrong:</span><br />
<br />
<pre>
❯ echo $
62676
❯ { echo $; }
62676
❯ ( echo $; )
62676
</pre>
<br />
<span>One difference is, that the curly braces require you to end the last statement with a semicolon, whereas with the normal braces you can omit the last semicolon:</span><br />
<br />
<pre>
❯ ( env; ls ) | wc -l
27
❯ { env; ls } | wc -l
&gt;
&gt; ^C
</pre>
<br />
<span>In case you know more (subtle) differences, please write me an E-Mail and let me know.</span><br />
<br />
<span class='quote'>Update: A reader sent me an E-Mail and pointed me to the Bash manual page, which explains the difference between () and {} (I should have checked that by myself):</span><br />
<br />
<pre>
(list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT
       below).   Variable  assignments  and builtin commands that affect the shell&#39;s
       environment do not remain in effect after the command completes.  The  return
       status is the exit status of list.

{ list; }
       list  is simply executed in the current shell environment.  list must be ter‐
       minated with a newline or semicolon.  This is known as a group command.   The
       return  status  is the exit status of list.  Note that unlike the metacharac‐
       ters ( and ), { and } are reserved words and must occur where a reserved word
       is  permitted  to  be recognized.  Since they do not cause a word break, they
       must be separated from list by whitespace or another shell metacharacter.
</pre>
<br />
<span>So I was right that () is executed in a subprocess. But why does $ not show a different PID? Also here (as pointed out by the reader) is the answer in the manual page:</span><br />
<br />
<pre>
$      Expands to the process ID of the shell.  In a () subshell, it expands to  the
       process ID of the current shell, not the subshell.
</pre>
<br />
<span>If we want print the subprocess PID, we can use the BASHPID variable:</span><br />
<br />
<pre>
❯ echo $BASHPID; { echo $BASHPID; }; ( echo $BASHPID; )
1028465
1028465
1028739
</pre>
<br />
<h2 style='display: inline'>Expansions</h2><br />
<br />
<span>Let&#39;s start with simple examples:</span><br />
<br />
<pre>
❯ echo {0..5}
0 1 2 3 4 5
❯ for i in {0..5}; do echo $i; done
0
1
2
3
4
5
</pre>
<br />
<span>You can also add leading 0 or expand to any number range:</span><br />
<br />
<pre>
❯ echo {00..05}
00 01 02 03 04 05
❯ echo {000..005}
000 001 002 003 004 005
❯ echo {201..205}
201 202 203 204 205
</pre>
<br />
<span>It also works with letters:</span><br />
<br />
<pre>
❯ echo {a..e}
a b c d e
</pre>
<br />
<span>Now it gets interesting. The following takes a list of words and expands it so that all words are quoted:</span><br />
<br />
<pre>
❯ echo \"{These,words,are,quoted}\"
"These" "words" "are" "quoted"
</pre>
<br />
<span>Let&#39;s also expand to the cross product of two given lists:</span><br />
<br />
<pre>
❯ echo {one,two}\:{A,B,C}
one:A one:B one:C two:A two:B two:C
❯ echo \"{one,two}\:{A,B,C}\"
"one:A" "one:B" "one:C" "two:A" "two:B" "two:C"
</pre>
<br />
<span>Just because we can:</span><br />
<br />
<pre>
❯ echo Linux-{one,two,three}\:{A,B,C}-FreeBSD
Linux-one:A-FreeBSD Linux-one:B-FreeBSD Linux-one:C-FreeBSD Linux-two:A-FreeBSD Linux-two:B-FreeBSD Linux-two:C-FreeBSD Linux-three:A-FreeBSD Linux-three:B-FreeBSD Linux-three:C-FreeBSD
</pre>
<br />
<h2 style='display: inline'>- aka stdin and stdout placeholder</h2><br />
<br />
<span>Some commands and Bash builtins use "-" as a placeholder for stdin and stdout:</span><br />
<br />
<pre>
❯ echo Hello world
Hello world
❯ echo Hello world | cat -
Hello world
❯ cat - &lt;&lt;ONECHEESEBURGERPLEASE
Hello world
ONECHEESEBURGERPLEASE
Hello world
❯ cat - &lt;&lt;&lt; &#39;Hello world&#39;
Hello world
</pre>
<br />
<span>Let&#39;s walk through all three examples from the above snippet:</span><br />
<br />
<ul>
<li>The first example is obvious (the Bash builtin "echo" prints its arguments to stdout).</li>
<li>The second pipes "Hello world" via stdout to stdin of the "cat" command. As cat&#39;s argument is "-" it reads its data from stdin and not from a regular file named "-". So "-" has a special meaning for cat.</li>
<li>The third and fourth examples are interesting as we don&#39;t use a pipe as of "|" but a so-called HERE-document and a HERE-string. But the end results are the same.</li>
</ul><br />
<span>The "tar" command understands "-" too. The following example tars up some local directory and sends the data to stdout (this is what "-f -" commands it to do). stdout then is piped via an SSH session to a remote tar process (running on buetow.org) and reads the data from stdin and extracts all the data coming from stdin (as we told tar with "-f -") on the remote machine:</span><br />
<br />
<pre>
❯ tar -czf - /some/dir | ssh hercules@buetow.org tar -xzvf - 
</pre>
<br />
<span>This is yet another example of using "-", but this time using the "file" command:</span><br />
<br />
<pre>
$ head -n 1 grandmaster.sh
#!/usr/bin/env bash
$ file - &lt; &lt;(head -n 1 grandmaster.sh)
/dev/stdin: a /usr/bin/env bash script, ASCII text executable
</pre>
<br />
<span>Some more golfing:</span><br />
<br />
<pre>
$ cat -
hello
hello
^C
$ file -
#!/usr/bin/perl
/dev/stdin: Perl script text executable
</pre>
<br />
<h2 style='display: inline'>Alternative argument passing</h2><br />
<br />
<span>This is a quite unusual way of passing arguments to a Bash script:</span><br />
<br />
<pre>
❯ cat foo.sh
#/usr/bin/env bash
declare -r USER=${USER:?Missing the username}
declare -r PASS=${PASS:?Missing the secret password for $USER}
echo $USER:$PASS
</pre>
<br />
<span>So what we are doing here is to pass the arguments via environment variables to the script. The script will abort with an error when there&#39;s an undefined argument.</span><br />
<br />
<pre>
❯ chmod +x foo.sh
❯ ./foo.sh
./foo.sh: line 3: USER: Missing the username
❯ USER=paul ./foo.sh
./foo.sh: line 4: PASS: Missing the secret password for paul
❯ echo $?
1
❯ USER=paul PASS=secret ./foo.sh
paul:secret
</pre>
<br />
<span>You have probably noticed this *strange* syntax:</span><br />
<br />
<pre>
❯ VARIABLE1=value1 VARIABLE2=value2 ./script.sh
</pre>
<br />
<span>That&#39;s just another way to pass environment variables to a script. You can write it as well as like this:</span><br />
<br />
<pre>
❯ export VARIABLE1=value1
❯ export VARIABLE2=value2
❯ ./script.sh
</pre>
<br />
<span>But the downside of it is that the variables will also be defined in your current shell environment and not just in the scripts sub-process.</span><br />
<br />
<h2 style='display: inline'>: aka the null command</h2><br />
<br />
<span>First, let&#39;s use the "help" Bash built-in to see what it says about the null command:</span><br />
<br />
<pre>
❯ help :
:: :
    Null command.

    No effect; the command does nothing.

    Exit Status:
    Always succeeds.
</pre>
<br />
<span>PS: IMHO, people should use the Bash help more often. It is a very useful Bash reference. Too many fallbacks to a Google search and then land on Stack Overflow. Sadly, there&#39;s no help built-in for the ZSH shell though (so even when I am using the ZSH I make use of the Bash help as most of the built-ins are compatible). </span><br />
<br />
<span>OK, back to the null command. What happens when you try to run it? As you can see, absolutely nothing. And its exit status is 0 (success):</span><br />
<br />
<pre>
❯ :
❯ echo $?
0
</pre>
<br />
<span>Why would that be useful? You can use it as a placeholder in an endless while-loop:</span><br />
<br />
<pre>
❯ while : ; do date; sleep 1; done
Sun 21 Nov 12:08:31 GMT 2021
Sun 21 Nov 12:08:32 GMT 2021
Sun 21 Nov 12:08:33 GMT 2021
^C
❯
</pre>
<br />
<span>You can also use it as a placeholder for a function body not yet fully implemented, as an empty function ill result in a syntax error:</span><br />
<br />
<pre>
❯ foo () {  }
-bash: syntax error near unexpected token `}&#39;
❯ foo () { :; }
❯ foo
❯
</pre>
<br />
<span>Or use it as a placeholder for not yet implemented conditional branches:</span><br />
<br />
<pre>
❯ if foo; then :; else echo bar; fi
</pre>
<br />
<span>Or (not recommended) as a fancy way to comment your Bash code:</span><br />
<br />
<pre>
❯ : I am a comment and have no other effect
❯ : I am a comment and result in a syntax error ()
-bash: syntax error near unexpected token `(&#39;
❯ : "I am a comment and don&#39;t result in a syntax error ()"
❯
</pre>
<br />
<span>As you can see in the previous example, the Bash still tries to interpret some syntax of all text following after ":". This can be exploited (also not recommended) like this:</span><br />
<br />
<pre>
❯ declare i=0
❯ $[ i = i + 1 ]
bash: 1: command not found...
❯ : $[ i = i + 1 ]
❯ : $[ i = i + 1 ]
❯ : $[ i = i + 1 ]
❯ echo $i
4
</pre>
<br />
<span>For these kinds of expressions it&#39;s always better to use "let" though. And you should also use $((...expression...)) instead of the old (deprecated) way $[ ...expression... ] like this example demonstrates:</span><br />
<br />
<pre>
❯ declare j=0
❯ let j=$((j + 1))
❯ let j=$((j + 1))
❯ let j=$((j + 1))
❯ let j=$((j + 1))
❯ echo $j
4
</pre>
<br />
<h2 style='display: inline'>(No) floating point support</h2><br />
<br />
<span>I have to give a plus-point to the ZSH here. As the ZSH supports floating point calculation, whereas the Bash doesn&#39;t:</span><br />
<br />
<pre>
❯ bash -c &#39;echo $(( 1/10 ))&#39;
0
❯ zsh -c &#39;echo $(( 1/10 ))&#39;
0
❯ bash -c &#39;echo $(( 1/10.0 ))&#39;
bash: line 1: 1/10.0 : syntax error: invalid arithmetic operator (error token is ".0 ")
❯ zsh -c &#39;echo $(( 1/10.0 ))&#39;
0.10000000000000001
❯
</pre>
<br />
<span>It would be nice to have native floating point support for the Bash too, but you don&#39;t want to use the shell for complicated calculations anyway. So it&#39;s fine that Bash doesn&#39;t have that, I guess. </span><br />
<br />
<span>In the Bash you will have to fall back to an external command like "bc" (the arbitrary precision calculator language):</span><br />
<br />
<pre>
❯ bc &lt;&lt;&lt; &#39;scale=2; 1/10&#39;
.10
</pre>
<br />
<span>See you later for the next post of this series.</span><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-01-01-bash-golf-part-2.html'>2022-01-01 Bash Golf Part 2</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>2021-11-29 Bash Golf Part 1 (You are currently reading this)</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all</a><br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>2021-05-16 Personal Bash coding style guide</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Defensive DevOps</title>
        <link href="gemini://foo.zone/gemfeed/2021-10-22-defensive-devops.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-10-22-defensive-devops.gmi</id>
        <updated>2021-10-22T10:02:46+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I have seen many different setups and infrastructures during my carreer. My roles always included front-line ad-hoc fire fighting production issues. This often involves identifying and fixing these under time pressure, without the comfort of 2-week-long SCRUM sprints and without an exhaustive QA process. I also wrote a lot of code (Bash, Ruby, Perl, Go, and a little Java), and I followed the typical software development process, but that did not always apply to critical production issues.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Defensive DevOps</h1><br />
<br />
<span class='quote'>Published at 2021-10-22T10:02:46+03:00</span><br />
<br />
<pre>
                                                            c=====e
                                                               H
      ____________                                         _,,_H__
     (__((__((___()                                       //|     |
    (__((__((___()()_____________________________________// |ACME |
   (__((__((___()()()------------------------------------&#39;  |_____|
                           ASCII Art by Clyde Watson
</pre>
<br />
<span>I have seen many different setups and infrastructures during my carreer. My roles always included front-line ad-hoc fire fighting production issues. This often involves identifying and fixing these under time pressure, without the comfort of 2-week-long SCRUM sprints and without an exhaustive QA process. I also wrote a lot of code (Bash, Ruby, Perl, Go, and a little Java), and I followed the typical software development process, but that did not always apply to critical production issues.</span><br />
<br />
<span>Unfortunately, no system is 100% reliable, and you can never be prepared for a subset of the possible problem-space. IT infrastructures can be complex. Not even mentioning Kubernetes yet, a Microservice-based infrastructure can complicate things even further. You can take care of 99% of all potential problems by following all DevOps best practices. Those best practices are not the subject of this blog post; this post is about the sub 1% of the issues arising from nowhere you can&#39;t be prepared for. </span><br />
<br />
<span>Is there a software bug in a production, even though the software passed QA (after all, it is challenging to reproduce production behaviour in an artificial testing environment) and the software didn&#39;t show any issues running in production until a special case came up just now after it got deployed to production a week ago? Are there multiple hardware failure happening which causes loss of service redundancy or data inaccessibility? Is the automation of external customers connected to our infrastructure putting unexpectedly extra pressure on your grid, driving higher latencies and putting the SLAs at risk? You bet the solution is: Sysadmins, SREs and DevOps Engineers to the rescue. </span><br />
<br />
<span>You agree that fixing production issues this way is not proactive but rather reactive. I prefer to call it defensive, though, as you "defend" your system against a production issue. But, at the same time, you have to take a cautious (defensive) approach to fix it, as you don&#39;t want to make things worse. </span><br />
<br />
<span>Over time, I have compiled a list of fire-fighting automation strategies, which I would like to share here. </span><br />
<br />
<h2 style='display: inline'>Meet Defensive DevOps</h2><br />
<br />
<span>Defensive DevOps is a term I invented by myself. I define it this way:</span><br />
<br />
<ul>
<li>It is the practice of automating production issues away ASAP as they appear. </li>
<li>For rapid development, ignore most of the CI and QA best practices.</li>
<li>Ignore the SCRUM process (if your team does SCRUM), as it will take too long to implement a solution. </li>
<li>Be extremely careful (defensive) executing any fixing code in production, taking all failure scenarios into consideration and always have a rollback plan at hand. </li>
<li>Still deliver a high-quality solution so that no customer will ever notice that there was an issue in the first place.</li>
</ul><br />
<span>That sounds a bit crazy, but this is, unfortunately, in rare occasions the reality. As the question is not whether production issues will happen, the question is WHEN they will happen. Every large provider, such as Google, Netflix, and so on, suffered significant outages before, and I firmly believe that their engineers know what they are doing. But you can prepare for the unexpected only to a certain degree.</span><br />
<br />
<h2 style='display: inline'>Don&#39;t fully automate from the beginning</h2><br />
<br />
<span>Do you have to solve problem X? The best solution would be to fully automate it away, correct? No, the best way is to fix problem X manually first. Does the problem appear on one server or on thousand servers? The scale does not matter here. The point is that you should fix the problem at least once manually, so you understand the problem and how to solve it before implementing automation around it.</span><br />
<br />
<span>You should also have a short meeting with your team. Every person may has a different perspective and can give valuable input for determining the best strategy. But, again, keep the session short and efficient. Focus on the facts. After all, you are the domain expert and you probably know what you are doing.</span><br />
<br />
<span>Once you understand the problem, fix it on a different server again. This time maybe write a small program or script. Semi-automate the process, but don&#39;t fully automate it yet. Start the semi-automated solution manually on a couple of more servers and observe the result. You want to gain more confidence that this really solved the problem. This can take a couple of hours manually running it over and over again. During that process, you will improve your script iteratively.</span><br />
<br />
<h2 style='display: inline'>Develop code directly on production systems</h2><br />
<br />
<span>You have to develop code directly on a production system. This sounds a bit controversial, but you want to get a working solution ASAP, and there is a very high chance that you can&#39;t reproduce problem X in a development or QA environment. Or at least it will consume significant effort and time to reproduce the problem, and by the time your code is ready, it&#39;s already too late. So the most practical solution is to directly develop your solution against a production system with the problem at hand. </span><br />
<br />
<span>You might not have your full-featured IDE available on a production system, but a text editor, such as Vim (or Neovim), is sufficient for writing scripts. Some editors allow you to edit files remotely. With Vim you can accomplish it with "vim scp://SERVER///path/to/file.sh". Every time you save the file, it will be automatically uploaded via SCP to the server. From there, you can execute it directly. This comes with the additional benefits of still having access to all the Vim plugins installed locally, which you might not have installed on any production machines. This approach also removes any network delays you might experience when running your editor directly on a remote machine. </span><br />
<br />
<span>Unfortunately, it will be a bit more complicated when you rely on code reviews (e.g. in a FIPS environment). Pair-programming could be the solution here.</span><br />
<br />
<h3 style='display: inline'>Don&#39;t make it worse</h3><br />
<br />
<span>You want to triple-check that your script is not damaging your system even further. You might introduce a bug to the code, so there should always be a way to roll back any permanent change it causes. You have to program it in a defensive style:</span><br />
<br />
<ul>
<li>Make sure that all that your script does is logged to a file. Best, when it&#39;s a Bash script, use "set -x". This makes the script print all commands as they are executed. Always write the output to a file. This helps to verify that your script is working as intended. The log output should always include timestamps for each significant operation performed.</li>
<li>Make sure that no command executed by your script is failing. You should use "set -e" in your script, which makes the whole script terminate immediately if a command in it exits with a non-zero status. This will save you from apparent errors, e.g. trying to move files to a non-existent directory or trying to operate on a non-existent file. </li>
<li>Your script should never delete any files. If solving problem X involves deleting files, don&#39;t delete them but rename or move them to a separate directory so that these can be recovered just in case. </li>
<li>When you rename/move files around, always add a timestamp to a directory or the end of the file name (e.g. with "mv FILE FILE.$(date +%s"). This ensures that a backup never gets overwritten by another backup during a subsequential run of your script. Alternatively, before renaming a file, check whether the destination file already exists or not. </li>
<li>When solving problem X involves manipulating files in place, be ultra-cautious. Best try to avoid in-place file manipulation. But if you really have to, you should, if disk space permits, always create a backup of the file first. Depending on the particular case, you might add a timestamp to the backup or only keep the very first initial backup of a file.</li>
<li>You should implement a "--dry" switch in your script. When you run the script in dry mode, it won&#39;t manipulate anything on the system, but it would only print out what it would do. Always run your script in dry mode before running it for real. </li>
</ul><br />
<span>Furthermore, when you write Bash script, always run the tool ShellSheck (https://shellshock.io/) on it. This helps to catch many potential issues before applying it in production. </span><br />
<br />
<h2 style='display: inline'>Test your code</h2><br />
<br />
<span>You probably won&#39;t have time for writing unit tests. But what you can do is to pedantically test your code manually. But you have to do the testing on a production machine. So how can you test your code in production without causing more damage? </span><br />
<br />
<span>Your script should be idempotent. This means you can run it infinite times in a row, and you will always get the same result. For example, in the first run of the script, a file A get&#39;s renamed to A.backup. The second time you run the script, it attempts to do the same, but it recognises that A has already been renamed to A.backup and then it is skipping that step. This is very helpful for manually testing, as it means that you can re-run the script every time you extended it. You should dry-run the script at least once before running it for real. You can apply the same principle for almost all features you add to the code.  </span><br />
<br />
<span>You may also want to inject manual negative testing into your script. For example, you want to run a particular function F in your script but only if a certain pre-condition is met, and you want to ensure that the code branching works as expected. The pre-condition check could be pretty complex (e.g. N log messages containing a specific warning string are found in the applications logs, but only on the cluster leader server). You can flip the switch directly in the code manually (e.g. run F only, when the pre-condition isn&#39;t met) and then perform a dry run of the script and study the output. Once done, flip the switch back to its correct configuration. For double insurance, test the same on a different server type (e.g. on a follower and not on a leader system).</span><br />
<br />
<span>By following these principles, you test every line of code while you are developing on it. </span><br />
<br />
<h2 style='display: inline'>Automation</h2><br />
<br />
<span>At one point, you will be tired of manually running your script and also confident enough to automate it. You could deploy it with a configuration management system such as puppet Puppet and schedule a periodic execution via cron, a systemd timer or even a separate background daemon process. You have to be extremely careful here. The more you automate, the more damage you can cause. You don&#39;t want to automate it on all servers involved at once, but you want to slowly ramp up the automation. </span><br />
<br />
<span>First, automate it only on one single server and monitor the result closely. At first, only automate running the script in dry mode. Also, don&#39;t forget that you still should log everything that the script is doing. Once everything looks fine, you can automate the script on the canary server for real. It shouldn&#39;t be a disaster if something goes wrong as usually systems are designed in a HA fashion, where the same data is still at least on another server available. In the worst-case scenario, you could recover data from there or from the local backup files your script created.</span><br />
<br />
<span>Now, you can add a handful more canary servers to the automation. You should keep close attention to what the automation is doing. You could use a tool like DTail for distributed log file following. At this point, you could also think of deploying a monitoring check (e.g. Icinga) to see whether your script is not terminating abnormally or logging warnings or errors.</span><br />
<br />
<a class='textlink' href='./2021-04-22-dtail-the-distributed-log-tail-program.html'>DTail - The distributed log tail program</a><br />
<br />
<span>From there, you could automate the solution on more and more servers. Best, ramp up the automation to a handful of systems, and later to a whole line of servers (e.g. all secondary servers of a given cluster). And afterwards, automate it on all servers.</span><br />
<br />
<span>Remember, whenever something goes wrong, you will have plenty of logs and backup files available. The disaster recovery would involve extending your script to take care of that too or writing a new script for rolling back the backups. </span><br />
<br />
<h2 style='display: inline'>Out of office hours</h2><br />
<br />
<span>If possible, don&#39;t deploy any automation shortly before out of office hours, such as in the evening, before holidays or weekends. The only exception would be that you, or someone else, will be available to monitor the automation out of office hours. If it is a critical issue, someone, for example, the on-call person, could take over. Or ask your boss to work now but to take off another day to compensate.</span><br />
<br />
<span>You should add an easy off-switch to your automation so that everyone from your team knows how to pause it if something goes wrong in order to adjust the automation accordingly. Of course, you should still follow all the principles mentioned in this blog post when making any changes. </span><br />
<br />
<h2 style='display: inline'>Retrospective</h2><br />
<br />
<span>For every major incident, you need to follow up with an incident retrospective. A blame-free, detailed description of exactly what went wrong to cause the incident, along with a list of steps to take to prevent a similar incident from occurring again in the future.</span><br />
<br />
<span>This usually means creating one or more tickets, which will be dealt with soon. Once the permanent fix is deployed, you can remove your ad-hoc automation and monitoring around it and focus on your regular work again.</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Keep it simple and stupid</title>
        <link href="gemini://foo.zone/gemfeed/2021-09-12-keep-it-simple-and-stupid.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-09-12-keep-it-simple-and-stupid.gmi</id>
        <updated>2021-09-12T09:39:20+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>A robust computer system must be kept simple and stupid (KISS). The fancier the system is, the more can break. Unfortunately, most systems tend to become complex and challenging to maintain in today's world. In the early days, so I was told, engineers understood every part of the system, but nowadays, we see more of the 'lasagna' stack. One layer or framework is built on top of another layer, and in the end, nobody has got a clue what's going on.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Keep it simple and stupid</h1><br />
<br />
<span class='quote'>Published at 2021-09-12T09:39:20+03:00; Updated at 2023-03-23</span><br />
<br />
<pre>
  _______________                        |*\_/*|_______
  |  ___________  |     .-.     .-.      ||_/-\_|______  |
  | |           | |    .****. .****.     | |           | |
  | |   0   0   | |    .*****.*****.     | |   0   0   | |
  | |     -     | |     .*********.      | |     -     | |
  | |   \___/   | |      .*******.       | |   \___/   | |
  | |___     ___| |       .*****.        | |___________| |
  |_____|\_/|_____|        .***.         |_______________|
    _|__|/ \|_|_.............*.............._|________|_
   / ********** \                          / ********** \
 /  ************  \                      /  ************  \
--------------------                    --------------------
</pre>
<br />
<span>A robust computer system must be kept simple and stupid (KISS). The fancier the system is, the more can break. Unfortunately, most systems tend to become complex and challenging to maintain in today&#39;s world. In the early days, so I was told, engineers understood every part of the system, but nowadays, we see more of the "lasagna" stack. One layer or framework is built on top of another layer, and in the end, nobody has got a clue what&#39;s going on.</span><br />
<br />
<h1 style='display: inline'>Need faster hardware</h1><br />
<br />
<span>This not just makes the system much more complex, difficult to maintain and challenging to troubleshoot, but also slow. So more experts are needed to support it. Also, newer and faster hardware is required to make it run smoothly. Often, it&#39;s so much easier to buy speedier hardware than rewrite a whole system from scratch from the bottom-up. The latter would require much more resources in the short run, but in the long run, it should pay off. Unfortunately, many project owners scare away from it as they only want to get their project done and then move on.</span><br />
<br />
<h1 style='display: inline'>Too complex to be replaced</h1><br />
<br />
<h2 style='display: inline'>On COBOL</h2><br />
<br />
<span>Have a look at COBOL, a prevalent programming language of the past. No one is learning COBOL in college or university anymore, but many legacy systems still require COBOL experts. Why is this? It&#39;s just too scary to write everything from scratch. There&#39;s too much COBOL code out there that can&#39;t be replaced from today to tomorrow. </span><br />
<br />
<a class='textlink' href='https://nymag.com/intelligencer/2020/04/what-is-cobol-what-does-it-have-to-do-with-the-coronavirus.html'>https://nymag.com/intelligencer/2020/04/what-is-cobol-what-does-it-have-to-do-with-the-coronavirus.html</a><br />
<br />
<h2 style='display: inline'>On Kubernetes</h2><br />
<br />
<span>Now have a look at Kubernetes (k8s), the current trendy infrastructure thing to use nowadays. Of course, there are many benefits of using k8s (auto-scaling, reproducible deployments, dynamic resource allocation and resource sharing, saving of hardware costs, good commercial for potential employees as it is the current hot sauce of infrastructure). But all of this also comes with costs: You need experts operating the k8s cluster (or you need to pay extra for a managed cluster in the cloud), increased complexity of the system (k8s comes with a steep learning curve). The latter not only applies to the engineers managing the k8s cluster -  it also applies to the software engineers, who now have to develop &#39;cloud native&#39; applications and, therefore, have to change how they developed software how they used to. They all need to be re-educated on what cloud-native means, and they also need to understand the key concepts of k8s for writing optimal software for it.</span><br />
<br />
<h2 style='display: inline'>The younger generation of IT professionals</h2><br />
<br />
<span>Maybe the younger generation knows all of this already after graduation, but then they are missing other critical parts of the system for sure. I have seen engineers who knew about containers and how to configure resource restrictions for a Docker container managed via k8s but have never heard the terms Linux control groups and Linux namespaces. So obviously, there is some knowledge gap of the underlying architecture. This can be a big problem when you have to troubleshoot such a system during a production incident and k8s adds a lot of abstraction to the mix which doesn&#39;t make it easier. </span><br />
<br />
<span>Coming back to COBOL, k8s is on its way to becoming something similar. One day, k8s might not be the hottest tech stuff everyone wants to use. But there will be still many legacy k8s clusters around but not enough experts available to manage those:</span><br />
<br />
<a class='textlink' href='https://www.techrepublic.com/article/why-kubernetes-is-our-modern-day-cobol-says-a-tech-expert/'>https://www.techrepublic.com/article/why-kubernetes-is-our-modern-day-cobol-says-a-tech-expert/</a><br />
<br />
<span>Another article which stroke me is:</span><br />
<br />
<a class='textlink' href='https://it.slashdot.org/story/21/09/23/163212/todays-students-dont-understand-the-basics-of-computer-operations'>Today&#39;s Students Don&#39;t Understand the Basics of Computer Operations </a><br />
<br />
<span>And here is something to smile about:</span><br />
<br />
<a class='textlink' href='https://christine.website/blog/theres-a-node-2021-10-02'>https://christine.website/blog/theres-a-node-2021-10-02</a><br />
<br />
<h1 style='display: inline'>The bloated web</h1><br />
<br />
<span>Another example is the modern web. Have you ever wondered why the internet becomes slower and slower nowadays? The modern web is so much like lasagna that I decided to use Gemini to be the primary protocol of my website. The HTML version of this website is just a fallback as many visitors don&#39;t know what Gemini is and don&#39;t have any compatible software installed for surfing the Geminispace:</span><br />
<br />
<a class='textlink' href='2021-04-24-welcome-to-the-geminispace.html'>2021-04-24-welcome-to-the-geminispace.html</a><br />
<br />
<span>The Gemtext protocol is KISS. There&#39;s no way to do other formattings than headings, links, paragraphs, lists, quotes, and bare text blocks (e.g., ASCII art or code snippets). There&#39;s no way to create bloated Gemini sites, and due to its limited capabilities, there&#39;s also no way to commercialise it (e.g. there&#39;s no good way to track the site visitors as things like cookies don&#39;t exist). By design, the Gemini protocol can&#39;t be extended, so there is no chance to abuse it even in the future. Gemini sites will stay KISS forever, and there won&#39;t be any fancy HTML/JavaScript frameworks like we see on the modern web.</span><br />
<br />
<h1 style='display: inline'>Fancy log-management solutions</h1><br />
<br />
<span>Yet another example I want to bring up is DTail, the distributed log tail program I wrote. There are many great and fancy log-management solutions available to choose from, and they all seem complex to set up and maintain. The ELK stack, for example, requires you to operate an ElasticSearch cluster (or multiple, if you are geo-redundant), Logstash (different configurations and instances, depending on your infrastructure) and a Kibana web-frontend (which also needs to be highly available). I have operated ElasticSearch clusters on multiple occasions, and I must say that it is not an easy task to optimise it for the particular workload you might encounter. I also have seen many ES clusters operated by other people, and I have seen these clusters failing a lot (so it&#39;s not just me). The reduced complexity of DTail also makes it more robust against outages. You won&#39;t troubleshoot your distributed application very well if the log management infrastructure isn&#39;t working either.</span><br />
<br />
<a class='textlink' href='2021-04-22-dtail-the-distributed-log-tail-program.html'>2021-04-22-dtail-the-distributed-log-tail-program.html</a><br />
<br />
<span>I don&#39;t say that the ELK stack doesn&#39;t work, but it requires experts and additional hardware resources to support it. But instead, if you keep your infrastructure simple (e.g. only use DTail), it will maintain pretty much by itself. </span><br />
<br />
<h1 style='display: inline'>More KISS</h1><br />
<br />
<h2 style='display: inline'>The Adslowbe PDF Reader</h2><br />
<br />
<span>Another perfect example is the Adobe PDF reader. How can it be that the inventor of the PDF format creates such a terrible user experience with its official reader? The reader is awful bloated, and slow. There are much better alternatives around (especially for Linux and other UNIX like operating systems, look at Zathura for example). I believe the reason Adobe&#39;s reader is like this is featuritis, and 90% of the users don&#39;t use 90% of all available features. Less is more; keep it simple and stupid. </span><br />
<br />
<h2 style='display: inline'>The power of plain text files</h2><br />
<br />
<span>Speaking of file formats, never underestimate the power of plain text files.  Plain text files don&#39;t require any special software to be opened, and they outlive the software which created them in the first place. You will still be able to read a plain text file on a modern computer system ten (or twenty) years from now, but you probably won&#39;t be able to read such an old version of an Adobe Photoshop image file if the software required for reading that format isn&#39;t supported anymore and doesn&#39;t run anymore on modern computers.</span><br />
<br />
<h2 style='display: inline'>KISS for programmers</h2><br />
<br />
<span>Not to mention, keeping things simple and stupid also reduces the potential malicious attack surface. It&#39;s not just about the software and services you use and operate. It&#39;s also about the software you write. Here is a nice article about the KISS principle in software development:</span><br />
<br />
<a class='textlink' href='https://thevaluable.dev/kiss-principle-explained/'>https://thevaluable.dev/kiss-principle-explained/</a><br />
<br />
<h1 style='display: inline'>When KISS is not KISS anymore</h1><br />
<br />
<span>There is, however, a trap. The more you spend time with things, the more these things feel natural to you and you become an expert. The more you become an expert, the more you introduce more abstractions and other clever ways of doing things. For you, things seem to be KISS still, but another person may not be an expert and might not understand what you do. One of the fundamental challenges is to keep things really KISS. You might add abstraction upon abstraction to a system and don&#39;t even notice it until it is too late.</span><br />
<br />
<h2 style='display: inline'>Other relevant readings</h2><br />
<br />
<a class='textlink' href='https://unixsheikh.com/articles/is-the-madness-ever-going-to-end.html'>Is the madness ever going to end?</a><br />
<a class='textlink' href='https://sive.rs/plaintext'>Write plain text files</a><br />
<br />
<span>Enough ranted for now!</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<span class='quote'>Controversially, a lack of features is a feature. Enjoy your peace an quiet. - Michael W Lucas </span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>On being Pedantic about Open-Source</title>
        <link href="gemini://foo.zone/gemfeed/2021-08-01-on-being-pedantic-about-open-source.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-08-01-on-being-pedantic-about-open-source.gmi</id>
        <updated>2021-08-01T10:37:58+03:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I believe that it is essential to always have free and open-source alternatives to any kind of closed-source proprietary software available to choose from. But there are a couple of points you need to take into consideration. </summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>On being Pedantic about Open-Source</h1><br />
<br />
<span class='quote'>Published at 2021-08-01T10:37:58+03:00; Updated at 2023-01-23</span><br />
<br />
<pre>
                                           __
                               _____....--&#39; .&#39;
                     ___...---&#39;._ o      -`(
           ___...---&#39;            \   .--.  `\
 ___...---&#39;                      |   \   \ `|
|                                |o o |  |  |
|                                 \___&#39;.-`.  &#39;.
|                                      |   `---&#39;
&#39;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&#39; LGB - Art by lgbearrd
</pre>
<br />
<span>I believe that it is essential to always have free and open-source alternatives to any kind of closed-source proprietary software available to choose from. But there are a couple of points you need to take into consideration. </span><br />
<br />
<h2 style='display: inline'>The costs of open-source</h2><br />
<br />
<span>One benefit of using open-source software is that it doesn&#39;t cost anything, right? That&#39;s correct in many cases. However, in some cases you still need to spend a significant amount of time configuring the software to work for you. It will be more expensive to use open-source software than proprietary commercial one if you aren&#39;t careful. </span><br />
<br />
<span>Not to say that I haven&#39;t seen the same effect with commercial software where people had to, after buying it, put a bunch of effort to make it work due to the lack of quality or due to high complexity. But that&#39;s either bad luck or bad decision-making. Most commercial providers  I have worked with try to make it work for you, so you also will buy other products and services from them later on and don&#39;t lose you as a happy customer.</span><br />
<br />
<h2 style='display: inline'>Commercial providers</h2><br />
<br />
<span>Producers of commercial software want to earn money after all. This is to grow their businesses and also to be able to pay their employees, who also need to care for their families. Employees build up their careers, build houses, and are proud of their accomplishments in the company.</span><br />
<br />
<span>So per se, commercial software is not a bad thing. Right? At least, commercial closed-source software is not a bad thing in its heart. Unfortunately, some companies have to keep their software closed-source to not lose their competitive edge over other competitors. </span><br />
<br />
<h2 style='display: inline'>Earning on open-source</h2><br />
<br />
<span>There are also companies that earn on open-source software. All the code they write is free for download and use, but you, as a customer, could pay for service and support if you are not an expert and can&#39;t manage it by yourself. </span><br />
<br />
<span>I like this approach, as you can balance the effort and costs the way it suits you best, and in doubt, you can audit the source code. Are you already an expert? Perfect, you don&#39;t need to buy additional support for the software. Everything can be set up by yourself, given that you have the time and priority.</span><br />
<br />
<span>Also, once an open-source project reached a certain size, it is unlikely to be abandoned one day. As long as at least one person is willing to be the open-source maintainer, the project won&#39;t die. Whereas commercial providers can decide from today to tomorrow to retire software or go bankrupt (unless you purchase Microsoft Word, I don&#39;t believe it will die anytime soon). </span><br />
<br />
<h2 style='display: inline'>Open-source organizations and individual contributors</h2><br />
<br />
<span>Besides corporations, millions of individual open-source contributors write free and open-source software not for money but for pleasure. Often, they are organized in non-profit organizations, working together to reach a common goal (it is worth mentioning that there are also many professionals, payed by large corporations, working full-time for non-profit open-source projects in order to push the features and reach the goals of the corporations). Sometimes, people don&#39;t agree on the project goal, so it gets forked, which can be a good thing. The more diversity, the better, as this is where competition and innovation happens. Also, the end user will end up with more choices. </span><br />
<br />
<span>These open-source projects are of a very high quality standard and are rock-solid, if not better, alternatives to proprietary counterparts. If the project isn&#39;t backed by a large corporation already, you should donate to these open-source organizations and/or individual contributors. I have donated to some projects I use personally. Do you learn a foreign language and use Anki flashcards? It&#39;s entirely free and open-source, and they happily accept donations ensuring future maintenance and development.</span><br />
<br />
<h2 style='display: inline'>Lesser known projects and the charm of clunkiness</h2><br />
<br />
<span>Looking at the smaller, lesser-known open-source projects (not talking about established open-source projects like FreeBSD and Linux): You can&#39;t, however, expect the software to be perfect and bug-free. After all, most of the code is written for pleasure and fun in the developers&#39; free time. Besides the developer himself, you might be the only user of the project. The software may be a bit clunky to use, and probably bugs are lurking around, and it might only work for a very specific use case.</span><br />
<br />
<span>Clunkiness can be charmful, though. And it can also encourage you to contribute code to make it better. There is a lot of such code in personal GitHub and GitLab repositories. The quality of such small open-source projects varies drastically. Many hobbyist programmers see programming as an art and put tons of effort into their projects. Others upload broken crap, which is dangerous to use. So have a look at the code before you use it!</span><br />
<br />
<h2 style='display: inline'>The security aspect</h2><br />
<br />
<span>One of the main conceptions about open-source software is that it is more secure than closed-source software because everybody can read and fix the code. Is that actually true? You can only be sure when you audit the code by yourself. If you are like me, you won&#39;t have time to audit all the open-source software you use. It&#39;s impossible to audit more than 100 million lines of Linux kernel code. Static code analysis tools come in handy here, but they still require humans to look at the results.</span><br />
<br />
<span>Security bugs in open-source projects are exposed to the public and fixed quickly, while we don&#39;t know exactly what happens to security bugs in closed-source ones. Still, hackers and security specialists can find them through reverse engineering and penetration testing. Overall, thinking of security, In my opinion it is still better to prefer open-source software because the more significant the project, the higher the probability that security bugs are found and fixed as more parties are looking into it. Furthermore, provided you have the necessary resources, you could still deduct an audit by yourself. The latter especially happens when companies with its own security and penetration testing departments are evaluating the use of open-source. This is something not every company can afford though.</span><br />
<br />
<h2 style='display: inline'>Always watch out for open-source alternatives</h2><br />
<br />
<span>Do you need Microsoft Word? Why don&#39;t you just use the Vim text editor or GNU Emacs to write your letters? If that&#39;s too nerdy, you can still use open-source alternatives such as AbiWord or LibreOffice. Larger organizations have the tendency to standardize the software their employees have to use. Unfortunately, as Microsoft Word is the de-facto standard text processing program, most companies prefer Word over LibreOffice. Same with Microsoft Excel vs LibreOffice Calc or other spreadsheet alternatives like Gnumeric. I don&#39;t know why that is; please....</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<span>I only use free and open-source operating systems on my personal Laptops, Desktop PCs and servers (FreeBSD and Linux based ones). Most of the programs and apps I use on them are free and open-source as well, and I am comfortable with it for over twenty years. Exceptions are the BIOSes and some firmwares of my devices. I also use Skype as most of my friends and family are using it. They are, unfortunately, proprietary software still. But I will be looking into Matrix as a Skype alternative when I have time. There are also open BIOS alternatives, but they usually don&#39;t work on my devices.</span><br />
<br />
<h2 style='display: inline'>What about mobile?</h2><br />
<br />
<span class='quote'>Update 2023-01-21: Check out my newer post about GrapheneOS, which solves some of my dilemmas</span><br />
<br />
<a class='textlink' href='./2023-01-23-why-grapheneos-rox.html'>Why GrapheneOS Rox</a><br />
<br />
<span>I struggle to go 100% open-source on my Smartphone. I use a Samsung phone with the stock Android as provided by Samsung. I love the device as it is large enough to use as a portable reading and note-taking device, and it can also take decent pictures. As a cloud backup solution, I have my own NextCloud server (open-source). Android is mainly open-source software, but many closed parts are still included. I replaced most of the standard apps with free and open-source variants from the F-Droid store though.</span><br />
<br />
<span>I could get a LineageOS based phone to get rid of the proprietary Android parts (I tried that out a couple of times in the past). But then a couple of convenient apps, such as Google Maps or Banking or Skype or the E-Ticket apps of various Airlines, various review apps when searching for restaurants, Audible (I think Audible offers an excellent service), etc., won&#39;t work anymore. The proprietary Google Maps is still the best maps app, even though there are open alternatives available. It&#39;s not that I couldn&#39;t live without these apps, but they make life a lot more convenient.</span><br />
<br />
<h2 style='display: inline'>Know the alternatives</h2><br />
<br />
<span>Thinking about alternative solutions is always a good idea. My advice is never to be entirely dependant on any proprietary software. Before you decide to use proprietary software, try to find alternatives in the open-source world. You might need to invest some time playing around with the options available. Maybe they are good enough for you, or maybe not.</span><br />
<br />
<span>If you still want to use proprietary software, use it with caution. Have a look at the recent change at Google Photos: For a long time, "high quality" photos could be uploaded there quota-less for free. However, Google recently changed the model so that people exceeding a quota have to start paying for the extra space consumed. I am not against Google&#39;s decision, but it shows you that a provider can always change its direction. So you can&#39;t entirely rely on these. I repeat myself: Don&#39;t fully rely on anything proprietary, but you might still use proprietary software or services for your own convenience.</span><br />
<br />
<h2 style='display: inline'>You can&#39;t control it all</h2><br />
<br />
<span>The biggest problem I have with going 100% open-source is actually time. You can&#39;t control all the software you use or might be using in the future. You have only a finite amount of time available in your life. So you have to decide what&#39;s more important: Investigate and use an open-source alternative of every program and app you have installed, or rather spend quality time with your family and have a nice walk in the park or go to a sports class or cook a nice meal? You can&#39;t control it all in today&#39;s world of tech, not as a user and even not as a tech worker. There&#39;s a great blog post worth reading: </span><br />
<br />
<a class='textlink' href='https://unixsheikh.com/articles/how-to-stay-sane-in-todays-world-of-tech.html'>https://unixsheikh.com/articles/how-to-stay-sane-in-todays-world-of-tech.html</a><br />
<br />
<h2 style='display: inline'>The middle way</h2><br />
<br />
<span>Regarding my personal Smartphone dilemma: I guess the middle way is to use two phones: </span><br />
<br />
<ul>
<li>Have a secondary, proprietary Android phone with Google Play store (or an Apple iPhone if this is more your thing) and all its benefits for occasional use. Use the proprietary phone only with intention. Such a phone implies some risks regarding your privacy. If you aren&#39;t careful, app providers will collect your personal data for building a digital profile of you, which gets used for online advertisement and other things. This doesn&#39;t only applies to the Smartphone, this also applies to some proprietary software (including cloud services such as Google Photos) you use on your home computer or websites you visit (I am looking at you, Facebook, Twitter and friends). Try to disable all tracking features on such a phone. It&#39;s not a guarantee that nobody will be collecting data from you anymore, but you should take at least the chance. Cal Newport once mentioned that you should not use privacy concerning apps as much anyway and instead spend more time on things which matter.</li>
<li>Have a primary phone, entirely based on free and open-source software. There will be probably no app collecting your personal data. Try to use the primary phone for all of your everyday activities and fall back to the proprietary phone only for particular use cases. Once there is decent hardware (with a decent camera) running Linux (such as Mobian, for example) available, I will consider a purchase. The only 3rd party which then will still be able to track you will be your network provider. You could start your own phone network, but that seems overkill. There is already the Pinephone and the Librem 5 running a real Linux (Android is Linux based, but it doesn&#39;t count as a real Linux for me). Still, I want to wait a bit longer for better hardware to be available (I want to have a good camera always with me).</li>
<li>You could also add a tertiary phone to the mix, which you only use for work and nothing else. That one will be very likely a proprietary phone too. You only have to keep this one around when you are working or when you are on-call.</li>
</ul><br />
<span>I have been playing with other smartphone OS alternatives, especially with MeeGo (which has died already) and SailfishOS, too. Security and privacy seem to be significantly improved compared to an Android. As a matter of fact, I bought a cheap and used Sony Xperia XA2 last year and installed SailfishOS on it. It&#39;s a nice toy, but it&#39;s still not the holy open-source grail as there are also proprietary parts in SailfishOS. Platforms such as Mobian, Ubuntu Touch and Plasma Mobile are more compelling to me. People must explore alternatives to Android and Apple here, as otherwise, you won&#39;t own any gadgets anymore:</span><br />
<br />
<a class='textlink' href='https://news.slashdot.org/story/21/07/10/0120236/by-2030-you-wont-own-any-gadgets'>https://news.slashdot.org/story/21/07/10/0120236/by-2030-you-wont-own-any-gadgets</a><br />
<br />
<span>Anyhow, any gadgets, including your phone, should be a tool you use. Don&#39;t let the phone use you!</span><br />
<br />
<h2 style='display: inline'>The downside of being a nobody</h2><br />
<br />
<span>Be aware that it might be to your disadvantage if you manage to go completely under cover without anyone collecting data from you. Suppose you are a nobody on the web (no social media profiles, no tracking history, etc.). In that case, you aren&#39;t behaving like the mass, and therefore you are suspicious. So it might be even a good thing to leave your marks here and there once in a while. You aren&#39;t hiding anything anyway, correct? Just be mindful what you are sharing about yourself. I share personal things very rarely on Facebook for example. And I only share a small subset of my personal life on my personal homepage and this blog and on all of my social media accounts. Nobody is interested in what I have for breakfast anyway I guess. Write me an E-Mail if you are interested in what I am having for breakfast.</span><br />
<br />
<h2 style='display: inline'>Mobile open-source OSes are still evolving</h2><br />
<br />
<span>You might have noticed that I wrote a lot about Smartphones in this article. The reason is that free and open-source software for Smartphones is still evolving. In contrast, for Laptops and Desktop PCs, it&#39;s already there. There is no reason to use proprietary operating systems such as Windows or macOS on your computers unless your employer forces you to use one of these. Why would they force you? It has to do with standardization again. The IT department only can manage so many platforms. It wouldn&#39;t be manageable by IT if every employee would install their own Linux distribution or one of the *BSDs. That might work for small startups but not for larger companies, especially not for a security-focused companies.</span><br />
<br />
<span>I would love a standardized Linux at work, though. Dell and Lenovo also officially support Linux on their notebooks. The culprit may be knowledgeable IT staff maintaining and giving support to the Desktop Linux users. Not all colleagues are Linux geeks like you and me. I am using macOS for work, but I am not an Apple expert. Occasionally I have to contact IT support regarding some issues I have. I don&#39;t use the macOS GUI a lot; I mainly live in the terminal so I can run the same tools I also use on Linux.</span><br />
<br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>Should you be pedantic about open-source software? It depends. It depends on your fundamental values and how much time you are ready to invest. Open-source software is not just free as in money, but also free as in freedom. You will gain back complete control of your personal data. Unfortunately, installing ready proprietary apps from the Play Store is much more convenient than building up a trustworthy open-source-based infrastructure by yourself. As a guideline, use proprietary software and services with caution. Be mindful about your choices and where you leave your digital fingerprints. In doubt, think less is more. Do you really need this new shiny app? What benefit does it provide to you? Probably you don&#39;t really need that shiny new app.</span><br />
<br />
<span>You have better chances when you know how to manage your own server and install and manage alternatives to the big cloud providers by yourself. I have the advantage that I have work experience as a Linux Systems Administrator here. I mentioned NextCloud already. I use NextCloud for online photo and file storage, contact and calendar sync and as an RSS news feed server. You could do the same with your own E-Mail server, you can also host your own website and blog. I also mentioned Matrix as a Skype alternative (which could also be an alternative to WhatsApp, Skype, Telegram, Viber, ...). I don&#39;t know a lot about Matrix yet, but it seems to be a very neat alternative. I am ready to invest time in it as one of my future personal pet projects. Not only because I think it&#39;s better, but also because for fun and as a hobby. But this doesn&#39;t mean that I invest *all* of my personal free time in it.</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>The Well-Grounded Rubyist</title>
        <link href="gemini://foo.zone/gemfeed/2021-07-04-the-well-grounded-rubyist.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-07-04-the-well-grounded-rubyist.gmi</id>
        <updated>2021-07-04T10:51:23+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>When I was a Linux System Administrator, I have been programming in Perl for years. I still maintain some personal Perl programming projects (e.g. Xerl, guprecords, Loadbars). After switching jobs a couple of years ago (becoming a Site Reliability Engineer), I found Ruby (and some Python) widely used there. As I wanted to do something new, I decided to give Ruby a go.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>The Well-Grounded Rubyist</h1><br />
<br />
<span class='quote'>Published at 2021-07-04T10:51:23+01:00</span><br />
<br />
<span>When I was a Linux System Administrator, I have been programming in Perl for years. I still maintain some personal Perl programming projects (e.g. Xerl, guprecords, Loadbars). After switching jobs a couple of years ago (becoming a Site Reliability Engineer), I found Ruby (and some Python) widely used there. As I wanted to do something new, I decided to give Ruby a go.</span><br />
<br />
<span>You should learn or try out one new programming language once yearly anyway. If you end up not using the new language, that&#39;s not a problem. You will learn new techniques with each new programming language and this also helps you to improve your overall programming skills even for other languages. Also, having some background in a similar programming language makes it reasonably easy to get started. Besides that, learning a new programming language is kick-a** fun!</span><br />
<br />
<a href='./2021-07-04-the-well-grounded-rubyist/book-cover.jpg'><img src='./2021-07-04-the-well-grounded-rubyist/book-cover.jpg' /></a><br />
<br />
<span>Superficially, Perl seems to have many similarities to Ruby (but, of course, it is entirely different to Perl when you look closer), which pushed me towards Ruby instead of Python. I have tried Python a couple of times before, and I managed to write good code, but I never felt satisfied with the language. I didn&#39;t love the syntax, especially the indentations used; they always confused me. I don&#39;t dislike Python, but I don&#39;t prefer to program in it if I have a choice, especially when there are more propelling alternatives available. Personally, it&#39;s so much more fun to program in Ruby than in Python.</span><br />
<br />
<a href='./2021-07-04-the-well-grounded-rubyist/book-backside.jpg'><img src='./2021-07-04-the-well-grounded-rubyist/book-backside.jpg' /></a><br />
<br />
<span>Yukihiro Matsumoto, the inventor of Ruby, said: "I wanted a scripting language that was more powerful than Perl and more object-oriented than Python" - So I can see where some of the similarities come from. I personally don&#39;t believe that Ruby is more powerful than Perl, though, especially when you take CPAN and/or Perl 6 (now known as Raku) into the equation. Well, it all depends on what you mean with "more powerful". But I want to stay pragmatic and use what&#39;s already used at my workplace.</span><br />
<br />
<h2 style='display: inline'>My Ruby problem domain</h2><br />
<br />
<span>I wrote a lot of Ruby code over the last couple of years. There were many small to medium-sized tools and other projects such as Nagios monitoring checks, even an internal monitoring &amp; reporting site based on Sinatra. All Ruby scripts I wrote do their work well; I didn&#39;t encounter any significant problems using Ruby for any of these tasks. Of course, there&#39;s nothing that couldn&#39;t be written in Perl (or Python), though, after all, these languages are all Turing-complete and all these languages also come with a huge set of 3rd party libraries :-).</span><br />
<br />
<span>I don&#39;t use Ruby for all programming projects, though. </span><br />
<br />
<ul>
<li>I am using Bash for small sized (usually below 500 lines of code) scripts and ad-hoc command-line automation.</li>
<li>I program in Google Go for more complex tools (such as DTail) and for problem solving involving data crunching.</li>
<li>Occasionally, I write some lines of Java code for minor feature enhancements and fixes to improve the reliability of some the services.</li>
<li>Sometimes, I still program in good old C. This is for special projects (e.g. I/O Riot) or low-level PoCs or SystemTap guru mode scripts.</li>
</ul><br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>Also have a look at my personal Bash coding style.</a><br />
<a class='textlink' href='./2021-04-22-dtail-the-distributed-log-tail-program.html'>Read here about DTail - the distributed log tail program.</a><br />
<a class='textlink' href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux.html'>This is a magazine article about I/O Riot I wrote.</a><br />
<br />
<span>For all other in-between tasks I mainly use the Ruby programming language (unless I decide to give something new a shot once in a while).</span><br />
<br />
<h2 style='display: inline'>Being stuck in Ruby-mediocrity</h2><br />
<br />
<span>As a Site Reliability Engineer there were many tasks and problems to be solved as efficiently and quickly as possible and, of course, without bugs. So I learned Ruby relatively fast by doing and the occasional web search for "how to do thing X". I always was eager to get the problem at hand solved and as long as the code solved the problem I usually was happy.</span><br />
<br />
<span>Until now, I never read a whole book or took a course on Ruby. As a result, I found myself writing Ruby in a Perl-ish procedural style (with Perl, you can do object-oriented programming too, but Perl wasn&#39;t designed from the ground up to be an object-oriented language). I didn&#39;t take advantage of all the specialities Ruby has to offer as I invested most of my time in the problems at hand and not in the Ruby idiomatic way of doing things.</span><br />
<br />
<span>An unexpected benefit was that most of my Ruby code (probably not all, there are always dark corners in some old code bases lurking around) was easy to follow and extend or fix, even by people who usually don&#39;t speak Ruby, as there wasn&#39;t too much magic involved in my code - However, I could have done better still. Looking at other Ruby projects, I noticed over time that there is so much more to the language I wanted to explore. For example new techniques and the Ruby best practise, and much more about how things work under the hood, I wanted to learn about.</span><br />
<br />
<h2 style='display: inline'>O&#39;Reilly Safari Books Online</h2><br />
<br />
<span>I do have an O&#39;Reilly Safari Online subscription (thank you, employer). To my liking, I found the "The Well-Grounded Rubyist" book there (the text version and also the video version of it). I watched the video version for a couple of weeks, chunking the content into small pieces so it was able to fit into my schedule, increasing the playback speed for the topics I knew already well enough and slowed it down to actual pace when there was something new to learn and occasionally jumped back to the text book to review what I just learned. To my satisfaction, I was already familiar with over half of the language. But there was still the big chunk, especially how the magic happens under the hood in Ruby, which I missed out on, but I am happy now to be aware of it now.</span><br />
<br />
<span>I also loved the occasional dry humour in the book: "An enumerator is like a brain in a science fiction movie, sitting on a table with no connection to a body but still able to think". :-)</span><br />
<br />
<span>Will I rewrite and refactor all of my existing Ruby programs? Probably not, as they all do their work as intended. Some of these scripts will be eventually replaced or retired. But depending on the situation, I might refactor a module, class or a method or two once in a while. I already knew how to program in an object-oriented style from other languages (e.g. Java, C++, Perl Moose and plain) before I started Ruby, so my existing Ruby code is not as bad as you might assume after reading this article :-). In contrast to Java/C++, Ruby is a dynamic language, and the idiomatic ways of doing things differs from statically typed languages.</span><br />
<br />
<h2 style='display: inline'>Key takeaways</h2><br />
<br />
<span>These are my key takeaways. These only point out some specific things I have learned, and represent, by far, not everything I&#39;ve learned from the book.</span><br />
<br />
<h3 style='display: inline'>"Everything" is an object</h3><br />
<br />
<span>In Ruby, everything is an object. However, Ruby is not Smalltalk. It depends on what you mean by "everything". Fixnums are objects. Classes also are, as instances of class Class. Methods, operators and blocks aren&#39;t but can be wrapped by objects via a "Proc". A simple assignment is not and can&#39;t. Statements like "while" also aren&#39;t and can&#39;t. Comments obviously also fall in the latter group. Ruby is more object-oriented than everything else I have ever seen, except for Smalltalk.</span><br />
<br />
<span>In Ruby, like in Java/C++, classes are classes, objects are instances of classes, and there are class inheritances. There is single inheritance in Ruby, but with the power of mixing in modules, you can extend your classes in a better way than multiple class inheritances (like in C++) would allow. It&#39;s also different to Java interfaces, as interfaces in Java only come with the method prototypes and not with the actual method implementations like Ruby modules.</span><br />
<br />
<h3 style='display: inline'>"Normal" objects and singleton objects</h3><br />
<br />
<span>In Ruby, you can also have singleton objects. A singleton object can be an instance of a class but be modified after its creation (e.g. a method added to only this particular instance after its instantiation). Or, another variant of a singleton object is a class (yes, classes are also objects in Ruby). All of that is way better described in the book, so have a read by yourself if you are confused now; just remember: Rubys object system is very dynamic and flexible. At runtime, you can add and modify classes, objects of classes, singleton objects and modules. You don&#39;t need to restart the Ruby interpreter; you can change the code during runtime dynamically through Ruby code.</span><br />
<br />
<h3 style='display: inline'>Domain specific languages</h3><br />
<br />
<span>Due to Ruby&#39;s flexibility through object individualization (e.g. adding methods at runtime, or changing the core behaviour of classes, catching unknown method calls and dynamically dispatch and/or generate the missing methods via the "method_missing" method), Ruby is a very good language to write your own small domain specific language (DSL) on top of Ruby syntax. I only noticed that after reading this book. Maybe, this is one of the reasons why even the configuration management system Puppet once tried to use a Ruby DSL instead of the Puppet DSL for its manifests. I am not sure why the project got abandoned though, probably it has to do with performance. Do be honest, Ruby is not the fastest language, but it is fast enough for most use cases. And, especially from Ruby 3, performance is one of the main things being worked on currently. If I want performance, I can always use another programming language.</span><br />
<br />
<h3 style='display: inline'>Ruby is "self-ish"</h3><br />
<br />
<span>Ruby will fall back to the default "self" object if you don&#39;t specify an object method receiver. To give you an example, some more explanation is needed: There is the "Kernel" module mixed into almost every Ruby object. For example, "puts" is just a method of module "Kernel". When you write "puts :foo", Ruby sends the message "puts" to the current object "self". The class of object "self" is "Object". Class Object has module "Kernel" mixed in, and "Kernel" defines the method "puts". </span><br />
<br />
<pre>
&gt;&gt; self
=&gt; main
&gt;&gt; self.class
=&gt; Object
&gt;&gt; self.class.included_modules
=&gt; [PP::ObjectMixin, Kernel]
&gt;&gt; Kernel.class
=&gt; Module
&gt;&gt; Kernel.methods.grep(/puts/)
=&gt; [:puts]
&gt;&gt; puts &#39;Hello Ruby&#39;
Hello Ruby
=&gt; nil
&gt;&gt; self.puts &#39;Hello World&#39;
Hello World
=&gt; nil
</pre>
<br />
<span>Ruby offers a lot of syntactic sugar and seemingly magic, but it all comes back to objects and messages to objects under the hood. As all is hidden in objects, you can unwrap and even change the magic and see what&#39;s happening under the hood. Then, suddenly everything makes so much sense.</span><br />
<br />
<h3 style='display: inline'>Functional programming</h3><br />
<br />
<span>Ruby embraces an object-oriented programming style. But there is good news for fans of the functional programming paradigm: From immutable data (frozen objects), pure functions, lambdas and higher-order functions, lazy evaluation, tail-recursion optimization, method chaining, currying and partial function application, all of that is there. I am delighted about that, as I am a big fan of functional programming (having played with Haskell and Standard ML before).</span><br />
<br />
<span>Remember, however, that Ruby is not a pure functional programming language. You, the Rubyist, need to explicitly decide when to apply a functional style, as, by heart, Ruby is designed to be an object-oriented language. The language will not enforce side effect avoidance, and you will have to enable tail-recursion optimization (as of Ruby 2.5) explicitly, and variables/objects aren&#39;t immutable by default either. But that all does not hinder you from using these features. </span><br />
<br />
<span>I liked this book so much so that I even bought myself a (used) paper copy of it. To my delight, there was also a free eBook version in ePub format included, which I now have on my Kobo Forma eBook reader. :-)</span><br />
<br />
<h2 style='display: inline'>Perl</h2><br />
<br />
<span>Will I abandon my beloved Perl? Probably not. There are also some Perl scripts I use at work. But unfortunately I only have a limited amount of time and I have to use it wisely. I might look into Raku (formerly known as Perl 6) next year and use it for a personal pet project, who knows. :-). I also highly recommend reading the two Perl books "Modern Perl" and "Higher-Order Perl".</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Gemtexter - One Bash script to rule it all</title>
        <link href="gemini://foo.zone/gemfeed/2021-06-05-gemtexter-one-bash-script-to-rule-it-all.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-06-05-gemtexter-one-bash-script-to-rule-it-all.gmi</id>
        <updated>2021-06-05T19:03:32+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>You might have read my previous blog posts about entering the Geminispace, where I pointed out the benefits of having and maintaining an internet presence there. This whole site (the blog and all other pages) is composed in the Gemtext markup language.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Gemtexter - One Bash script to rule it all</h1><br />
<br />
<span class='quote'>Published at 2021-06-05T19:03:32+01:00</span><br />
<br />
<pre>
                                                               o .,&lt;&gt;., o
                                                               |\/\/\/\/|
                                                               &#39;========&#39;
                                                               (_ SSSSSSs
                                                               )a&#39;`SSSSSs
                                                              /_   SSSSSS
                                                              .=## SSSSS
                                                              .####  SSSSs
                                                              ###::::SSSSS
                                                             .;:::""""SSS
                                                            .:;:&#39;  . .  \\
                                                           .::/  &#39;     .&#39;|
                                                          .::( .         |
                                                          :::)           \
                                                          /\(            /
                                                         /)            ( |
                                                       .&#39;  \  .       ./ /
                                                    _-&#39;    |\  .        |
                                  _..--..   .  /"---\      | ` |      . |
          -=====================,&#39; _     \=(*#(7.#####()   |  `/_..   , (
                      _.-&#39;&#39;``&#39;;&#39;-&#39;&#39;-) ,.  \ &#39;  &#39;+/// |   .&#39;/   \  ``-.) \
                    ,&#39;  _.-  ((    `-&#39;  `._\    `` \_/_.&#39;  )    /`-._  ) |
                  ,&#39;\ ,&#39;  _.&#39;.`:-.    \.-&#39;                 /   &lt;_L   )"  |
                _/   `._,&#39; ,&#39;)`;  `-&#39;`&#39;                    |     L  /    /
               / `.   ,&#39; ,|_/ / \                          (    &lt;_-&#39;     \
               \ / `./  &#39;  / /,&#39; \                        /|`         `. |
               )\   /`._   ,&#39;`._.-\                       |)            \&#39;
              /  `.&#39;    )-&#39;.-,&#39; )__)                      |\            `|
             : /`. `.._(--.`&#39;:`&#39;:/ \                      ) \             \
             |::::\     ,&#39;/::;-))  /                      ( )`.            |
             ||:::::  . .::&#39;:  :`-(                       |/    .          |
             ||::::|  . :|  |==[]=:                       .        -       \
             |||:::|  : ||  :  |  |                      /\           `     |
 ___ ___     &#39;|;:::|  | |&#39;   \=[]=|                     /  \                \
|   /_  ||``|||:::::  | ;    | |  |                     \_.&#39;\_               `-.
:   \_``[]--[]|::::&#39;\_;&#39;     )-&#39;..`._                 .-&#39;\``:: ` .              \
 \___.&gt;`&#39;&#39;-.||:.__,&#39;     SSt |_______`&gt;              &lt;_____:::.         . . \  _/
                                                           `+a:f:......jrei&#39;&#39;&#39;
</pre>
<br />
<span>You might have read my previous blog posts about entering the Geminispace, where I pointed out the benefits of having and maintaining an internet presence there. This whole site (the blog and all other pages) is composed in the Gemtext markup language.</span><br />
<br />
<span>This comes with the benefit that I can write content in my favourite text editor (Vim). </span><br />
<br />
<h2 style='display: inline'>Motivation</h2><br />
<br />
<span>Another benefit of using Gemini is that the Gemtext markup language is easy to parse. As my site is dual-hosted (Gemini+HTTP), I could, in theory, just write a shell script to deal with the conversion from Gemtext to HTML; there is no need for a full-featured programming language here. I have done a lot of Bash in the past, but I am also often revisiting old tools and techniques for refreshing and keeping the knowledge up to date here.</span><br />
<br />
<a href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all/blog-engine.jpg'><img alt='Motivational comic strip' title='Motivational comic strip' src='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all/blog-engine.jpg' /></a><br />
<br />
<span>I have exactly done that - I wrote a Bash script, named Gemtexter, for that:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/gemtexter'>https://codeberg.org/snonux/gemtexter</a><br />
<br />
<span>In short, Gemtexter is a static site generator and blogging engine that uses Gemtext as its input format.</span><br />
<br />
<h2 style='display: inline'>Output formats</h2><br />
<br />
<span>Gemtexter takes the Gemtext Markup files as the input and generates the following outputs from it (you find examples for each of these output formats on the Gemtexter GitHub page):</span><br />
<br />
<ul>
<li>HTML files for my website</li>
<li>Markdown files for a GitHub page</li>
<li>A Gemtext Atom feed for my blog posts</li>
<li>A Gemfeed for my blog posts (a particular feed format commonly used in Geminispace. The Gemfeed can be used as an alternative to the Atom feed).</li>
<li>An HTML Atom feed of my blog posts</li>
</ul><br />
<span>I could have done all of that with a more robust language than Bash (such as Perl, Ruby, Go...), but I didn&#39;t. The purpose of this exercise was to challenge what I can do with a "simple" Bash script and learn new things.</span><br />
<br />
<h2 style='display: inline'>Taking it as far as I should, but no farther</h2><br />
<br />
<span>The Bash is suitable very well for small scripts and ad-hoc automation on the command line. But it is for sure not a robust programming language. Writing this blog post, Gemtexter is nearing 1000 lines of code, which is actually a pretty large Bash script.</span><br />
<br />
<h3 style='display: inline'>Modularization </h3><br />
<br />
<span>I modularized the code so that each core functionality has its own file in ./lib. All the modules are included from the main Gemtexter script. For example, there is one module for HTML generation, one for Markdown generation, and so on. </span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>paul <b><font color="#0000FF">in</font></b> uranus <b><font color="#0000FF">in</font></b> gemtexter on 🌱 main
❯ wc -l gemtexter lib<font color="#990000">/*</font>
    <font color="#993399">117</font> gemtexter
     <font color="#993399">59</font> lib/assert<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
    <font color="#993399">128</font> lib/atomfeed<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
     <font color="#993399">64</font> lib/gemfeed<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
    <font color="#993399">161</font> lib/generate<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
     <font color="#993399">50</font> lib/git<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
    <font color="#993399">162</font> lib/html<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
     <font color="#993399">30</font> lib/log<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
     <font color="#993399">63</font> lib/md<font color="#990000">.</font><b><font color="#0000FF">source</font></b><font color="#990000">.</font>sh
     <font color="#993399">834</font> total
</pre>
<br />
<span>This way, the script could grow far beyond 1000 lines of code and still be maintainable. With more features, execution speed may slowly become a problem, though. I already notice that Gemtexter doesn&#39;t produce results instantly but requires few seconds of runtime already. That&#39;s not a problem yet, though. </span><br />
<br />
<h3 style='display: inline'>Bash best practises and ShellCheck</h3><br />
<br />
<span>While working on Gemtexter, I also had a look at the Google Shell Style Guide and wrote a blog post on that:</span><br />
<br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>Personal bash coding style guide</a><br />
<br />
<span>I followed all these best practices, and in my opinion, the result is a pretty maintainable Bash script (given that you are fluent with all the sed and grep commands I used).</span><br />
<br />
<span>ShellCheck, a shell script analysis tool written in Haskell, is run on Gemtexter ensuring that all code is acceptable. I am pretty impressed with what ShellCheck found. </span><br />
<br />
<span>It, for example, detected "some_command | while read var; do ...; done" loops and hinted that these create a new subprocess for the while part. The result is that all variable modifications taking place in the while-subprocess won&#39;t reflect the primary Bash process. ShellSheck then recommended rewriting the loop so that no subprocess is spawned as "while read -r var; do ...; done &lt; &lt;(some_command)".  ShellCheck also pointed out to add a "-r" to "read"; otherwise, there could be an issue with backspaces in the loop data.</span><br />
<br />
<span>Furthermore, ShellCheck recommended many more improvements. Declaration of unused variables and missing variable and string quotations were the most common ones. ShellSheck immensely helped to improve the robustness of the script.</span><br />
<br />
<a class='textlink' href='https://shellcheck.net'>https://shellcheck.net</a><br />
<br />
<h3 style='display: inline'>Unit testing</h3><br />
<br />
<span>There is a basic unit test module in ./lib/assert.source.sh, which is used for unit testing. I found this to be very beneficial for cross-platform development. For example, I noticed that some unit tests failed on macOS while everything still worked fine on my Fedora Linux laptop. </span><br />
<br />
<span>After digging a bit, I noticed that I had to install the GNU versions of the sed and grep commands on macOS and a newer version of the Bash to make all unit tests pass and Gemtexter work.</span><br />
<br />
<span>It has been proven quite helpful to have unit tests in place for the HTML part already when working on the Markdown generator part. To test the Markdown part, I copied the HTML unit tests and changed the expected outcome in the assertions. This way, I could implement the Markdown generator in a test-driven way (writing the test first and afterwards the implementation).</span><br />
<br />
<h3 style='display: inline'>HTML unit test example</h3><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#009900">gemtext</font><font color="#990000">=</font><font color="#FF0000">'=&gt; http://example.org Description of the link'</font>
assert<font color="#990000">::</font>equals <font color="#FF0000">"$(generate::make_link html "</font><font color="#009900">$gemtext</font><font color="#FF0000">")"</font> <font color="#990000">\</font>
    <font color="#FF0000">'&lt;a class="textlink" href="http://example.org"&gt;Description of the link&lt;/a&gt;&lt;br /&gt;'</font>
</pre>
<br />
<h3 style='display: inline'>Markdown unit test example</h3><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#009900">gemtext</font><font color="#990000">=</font><font color="#FF0000">'=&gt; http://example.org Description of the link'</font>
assert<font color="#990000">::</font>equals <font color="#FF0000">"$(generate::make_link md "</font><font color="#009900">$gemtext</font><font color="#FF0000">")"</font> <font color="#990000">\</font>
    <font color="#FF0000">'[Description of the link](http://example.org)  '</font>
</pre>
<br />
<h2 style='display: inline'>Handcrafted HTML styles</h2><br />
<br />
<span>I had a look at some ready off the shelf CSS styles, but they all seemed too bloated. There is a whole industry selling CSS styles on the interweb. I preferred an effortless and minimalist style for the HTML site. So I handcrafted the Cascading Style Sheets manually with love and included them in the HTML header template. </span><br />
<br />
<span>For now, I have to re-generate all HTML files whenever the CSS changes. That should not be an issue now, but I might move the CSS into a separate file one day.</span><br />
<br />
<span>It&#39;s worth mentioning that all generated HTML files and Atom feeds pass the W3C validation tests.</span><br />
<span> </span><br />
<h2 style='display: inline'>Configurability</h2><br />
<br />
<span>In case someone else than me wants to use Gemtexter for his own site, it is pretty much configurable. It is possible to specify your own configuration file and your own HTML templates. Have a look at the GitHub page for examples.</span><br />
<br />
<h2 style='display: inline'>Future features</h2><br />
<br />
<span>I could think of the following features added to a future version of Gemtexter:</span><br />
<br />
<ul>
<li>Templating of Gemtext files so that the .gmi files are generated from .gmi.tpl files. The template engine could do such things as an automatic table of contents and sitemap generation. It could also include the output of inlined shell code, e.g. a fortune quote. </li>
<li>Add support for more output formats, such as Groff, PDF, plain text, Gopher, etc.</li>
<li>External CSS file for HTML.</li>
<li>Improve speed by introducing parallelism and/or concurrency and/or better caching.</li>
</ul><br />
<h2 style='display: inline'>Conclusion</h2><br />
<br />
<span>It was quite a lot of fun writing Gemtexter. It&#39;s a relatively small project, but given that I worked on that in my spare time once in a while, it kept me busy for several weeks. </span><br />
<br />
<span>I finally revamped my personal internet site and started to blog again. I wanted the result to be exactly how it is now: A slightly retro-inspired internet site built for fun with unconventional tools. </span><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2023-03-25-gemtexter-2.0.0-lets-gemtext-again-2.html'>2023-03-25 Gemtexter 2.0.0 - Let&#39;s Gemtext again²</a><br />
<a class='textlink' href='./2022-08-27-gemtexter-1.1.0-lets-gemtext-again.html'>2022-08-27 Gemtexter 1.1.0 - Let&#39;s Gemtext again</a><br />
<a class='textlink' href='./2022-01-01-bash-golf-part-2.html'>2022-01-01 Bash Golf Part 2</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>2021-11-29 Bash Golf Part 1</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all (You are currently reading this)</a><br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>2021-05-16 Personal Bash coding style guide</a><br />
<a class='textlink' href='./2021-04-24-welcome-to-the-geminispace.html'>2021-04-24 Welcome to the Geminispace</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Personal Bash coding style guide</title>
        <link href="gemini://foo.zone/gemfeed/2021-05-16-personal-bash-coding-style-guide.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-05-16-personal-bash-coding-style-guide.gmi</id>
        <updated>2021-05-16T14:51:57+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Lately, I have been polishing and writing a lot of Bash code. Not that I never wrote a lot of Bash, but now as I also looked through the Google Shell Style Guide, I thought it is time also to write my thoughts on that. I agree with that guide in most, but not in all points. </summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Personal Bash coding style guide</h1><br />
<br />
<span class='quote'>Published at 2021-05-16T14:51:57+01:00</span><br />
<br />
<pre>
   .---------------------------.
  /,--..---..---..---..---..--. `.
 //___||___||___||___||___||___\_|
 [j__ ######################## [_|
    \============================|
 .==|  |"""||"""||"""||"""| |"""||
/======"---""---""---""---"=|  =||
|____    []*          ____  | ==||
//  \\               //  \\ |===||  hjw
"\__/"---------------"\__/"-+---+&#39;
</pre>
<br />
<span>Lately, I have been polishing and writing a lot of Bash code. Not that I never wrote a lot of Bash, but now as I also looked through the Google Shell Style Guide, I thought it is time also to write my thoughts on that. I agree with that guide in most, but not in all points. </span><br />
<br />
<a class='textlink' href='https://google.github.io/styleguide/shellguide.html'>Google Shell Style Guide</a><br />
<br />
<h2 style='display: inline'>My modifications</h2><br />
<br />
<span>These are my modifications to the Google Guide.</span><br />
<br />
<h3 style='display: inline'>Shebang</h3><br />
<br />
<span>Google recommends using always...</span><br />
<br />
<pre>
#!/bin/bash 
</pre>
<br />
<span>... as the shebang line, but that does not work on all Unix and Unix-like operating systems (e.g., the *BSDs don&#39;t have Bash installed to /bin/bash). Better is:</span><br />
<br />
<pre>
#!/usr/bin/env bash
</pre>
<br />
<h3 style='display: inline'>Two space soft-tabs indentation</h3><br />
<br />
<span>I know there have been many tab- and soft-tab wars on this planet. Google recommends using two space soft-tabs for Bash scripts. </span><br />
<br />
<span>I don&#39;t care if I use two or four space indentations. I agree, however, that we should not use tabs. I tend to use four-space soft-tabs as that&#39;s how I currently configured Vim for any programming language. What matters most, though, is consistency within the same script/project.</span><br />
<br />
<span>Google also recommends limiting the line length to 80 characters. For some people, that seems to be an old habit from the &#39;80s, where all computer terminals couldn&#39;t display longer lines. But I think that the 80 character mark is still a good practice, at least for shell scripts. For example, I am often writing code on a Microsoft Go Tablet PC (running Linux, of course), and it comes in convenient if the lines are not too long due to the relatively small display on the device.</span><br />
<br />
<span>I hit the 80 character line length quicker with the four spaces than with two spaces, but that makes me refactor the Bash code more aggressively, which is a good thing. </span><br />
<br />
<h3 style='display: inline'>Breaking long pipes</h3><br />
<br />
<span>Google recommends breaking up long pipes like this:</span><br />
<br />
<pre>
# All fits on one line
command1 | command2

# Long commands
command1 \
  | command2 \
  | command3 \
  | command4
</pre>
<br />
<span>I think there is a better way like the following, which is less noisy. The pipe | already indicates the Bash that another command is expected, thus making the explicit line breaks with \ obsolete:</span><br />
<br />
<pre>
# Long commands
command1 |
    command2 |
    command3 |
    command4
</pre>
<br />
<h3 style='display: inline'>Quoting your variables</h3><br />
<br />
<span>Google recommends always quote your variables. Generally, it would be best if you did that only for variables where you are unsure about the content/values of the variables (e.g., content is from an external input source and may contain whitespace or other special characters). In my opinion, the code will become quite noisy when you always quote your variables like this:</span><br />
<br />
<pre>
greet () {
    local -r greeting="${1}"
    local -r name="${2}"
    echo "${greeting} ${name}!"
}
</pre>
<br />
<span>In this particular example, I agree that you should quote them as you don&#39;t know the input (are there, for example, whitespace characters?). But if you are sure that you are only using simple bare words, then I think that the code looks much cleaner when you do this instead:</span><br />
<br />
<pre>
say_hello_to_paul () {
    local -r greeting=Hello
    local -r name=Paul
    echo "$greeting $name!"
}
</pre>
<br />
<span>You see, I also omitted the curly braces { } around the variables. I only use the curly braces around variables when it makes the code either easier/clearer to read or if it is necessary to use them:</span><br />
<br />
<pre>
declare FOO=bar
# Curly braces around FOO are necessary
echo "foo${FOO}baz"
</pre>
<br />
<span>A few more words on always quoting the variables: For the sake of consistency (and for making ShellCheck happy), I am not against quoting everything I encounter. I also think that the larger the Bash script becomes, the more critical it becomes always to quote variables. That&#39;s because it will be more likely that you might not remember that some of the functions don&#39;t work on values with spaces in them, for example. It&#39;s just that I won&#39;t quote everything in every small script I write. </span><br />
<br />
<h3 style='display: inline'>Prefer built-in commands over external commands</h3><br />
<br />
<span>Google recommends using the built-in commands over available external commands where possible:</span><br />
<br />
<pre>
# Prefer this:
addition=$(( X + Y ))
substitution="${string/#foo/bar}"

# Instead of this:
addition="$(expr "${X}" + "${Y}")"
substitution="$(echo "${string}" | sed -e &#39;s/^foo/bar/&#39;)"
</pre>
<br />
<span>I can&#39;t entirely agree here. The external commands (especially sed) are much more sophisticated and powerful than the built-in Bash versions. Sed can do much more than the Bash can ever do by itself when it comes to text manipulation (the name "sed" stands for streaming editor, after all).</span><br />
<br />
<span>I prefer to do light text processing with the Bash built-ins and more complicated text processing with external programs such as sed, grep, awk, cut, and tr. However, there is also medium-light text processing where I would want to use external programs. That is so because I remember using them better than the Bash built-ins. The Bash can get relatively obscure here (even Perl will be more readable then - Side note: I love Perl).</span><br />
<br />
<span>Also, you would like to use an external command for floating-point calculation (e.g., bc) instead of using the Bash built-ins (worth noticing that ZSH supports built-in floating-points).</span><br />
<br />
<span>I even didn&#39;t get started with what you can do with awk (especially GNU Awk), a fully-fledged programming language. Tiny Awk snippets tend to be used quite often in Shell scripts without honouring the real power of Awk. But if you did everything in Perl or Awk or another scripting language, then it wouldn&#39;t be a Bash script anymore, wouldn&#39;t it? ;-)</span><br />
<br />
<h2 style='display: inline'>My additions</h2><br />
<br />
<h3 style='display: inline'>Use of &#39;yes&#39; and &#39;no&#39;</h3><br />
<br />
<span>Bash does not support a boolean type. I tend just to use the strings &#39;yes&#39; and &#39;no&#39; here. I used 0 for false and 1 for true for some time, but I think that the yes/no strings are easier to read. Yes, the Bash script would need to perform string comparisons on every check, but if performance is crucial to you, you wouldn&#39;t want to use a Bash script anyway, correct?</span><br />
<br />
<pre>
declare -r SUGAR_FREE=yes
declare -r I_NEED_THE_BUZZ=no

buy_soda () {
    local -r sugar_free=$1

    if [[ $sugar_free == yes ]]; then
        echo &#39;Diet Dr. Pepper&#39;
    else
        echo &#39;Pepsi Coke&#39;
    fi
}

buy_soda $I_NEED_THE_BUZZ
</pre>
<br />
<h3 style='display: inline'>Non-evil alternative to variable assignments via eval</h3><br />
<br />
<span>Google is in the opinion that eval should be avoided. I think so too. They list these examples in their guide:</span><br />
<br />
<pre>
# What does this set?
# Did it succeed? In part or whole?
eval $(set_my_variables)

# What happens if one of the returned values has a space in it?
variable="$(eval some_function)"

</pre>
<br />
<span>However, if I want to read variables from another file, I don&#39;t have to use eval here. I only have to source the file:</span><br />
<br />
<pre>
% cat vars.source.sh
declare foo=bar
declare bar=baz
declare bay=foo

% bash -c &#39;source vars.source.sh; echo $foo $bar $baz&#39;
bar baz foo
</pre>
<br />
<span>And suppose I want to assign variables dynamically. In that case, I could just run an external script and source its output (This is how you could do metaprogramming in Bash without the use of eval - write code which produces code for immediate execution):</span><br />
<br />
<pre>
% cat vars.sh
#!/usr/bin/env bash
cat &lt;&lt;END
declare date="$(date)"
declare user=$USER
END

% bash -c &#39;source &lt;(./vars.sh); echo "Hello $user, it is $date"&#39;
Hello paul, it is Sat 15 May 19:21:12 BST 2021
</pre>
<br />
<span>The downside is that ShellCheck won&#39;t be able to follow the dynamic sourcing anymore.</span><br />
<br />
<h3 style='display: inline'>Prefer pipes over arrays for list processing</h3><br />
<br />
<span>When I do list processing in Bash, I prefer to use pipes. You can chain them through Bash functions as well, which is pretty neat. Usually, my list processing scripts are of a structure like this:</span><br />
<br />
<pre>
filter_lines () {
    echo &#39;Start filtering lines in a fancy way!&#39; &gt;&amp;2
    grep ... | sed ....
}

process_lines () {
    echo &#39;Start processing line by line!&#39; &gt;&amp;2
    while read -r line; do
        ... do something and produce a result...
        echo "$result"
    done 
}

# Do some post-processing of the data
postprocess_lines () {
    echo &#39;Start removing duplicates!&#39; &gt;&amp;2
    sort -u
}

genreate_report () {
    echo &#39;My boss wants to have a report!&#39; &gt;&amp;2
    tee outfile.txt
    wc -l outfile.txt
}

main () {
    filter_lines |
        process_lines |
        postprocess_lines |
        generate_report
}

main
</pre>
<br />
<span>The stdout is always passed as a pipe to the next following stage. The stderr is used for info logging.</span><br />
<br />
<h3 style='display: inline'>Assign-then-shift</h3><br />
<br />
<span>I often refactor existing Bash code. That leads me to add and removing function arguments quite often. It&#39;s pretty repetitive work changing the $1, $2.... function argument numbers every time you change the order or add/remove possible arguments.</span><br />
<br />
<span>The solution is to use of the "assign-then-shift"-method, which goes like this: "local -r var1=$1; shift; local -r var2=$1; shift". The idea is that you only use "$1" to assign function arguments to named (better readable) local function variables. You will never have to bother about "$2" or above. That is very useful when you constantly refactor your code and remove or add function arguments. It&#39;s something that I picked up from a colleague (a pure Bash wizard) some time ago:</span><br />
<br />
<pre>
some_function () {
    local -r param_foo="$1"; shift
    local -r param_baz="$1"; shift
    local -r param_bay="$1"; shift
    ...
}
</pre>
<br />
<span>Want to add a param_baz? Just do this:</span><br />
<br />
<pre>
some_function () {
    local -r param_foo="$1"; shift
    local -r param_bar="$1"; shift
    local -r param_baz="$1"; shift
    local -r param_bay="$1"; shift
    ...
}
</pre>
<br />
<span>Want to remove param_foo? Nothing easier than that:</span><br />
<br />
<pre>
some_function () {
    local -r param_bar="$1"; shift
    local -r param_baz="$1"; shift
    local -r param_bay="$1"; shift
    ...
}
</pre>
<br />
<span>As you can see, I didn&#39;t need to change any other assignments within the function. Of course, you would also need to change the function argument lists at every occasion where the function is invoked - you would do that within the same refactoring session.</span><br />
<br />
<h3 style='display: inline'>Paranoid mode</h3><br />
<br />
<span>I call this the paranoid mode. The Bash will stop executing when a command exits with a status not equal to 0:</span><br />
<br />
<pre>
set -e
grep -q foo &lt;&lt;&lt; bar
echo Jo
</pre>
<br />
<span>Here &#39;Jo&#39; will never be printed out as the grep didn&#39;t find any match. It&#39;s unrealistic for most scripts to run in paranoid mode purely, so there must be a way to add exceptions. Critical Bash scripts of mine tend to look like this:</span><br />
<br />
<pre>
#!/usr/bin/env bash

set -e

some_function () {
    .. some critical code
    ...

    set +e
    # Grep might fail, but that&#39;s OK now
    grep ....
    local -i ec=$?
    set -e

    .. critical code continues ...
    if [[ $ec -ne 0 ]]; then
        ...
    fi
    ...
}
</pre>
<br />
<h2 style='display: inline'>Learned</h2><br />
<br />
<span>There are also a couple of things I&#39;ve learned from Google&#39;s guide.</span><br />
<br />
<h3 style='display: inline'>Unintended lexicographical comparison.</h3><br />
<br />
<span>The following looks like a valid Bash code:</span><br />
<br />
<pre>
if [[ "${my_var}" &gt; 3 ]]; then
    # True for 4, false for 22.
    do_something
fi
</pre>
<br />
<span>... but it is probably an unintended lexicographical comparison. A correct way would be:</span><br />
<br />
<pre>
if (( my_var &gt; 3 )); then
    do_something
fi
</pre>
<br />
<span>or</span><br />
<br />
<pre>
if [[ "${my_var}" -gt 3 ]]; then
    do_something
fi
</pre>
<br />
<h3 style='display: inline'>PIPESTATUS</h3><br />
<br />
<span>I have never used the PIPESTATUS variable before. I knew that it&#39;s there, but I never bothered to understand how it works until now thoroughly.</span><br />
<br />
<span>The PIPESTATUS variable in Bash allows checking of the return code from all parts of a pipe. If it&#39;s only necessary to check the success or failure of the whole pipe, then the following is acceptable:</span><br />
<br />
<pre>
tar -cf - ./* | ( cd "${dir}" &amp;&amp; tar -xf - )
if (( PIPESTATUS[0] != 0 || PIPESTATUS[1] != 0 )); then
    echo "Unable to tar files to ${dir}" &gt;&amp;2
fi
</pre>
<br />
<span>However, as PIPESTATUS will be overwritten as soon as you do any other command, if you need to act differently on errors based on where it happened in the pipe, you&#39;ll need to assign PIPESTATUS to another variable immediately after running the command (don&#39;t forget that [ is a command and will wipe out PIPESTATUS).</span><br />
<br />
<pre>
tar -cf - ./* | ( cd "${DIR}" &amp;&amp; tar -xf - )
return_codes=( "${PIPESTATUS[@]}" )
if (( return_codes[0] != 0 )); then
    do_something
fi
if (( return_codes[1] != 0 )); then
    do_something_else
fi
</pre>
<br />
<h2 style='display: inline'>Use common sense and BE CONSISTENT.</h2><br />
<br />
<span>The following two paragraphs are thoroughly quoted from the Google guidelines. But they hit the hammer on the head:</span><br />
<br />
<span class='quote'>If you are editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around their if clauses, you should, too. If their comments have little boxes of stars around them, make your comments have little boxes of stars around them too.</span><br />
<br />
<span class='quote'>The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you are saying rather than on how you are saying it. We present global style rules here, so people know the vocabulary. But local style is also important. If the code you add to a file looks drastically different from the existing code around it, the discontinuity throws readers out of their rhythm when they go to read it. Try to avoid this.</span><br />
<br />
<br />
<h2 style='display: inline'>Advanced Bash learning pro tip</h2><br />
<br />
<span>I also highly recommend having a read through the "Advanced Bash-Scripting Guide" (not from Google). I use it as the universal Bash reference and learn something new every time I look at it.</span><br />
<br />
<a class='textlink' href='https://tldp.org/LDP/abs/html/'>Advanced Bash-Scripting Guide</a><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-01-01-bash-golf-part-2.html'>2022-01-01 Bash Golf Part 2</a><br />
<a class='textlink' href='./2021-11-29-bash-golf-part-1.html'>2021-11-29 Bash Golf Part 1</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all</a><br />
<a class='textlink' href='./2021-05-16-personal-bash-coding-style-guide.html'>2021-05-16 Personal Bash coding style guide (You are currently reading this)</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Welcome to the Geminispace</title>
        <link href="gemini://foo.zone/gemfeed/2021-04-24-welcome-to-the-geminispace.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-04-24-welcome-to-the-geminispace.gmi</id>
        <updated>2021-04-24T19:28:41+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>ASCII Art by Andy Hood!</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Welcome to the Geminispace</h1><br />
<br />
<span class='quote'>Published at 2021-04-24T19:28:41+01:00; Updated at 2021-06-18</span><br />
<br />
<span>ASCII Art by Andy Hood!</span><br />
<br />
<span>Have you reached this article already via Gemini? It requires a Gemini client; web browsers such as Firefox, Chrome, Safari, etc., don&#39;t support the Gemini protocol. The Gemini address of this site (or the address of this capsule as people say in Geminispace) is:</span><br />
<br />
<a class='textlink' href='gemini://foo.zone'>gemini://foo.zone</a><br />
<br />
<span>However, if you still use HTTP, you are just surfing the fallback HTML version of this capsule. In that case, I suggest reading on what this is all about :-).</span><br />
<br />
<pre>
    /\
   /  \
  |    |
  |NASA|
  |    |
  |    |
  |    |
 &#39;      `
 |Gemini|
 |      |
 |______|
  &#39;-`&#39;-`   .
  / . \&#39;\ . .&#39;
 &#39;&#39;( .&#39;\.&#39; &#39; .;&#39;
&#39;.;.;&#39; ;&#39;.;&#39; ..;;&#39; AsH

</pre>
<br />
<h2 style='display: inline'>Motivation</h2><br />
<br />
<h3 style='display: inline'>My urge to revamp my personal website</h3><br />
<br />
<span>For some time, I had to urge to revamp my personal website. Not to update the technology and its design but to update all the content (+ keep it current) and start a small tech blog again. So unconsciously, I began to search for an excellent platform to do all of that in a KISS (keep it simple &amp; stupid) way.</span><br />
<br />
<h3 style='display: inline'>My still great Laptop running hot</h3><br />
<br />
<span>Earlier this year (2021), I noticed that my almost seven-year-old but still great Laptop started to become hot and slowed down while surfing the web. Also, the Laptop&#39;s fan became quite noisy. This was all due to the additional bloat such as JavaScript, excessive use of CSS, tracking cookies+pixels, ads, and so on there was on the website. </span><br />
<br />
<span>All I wanted was to read an interesting article, but after a big advertising pop-up banner appeared and made everything worse, I gave up and closed the browser tab.</span><br />
<br />
<h2 style='display: inline'>Discovering the Gemini internet protocol</h2><br />
<br />
<span>Around the same time, I discovered a relatively new, more lightweight protocol named Gemini, which does not support all these CPU-intensive features like HTML, JavaScript, and CSS. Also, tracking and ads are unsupported by the Gemini protocol.</span><br />
<br />
<span>The "downside" is that due to the limited capabilities of the Gemini protocol, all sites look very old and spartan. But that is not a downside; that is, in fact, a design choice people made. It is up to the client software how your capsule looks. For example, you could use a graphical client, such as Lagrange, with nice font renderings and colours to improve the appearance. Or you could use a very minimalistic command line black-and-white Gemini client. It&#39;s your (the user&#39;s) choice.</span><br />
<br />
<a href='./2021-04-24-welcome-to-the-geminispace/amfora-screenshot.png'><img alt='Screenshot Amfora Gemini terminal client surfing this site' title='Screenshot Amfora Gemini terminal client surfing this site' src='./2021-04-24-welcome-to-the-geminispace/amfora-screenshot.png' /></a><br />
<a href='./2021-04-24-welcome-to-the-geminispace/lagrange-screenshot.png'><img alt='Screenshot graphical Lagrange Gemini client surfing this site' title='Screenshot graphical Lagrange Gemini client surfing this site' src='./2021-04-24-welcome-to-the-geminispace/lagrange-screenshot.png' /></a><br />
<br />
<span>Why is there a need for a new protocol? As the modern web is a superset of Gemini, can&#39;t we use simple HTML 1.0 instead? That&#39;s a good and valid question. It is not a technical problem but a human problem. We tend to abuse the features once they are available. You can ensure that things stay efficient and straightforward as long as you are using the Gemini protocol. On the other hand, you can&#39;t force every website on the modern web to only create plain and straightforward-looking HTML pages.</span><br />
<br />
<h2 style='display: inline'>My own Gemini capsule</h2><br />
<br />
<span>As it is effortless to set up and maintain your own Gemini capsule (Gemini server + content composed via the Gemtext markup language), I decided to create my own. What I like about Gemini is that I can use my favourite text editor and get typing. I don&#39;t need to worry about the style and design of the presence, and I also don&#39;t have to test anything in ten different web browsers. I can only focus on the content! As a matter of fact, I am using the Vim editor + its spellchecker + auto word completion functionality to write this. </span><br />
<br />
<span>This site was generated with Gemtexter. You can read more about it here:</span><br />
<br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>Gemtexter - One Bash script to rule it all</a><br />
<br />
<h2 style='display: inline'>Gemini advantages summarised</h2><br />
<br />
<ul>
<li>Supports an alternative to the modern bloated web</li>
<li>Easy to operate and easy to write content</li>
<li>No need to worry about various web browser compatibilities</li>
<li>It&#39;s the client&#39;s responsibility how the content is designed+presented</li>
<li>Lightweight (although not as lightweight as the Gopher protocol)</li>
<li>Supports privacy (no cookies, no request header fingerprinting, TLS encryption)</li>
<li>Fun to play with (it&#39;s a bit geeky, yes, but a lot of fun!)</li>
</ul><br />
<h2 style='display: inline'>Dive into deep Gemini space</h2><br />
<br />
<span>Check out one of the following links for more information about Gemini. For example, you will find a FAQ that explains why the protocol is named Gemini. Many Gemini capsules are dual-hosted via Gemini and HTTP(S) so that people new to Gemini can sneak peek at the content with a regular web browser. Some people go as far as tri-hosting all their content via HTTP(S), Gemini and Gopher.</span><br />
<br />
<a class='textlink' href='gemini://gemini.circumlunar.space'>gemini://gemini.circumlunar.space</a><br />
<a class='textlink' href='https://gemini.circumlunar.space'>https://gemini.circumlunar.space</a><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2023-03-25-gemtexter-2.0.0-lets-gemtext-again-2.html'>2023-03-25 Gemtexter 2.0.0 - Let&#39;s Gemtext again²</a><br />
<a class='textlink' href='./2022-08-27-gemtexter-1.1.0-lets-gemtext-again.html'>2022-08-27 Gemtexter 1.1.0 - Let&#39;s Gemtext again</a><br />
<a class='textlink' href='./2021-06-05-gemtexter-one-bash-script-to-rule-it-all.html'>2021-06-05 Gemtexter - One Bash script to rule it all</a><br />
<a class='textlink' href='./2021-04-24-welcome-to-the-geminispace.html'>2021-04-24 Welcome to the Geminispace (You are currently reading this)</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>DTail - The distributed log tail program</title>
        <link href="gemini://foo.zone/gemfeed/2021-04-22-dtail-the-distributed-log-tail-program.gmi" />
        <id>gemini://foo.zone/gemfeed/2021-04-22-dtail-the-distributed-log-tail-program.gmi</id>
        <updated>2021-04-22T19:28:41+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This article first appeared at the Mimecast Engineering Blog but I made it available here in my personal internet site too.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>DTail - The distributed log tail program</h1><br />
<br />
<span class='quote'>Published at 2021-04-22T19:28:41+01:00; Updated at 2021-04-26</span><br />
<br />
<a href='./2021-04-22-dtail-the-distributed-log-tail-program/title.png'><img alt='DTail logo image' title='DTail logo image' src='./2021-04-22-dtail-the-distributed-log-tail-program/title.png' /></a><br />
<br />
<span>This article first appeared at the Mimecast Engineering Blog but I made it available here in my personal internet site too.</span><br />
<br />
<a class='textlink' href='https://medium.com/mimecast-engineering/dtail-the-distributed-log-tail-program-79b8087904bb'>Original Mimecast Engineering Blog post at Medium</a><br />
<br />
<span>Running a large cloud-based service requires monitoring the state of huge numbers of machines, a task for which many standard UNIX tools were not really designed. In this post, I will describe a simple program, DTail, that Mimecast has built and released as Open-Source, which enables us to monitor log files of many servers at once without the costly overhead of a full-blown log management system.</span><br />
<br />
<span>At Mimecast, we run over 10 thousand server boxes. Most of them host multiple microservices and each of them produces log files. Even with the use of time series databases and monitoring systems, raw application logs are still an important source of information when it comes to analysing, debugging, and troubleshooting services.</span><br />
<br />
<span>Every engineer familiar with UNIX or a UNIX-like platform (e.g., Linux) is well aware of tail, a command-line program for displaying a text file content on the terminal which is also especially useful for following application or system log files with tail -f logfile.</span><br />
<br />
<span>Think of DTail as a distributed version of the tail program which is very useful when you have a distributed application running on many servers. DTail is an Open-Source, cross-platform, fairly easy to use, support and maintain log file analysis &amp; statistics gathering tool designed for Engineers and Systems Administrators. It is programmed in Google Go.</span><br />
<br />
<h2 style='display: inline'>A Mimecast Pet Project</h2><br />
<br />
<span>DTail got its inspiration from public domain tools available already in this area but it is a blue sky from-scratch development which was first presented at Mimecast’s annual internal Pet Project competition (awarded with a Bronze prize). It has gained popularity since and is one of the most widely deployed DevOps tools at Mimecast (reaching nearly 10k server installations) and many engineers use it on a regular basis. The Open-Source version of DTail is available at:</span><br />
<br />
<a class='textlink' href='https://dtail.dev'>https://dtail.dev</a><br />
<br />
<span>Try it out — We would love any feedback. But first, read on…</span><br />
<br />
<h2 style='display: inline'>Differentiating from log management systems</h2><br />
<br />
<span>Why not just use a full-blown log management system? There are various Open-Source and commercial log management solutions available on the market you could choose from (e.g. the ELK stack). Most of them store the logs in a centralized location and are fairly complex to set up and operate. Possibly they are also pretty expensive to operate if you have to buy dedicated hardware (or pay fees to your cloud provider) and have to hire support staff for it.</span><br />
<br />
<span>DTail does not aim to replace any of the log management tools already available but is rather an additional tool crafted especially for ad-hoc debugging and troubleshooting purposes. DTail is cheap to operate as it does not require any dedicated hardware for log storage as it operates directly on the source of the logs. It means that there is a DTail server installed on all server boxes producing logs. This decentralized comes with the direct advantages that there is no introduced delay because the logs are not shipped to a central log storage device. The reduced complexity also makes it more robust against outages. You won’t be able to troubleshoot your distributed application very well if the log management infrastructure isn’t working either.</span><br />
<br />
<a href='./2021-04-22-dtail-the-distributed-log-tail-program/dtail.gif'><img alt='DTail sample session animated gif' title='DTail sample session animated gif' src='./2021-04-22-dtail-the-distributed-log-tail-program/dtail.gif' /></a><br />
<br />
<span>As a downside, you won’t be able to access any logs with DTail when the server is down. Furthermore, a server can store logs only up to a certain capacity as disks will fill up. For the purpose of ad-hoc debugging, these are not typically issues. Usually, it’s the application you want to debug and not the server. And disk space is rarely an issue for bare metal and VM-based systems these days, with sufficient space for several weeks’ worth of log storage being available. DTail also supports reading compressed logs. The currently supported compression algorithms are gzip and zstd.</span><br />
<br />
<h2 style='display: inline'>Combining simplicity, security and efficiency</h2><br />
<br />
<span>DTail also has a client component that connects to multiple servers concurrently for log files (or any other text files).</span><br />
<br />
<span>The DTail client interacts with a DTail server on port TCP/2222 via SSH protocol and does not interact in any way with the system’s SSH server (e.g., OpenSSH Server) which might be running at port TCP/22 already. As a matter of fact, you don’t need a regular SSH server running for DTail at all. There is no support for interactive login shells at TCP/2222 either, as by design that port can only be used for text data streaming. The SSH protocol is used for the public/private key infrastructure and transport encryption only and DTail implements its own protocol on top of SSH for the features provided. There is no need to set up or buy any additional TLS certificates. The port 2222 can be easily reconfigured if you preferred to use a different one.</span><br />
<br />
<span>The DTail server, which is a single static binary, will not fork an external process. This means that all features are implemented in native Go code (exception: Linux ACL support is implemented in C, but it must be enabled explicitly on compile time) and therefore helping to make it robust, secure, efficient, and easy to deploy. A single client, running on a standard Laptop, can connect to thousands of servers concurrently while still maintaining a small resource footprint.</span><br />
<br />
<span>Recent log files are very likely still in the file system caches on the servers. Therefore, there tends to be a minimal I/O overhead involved.</span><br />
<br />
<h2 style='display: inline'>The DTail family of commands</h2><br />
<br />
<span>Following the UNIX philosophy, DTail includes multiple command-line commands each of them for a different purpose:</span><br />
<br />
<ul>
<li>dserver: The DTail server, the only binary required to be installed on the servers involved.</li>
<li>dtail: The distributed log tail client for following log files.</li>
<li>dcat: The distributed cat client for concatenating and displaying text files.</li>
<li>dgrep: The distributed grep client for searching text files for a regular expression pattern.</li>
<li>dmap: The distributed map-reduce client for aggregating stats from log files.</li>
</ul><br />
<a href='./2021-04-22-dtail-the-distributed-log-tail-program/dgrep.gif'><img alt='DGrep sample session animated gif' title='DGrep sample session animated gif' src='./2021-04-22-dtail-the-distributed-log-tail-program/dgrep.gif' /></a><br />
<br />
<h2 style='display: inline'>Usage example</h2><br />
<br />
<span>The use of these commands is almost self-explanatory for a person already used to the standard command line in Unix systems. One of the main goals is to make DTail easy to use. A tool that is too complicated to use under high-pressure scenarios (e.g., during an incident) can be quite detrimental.</span><br />
<br />
<span>The basic idea is to start one of the clients from the command line and provide a list of servers to connect to with –servers. You also must provide a path of remote (log) files via –files. If you want to process multiple files per server, you could either provide a comma-separated list of file paths or make use of file system globbing (or a combination of both).</span><br />
<br />
<span>The following example would connect to all DTail servers listed in the serverlist.txt, follow all files with the ending .log and filter for lines containing the string error. You can specify any Go compatible regular expression. In this example we add the case-insensitive flag to the regex:</span><br />
<br />
<pre>
dtail –servers serverlist.txt –files ‘/var/log/*.log’ –regex ‘(?i:error)’
</pre>
<br />
<span>You usually want to specify a regular expression as a client argument. This will mean that responses are pre-filtered for all matching lines on the server-side and thus sending back only the relevant lines to the client. If your logs are growing very rapidly and the regex is not specific enough there might be the chance that your client is not fast enough to keep up processing all of the responses. This could be due to a network bottleneck or just as simple as a slow terminal emulator displaying the log lines on the client-side.</span><br />
<br />
<span>A green 100 in the client output before each log line received from the server always indicates that there were no such problems and 100% of all log lines could be displayed on your terminal (have a look at the animated Gifs in this post). If the percentage falls below 100 it means that some of the channels used by the servers to send data to the client are congested and lines were dropped. In this case, the color will change from green to red. The user then could decide to run the same query but with a more specific regex.</span><br />
<br />
<span>You could also provide a comma-separated list of servers as opposed to a text file. There are many more options you could use. The ones listed here are just the very basic ones. There are more instructions and usage examples on the GitHub page. Also, you can study even more of the available options via the –help switch (some real treasures might be hidden there).</span><br />
<br />
<h2 style='display: inline'>Fitting it in</h2><br />
<br />
<span>DTail integrates nicely into the user management of existing infrastructure. It follows normal system permissions and does not open new “holes” on the server which helps to keep security departments happy. The user would not have more or less file read permissions than he would have via a regular SSH login shell. There is a full SSH key, traditional UNIX permissions, and Linux ACL support. There is also a very low resource footprint involved. On average for tailing and searching log files less than 100MB RAM and less than a quarter of a CPU core per participating server are required. Complex map-reduce queries on big data sets will require more resources accordingly.</span><br />
<br />
<h2 style='display: inline'>Advanced features</h2><br />
<br />
<span>The features listed here are out of the scope of this blog post but are worthwhile to mention:</span><br />
<br />
<ul>
<li>Distributed map-reduce queries on stats provided in log files with dmap. dmap comes with its own SQL-like aggregation query language.</li>
<li>Stats streaming with continuous map-reduce queries. The difference to normal queries is that the stats are aggregated over a specified interval only on the newly written log lines. Thus, giving a de-facto live stat view for each interval.</li>
<li>Server-side scheduled queries on log files. The queries are configured in the DTail server configuration file and scheduled at certain time intervals. Results are written to CSV files. This is useful for generating daily stats from the log files without the need for an interactive client.</li>
<li>Server-side stats streaming with continuous map-reduce queries. This for example can be used to periodically generate stats from the logs at a configured interval, e.g., log error counts by the minute. These then can be sent to a time-series database (e.g., Graphite) and then plotted in a Grafana dashboard.</li>
<li>Support for custom extensions. E.g., for different server discovery methods (so you don’t have to rely on plain server lists) and log file formats (so that map-reduce queries can parse more stats from the logs).</li>
</ul><br />
<h2 style='display: inline'>For the future</h2><br />
<br />
<span>There are various features we want to see in the future.</span><br />
<br />
<ul>
<li>A spartan mode, not printing out any extra information but the raw remote log files would be a nice feature to have. This will make it easier to post-process the data produced by the DTail client with common UNIX tools. (To some degree this is possible already, just disable the ANSI terminal color output of the client with -noColors and pipe the output to another program).</li>
<li>Tempting would be implementing the dgoawk command, a distributed version of the AWK programming language purely implemented in Go, for advanced text data stream processing capabilities. There are 3rd party libraries available implementing AWK in pure Go which could be used.</li>
<li>A more complex change would be the support of federated queries. You can connect to thousands of servers from a single client running on a laptop. But does it scale to 100k of servers? Some of the servers could be used as middleware for connecting to even more servers.</li>
<li>Another aspect is to extend the documentation. Especially the advanced features such as map-reduce query language and how to configure the server-side queries currently do require more documentation. For now, you can read the code, sample config files or just ask the author for that! But this will be certainly addressed in the future.</li>
</ul><br />
<h2 style='display: inline'>Open Source</h2><br />
<br />
<span>Mimecast highly encourages you to have a look at DTail and submit an issue for any features you would like to see. Have you found a bug? Maybe you just have a question or comment? If you want to go a step further: We would also love to see pull requests for any features or improvements. Either way, if in doubt just contact us via the DTail GitHub page.</span><br />
<br />
<a class='textlink' href='https://dtail.dev'>https://dtail.dev</a><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-10-30-installing-dtail-on-openbsd.html'>2022-10-30 Installing DTail on OpenBSD</a><br />
<a class='textlink' href='./2022-03-06-the-release-of-dtail-4.0.0.html'>2022-03-06 The release of DTail 4.0.0</a><br />
<a class='textlink' href='./2021-04-22-dtail-the-distributed-log-tail-program.html'>2021-04-22 DTail - The distributed log tail program (You are currently reading this)</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Realistic load testing with I/O Riot for Linux</title>
        <link href="gemini://foo.zone/gemfeed/2018-06-01-realistic-load-testing-with-ioriot-for-linux.gmi" />
        <id>gemini://foo.zone/gemfeed/2018-06-01-realistic-load-testing-with-ioriot-for-linux.gmi</id>
        <updated>2018-06-01T14:50:29+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>This text first was published in the german IT-Administrator computer Magazine. 3 years have passed since and I decided to publish it on my blog too. </summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Realistic load testing with I/O Riot for Linux</h1><br />
<br />
<span class='quote'>Published at 2018-06-01T14:50:29+01:00; Updated at 2021-05-08</span><br />
<br />
<pre>
       .---.
      /     \
      \.@-@./
      /`\_/`\
     //  _  \\
    | \     )|_
   /`\_`&gt;  &lt;_/ \
jgs\__/&#39;---&#39;\__/
</pre>
<br />
<h2 style='display: inline'>Foreword</h2><br />
<br />
<span>This text first was published in the german IT-Administrator computer Magazine. 3 years have passed since and I decided to publish it on my blog too. </span><br />
<br />
<a class='textlink' href='https://www.admin-magazin.de/Das-Heft/2018/06/Realistische-Lasttests-mit-I-O-Riot'>https://www.admin-magazin.de/Das-Heft/2018/06/Realistische-Lasttests-mit-I-O-Riot</a><br />
<br />
<span>I havn&#39;t worked on I/O Riot for some time now, but all what is written here is still valid. I am still using I/O Riot to debug I/O issues and pattern once in a while, so by all means the tool is not obsolete yet. The tool even helped to resolve a major production incident at work caused by disk I/O.</span><br />
<br />
<span>I am eagerly looking forward to revamp I/O Riot so that it uses the new BPF Linux capabilities instead of plain old Systemtap (or alternatively: Newer versions of Systemtap can also use BPF as the backend I have learned). Also, when I wrote I/O Riot initially, I didn&#39;t have any experience with the Go programming language yet and therefore I wrote it in C. Once it gets revamped I might consider using Go instead of C as it would spare me from many segmentation faults and headaches during development ;-). I might also just stick to C for plain performance reasons and just refactor the code dealing with concurrency.</span><br />
<br />
<span>Pleace notice that some of the screenshots show the command "ioreplay" instead of "ioriot". That&#39;s because the name has changed after taking those.</span><br />
<br />
<h1 style='display: inline'>The article</h1><br />
<br />
<span>With I/O Riot IT administrators can load test and optimize the I/O subsystem of Linux-based operating systems. The tool makes it possible to record I/O patterns and replay them at a later time as often as desired. This means bottlenecks can be reproduced and eradicated. </span><br />
<br />
<span>When storing huge amounts of data, such as more than 200 billion archived emails at Mimecast, it&#39;s not only the available storage capacity that matters, but also the data throughput and latency. At the same time, operating costs must be kept as low as possible. The more systems involved, the more important it is to optimize the hardware, the operating system and the applications running on it.</span><br />
<br />
<h2 style='display: inline'>Background: Existing Techniques</h2><br />
<br />
<span>Conventional I/O benchmarking: Administrators usually use open source benchmarking tools like IOZone and bonnie++. Available database systems such as Redis and MySQL come with their own benchmarking tools. The common problem with these tools is that they work with prescribed artificial I/O patterns. Although this can test both sequential and randomized data access, the patterns do not correspond to what can be found on production systems.</span><br />
<br />
<span>Testing by load test environment: Another option is to use a separate load test environment in which, as far as possible, a production environment with all its dependencies is simulated. However, an environment consisting of many microservices is very complex. Microservices are usually managed by different teams, which means extra coordination effort for each load test. Another challenge is to generate the load as authentically as possible so that the patterns correspond to a productive environment. Such a load test environment can only handle as many requests as its weakest link can handle. For example, load generators send many read and write requests to a frontend microservice, whereby the frontend forwards the requests to a backend microservice responsible for storing the data. If the frontend service does not process the requests efficiently enough, the backend service is not well utilized in the first place. As a rule, all microservices are clustered across many servers, which makes everything even more complicated. Under all these conditions it is very difficult to test I/O of separate backend systems. Moreover, for many small and medium-sized companies, a separate load test environment would not be feasible for cost reasons.</span><br />
<br />
<span>Testing in the production environment: For these reasons, benchmarks are often carried out in the production environment. In order to derive value from this such tests are especially performed during peak hours when systems are under high load. However, testing on production systems is associated with risks and can lead to failure or loss of data without adequate protection.</span><br />
<br />
<h2 style='display: inline'>Benchmarking the Email Cloud at Mimecast</h2><br />
<br />
<span>For email archiving, Mimecast uses an internally developed microservice, which is operated directly on Linux-based storage systems. A storage cluster is divided into several replication volumes. Data is always replicated three times across two secure data centers. Customer data is automatically allocated to one or more volumes, depending on throughput, so that all volumes are automatically assigned the same load. Customer data is archived on conventional, but inexpensive hard disks with several terabytes of storage capacity each. I/O benchmarking proved difficult for all the reasons mentioned above. Furthermore, there are no ready-made tools for this purpose in the case of self-developed software. The service operates on many block devices simultaneously, which can make the RAID controller a bottleneck. None of the freely available benchmarking tools can test several block devices at the same time without extra effort. In addition, emails typically consist of many small files. Randomized access to many small files is particularly inefficient. In addition to many software adaptations, the hardware and operating system must also be optimized.</span><br />
<br />
<span>Mimecast encourages employees to be innovative and pursue their own ideas in the form of an internal competition, Pet Project. The goal of the pet project I/O Riot was to simplify OS and hardware level I/O benchmarking. The first prototype of I/O Riot was awarded an internal roadmap prize in the spring of 2017. A few months later, I/O Riot was used to reduce write latency in the storage clusters by about 50%. The improvement was first verified by I/O replay on a test system and then successively applied to all storage systems. I/O Riot was also used to resolve a production incident caused by disk I/O load.</span><br />
<br />
<h2 style='display: inline'>Using I/O Riot</h2><br />
<br />
<span>First, all I/O events are logged to a file on a production system with I/O Riot. It is then copied to a test system where all events are replayed in the same way. The crucial point here is that you can reproduce I/O patterns as they are found on a production system as often as you like on a test system. This results in the possibility of optimizing the set screws on the system after each run.</span><br />
<br />
<h3 style='display: inline'>Installation</h3><br />
<br />
<span>I/O Riot was tested under CentOS 7.2 x86_64. For compiling, the GNU C compiler and Systemtap including kernel debug information are required. Other Linux distributions are theoretically compatible but untested. First of all, you should update the systems involved as follows:</span><br />
<br />
<pre>
% sudo yum update
</pre>
<br />
<span>If the kernel is updated, please restart the system. The installation would be done without a restart but this would complicate the installation. The installed kernel version should always correspond to the currently running kernel. You can then install I/O Riot as follows:</span><br />
<br />
<pre>
% sudo yum install gcc git systemtap yum-utils kernel-devel-$(uname -r)
% sudo debuginfo-install kernel-$(uname -r)
% git clone https://github.com/mimecast/ioriot
% cd ioriot
% make
% sudo make install
% export PATH=$PATH:/opt/ioriot/bin
</pre>
<br />
<span>Note: It is not best practice to install any compilers on production systems. For further information please have a look at the enclosed README.md.</span><br />
<br />
<h3 style='display: inline'>Recording of I/O events</h3><br />
<br />
<span>All I/O events are kernel related. If a process wants to perform an I/O operation, such as opening a file, it must inform the kernel of this by a system call (short syscall). I/O Riot relies on the Systemtap tool to record I/O syscalls. Systemtap, available for all popular Linux distributions, helps you to take a look at the running kernel in productive environments, which makes it predestined to monitor all I/O-relevant Linux syscalls and log them to a file. Other tools, such as strace, are not an alternative because they slow down the system too much.</span><br />
<br />
<span>During recording, ioriot acts as a wrapper and executes all relevant Systemtap commands for you. Use the following command to log all events to io.capture:</span><br />
<br />
<pre>
% sudo ioriot -c io.capture
</pre>
<br />
<a href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure1-ioriot-io-recording.png'><img alt='Screenshot I/O recording' title='Screenshot I/O recording' src='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure1-ioriot-io-recording.png' /></a><br />
<br />
<span>A Ctrl-C (SIGINT) stops recording prematurely. Otherwise, ioriot terminates itself automatically after 1 hour. Depending on the system load, the output file can grow to several gigabytes. Only metadata is logged, not the read and written data itself. When replaying later, only random data is used. Under certain circumstances, Systemtap may omit some system calls and issue warnings. This is to ensure that Systemtap does not consume too many resources.</span><br />
<br />
<h3 style='display: inline'>Test preparation</h3><br />
<br />
<span>Then copy io.capture to a test system. The log also contains all accesses to the pseudo file systems devfs, sysfs and procfs. This makes little sense, which is why you must first generate a cleaned and playable version io.replay from io.capture as follows:</span><br />
<br />
<pre>
% sudo ioriot -c io.capture -r io.replay -u $USER -n TESTNAME
</pre>
<br />
<span>The parameter -n allows you to assign a freely selectable test name. An arbitrary system user under which the test is to be played is specified via paramater -u.</span><br />
<br />
<h3 style='display: inline'>Test Initialization</h3><br />
<br />
<span>The test will most likely want to access existing files. These are files the test wants to read but does not create by itself. The existence of these must be ensured before the test. You can do this as follows:</span><br />
<br />
<pre>
% sudo ioriot -i io.replay
</pre>
<br />
<span>To avoid any damage to the running system, ioreplay only works in special directories. The tool creates a separate subdirectory for each file system mount point (e.g. /, /usr/local, /store/00,...) (here: /.ioriot/TESTNAME, /usr/local/.ioriot/TESTNAME, /store/00/.ioriot/TESTNAME,...). By default, the working directory of ioriot is /usr/local/ioriot/TESTNAME.</span><br />
<br />
<a href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure2-ioriot-test-preparation.png'><img alt='Screenshot test preparation' title='Screenshot test preparation' src='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure2-ioriot-test-preparation.png' /></a><br />
<br />
<span>You must re-initialize the environment before each run. Data from previous tests will be moved to a trash directory automatically, which can be finally deleted with "sudo ioriot -P".</span><br />
<br />
<h3 style='display: inline'>Replay</h3><br />
<br />
<span>After initialization, you can replay the log with -r. You can use -R to initiate both test initialization and replay in a single command and -S can be used to specify a file in which statistics are written after the test run.</span><br />
<br />
<span>You can also influence the playback speed: "-s 0" is interpreted as "Playback as fast as possible" and is the default setting. With "-s 1" all operations are performed at original speed. "-s 2" would double the playback speed and "-s 0.5" would halve it.</span><br />
<br />
<a href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure3-ioriot-replay.png'><img alt='Screenshot replaying I/O' title='Screenshot replaying I/O' src='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure3-ioriot-replay.png' /></a><br />
<br />
<span>As an initial test, for example, you could compare the two Linux I/O schedulers CFQ and Deadline and check which scheduler the test runs the fastest. They run the test separately for each scheduler. The following shell loop iterates through all attached block devices of the system and changes their I/O scheduler to the one specified in variable $new_scheduler (in this case either cfq or deadline). Subsequently, all I/O events from the io.replay protocol are played back. At the end, an output file with statistics is generated:</span><br />
<br />
<pre>
% new_scheduler=cfq
% for scheduler in /sys/block/*/queue/scheduler; do
    echo $new_scheduler | sudo tee $scheduler
done
% sudo ioriot -R io.replay -S cfq.txt
% new_scheduler=deadline
% for scheduler in /sys/block/*/queue/scheduler; do
   echo $new_scheduler | sudo tee $scheduler
done
% sudo ioriot -R io.replay -S deadline.txt
</pre>
<br />
<span>According to the results, the test could run 940 seconds faster with Deadline Scheduler:</span><br />
<br />
<pre>
% cat cfq.txt
Num workers: 4
hreads per worker: 128
otal threads: 512
Highest loadavg: 259.29
Performed ioops: 218624596
Average ioops/s: 101544.17
Time ahead: 1452s
Total time: 2153.00s
% cat deadline.txt
Num workers: 4
Threads per worker: 128
Total threads: 512
Highest loadavg: 342.45
Performed ioops: 218624596
Average ioops/s: 180234.62
Time ahead: 2392s
Total time: 1213.00s
</pre>
<br />
<span>In any case, you should also set up a time series database, such as Graphite, where the I/O throughput can be plotted. Figures 4 and 5 show the read and write access times of both tests. The break-in makes it clear when the CFQ test ended and the deadline test was started. The reading latency of both tests is similar. Write latency is dramatically improved using the Deadline Scheduler.</span><br />
<br />
<a href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure4-ioriot-read-latency.png'><img alt='Graphite visualization of the mean read access times in ms with CFQ and Deadline Scheduler.' title='Graphite visualization of the mean read access times in ms with CFQ and Deadline Scheduler.' src='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure4-ioriot-read-latency.png' /></a><br />
<br />
<a href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure5-ioriot-write-latency.png'><img alt='Graphite visualization of the average write access times in ms with CFQ and Deadline Scheduler.' title='Graphite visualization of the average write access times in ms with CFQ and Deadline Scheduler.' src='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure5-ioriot-write-latency.png' /></a><br />
<br />
<span>You should also take a look at the iostat tool. The iostat screenshot shows the output of iostat -x 10 during a test run. As you can see, a block device is fully loaded with 99% utilization, while all other block devices still have sufficient buffer. This could be an indication of poor data distribution in the storage system and is worth pursuing. It is not uncommon for I/O Riot to reveal software problems.</span><br />
<br />
<a href='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure6-iostat.png'><img alt='Output of iostat. The block device sdy seems to be almost fully utilized by 99%.' title='Output of iostat. The block device sdy seems to be almost fully utilized by 99%.' src='./2018-06-01-realistic-load-testing-with-ioriot-for-linux/figure6-iostat.png' /></a><br />
<br />
<h2 style='display: inline'>I/O Riot is Open Source</h2><br />
<br />
<span>The tool has already proven to be very useful and will continue to be actively developed as time and priority permits. Mimecast intends to be an ongoing contributor to Open Source. You can find I/O Riot at:</span><br />
<br />
<a class='textlink' href='https://github.com/mimecast/ioriot'>https://github.com/mimecast/ioriot</a><br />
<br />
<h2 style='display: inline'>Systemtap</h2><br />
<br />
<span>Systemtap is a tool for the instrumentation of the Linux kernel. The tool provides an AWK-like programming language. Programs written in it are compiled from Systemtap to C- and then into a dynamically loadable kernel module. Loaded into the kernel, the program has access to Linux internals. A Systemtap program written for I/O Riot monitors when, with which parameters, at which time, and from which process I/O syscalls take place and their return values.</span><br />
<br />
<span>For example, the open syscall opens a file and returns the responsible file descriptor. The read and write syscalls can operate on a file descriptor and return the number of read or written bytes. The close syscall closes a given file descriptor. I/O Riot comes with a ready-made Systemtap program, which you have already compiled into a kernel module and installed to /opt/ioriot. In addition to open, read and close, it logs many other I/O-relevant calls.</span><br />
<br />
<a class='textlink' href='https://sourceware.org/systemtap/'>https://sourceware.org/systemtap/</a><br />
<br />
<h2 style='display: inline'>More refereces</h2><br />
<br />
<a class='textlink' href='http://www.iozone.org/'>IOZone</a><br />
<a class='textlink' href='https://www.coker.com.au/bonnie++/'>Bonnie++</a><br />
<a class='textlink' href='https://graphiteapp.org'>Graphite</a><br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Memory-mapped_I/O'>Memory mapped I/O</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Object oriented programming with ANSI C</title>
        <link href="gemini://foo.zone/gemfeed/2016-11-20-object-oriented-programming-with-ansi-c.gmi" />
        <id>gemini://foo.zone/gemfeed/2016-11-20-object-oriented-programming-with-ansi-c.gmi</id>
        <updated>2016-11-20T22:10:57+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>You can do a little of object-oriented programming in the C Programming Language. However, that is, in my humble opinion, limited. It's easier to use a different programming language than C for OOP. But still it's an interesting exercise to try using C for this.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Object oriented programming with ANSI C</h1><br />
<br />
<span class='quote'>Published at 2016-11-20T22:10:57+00:00; Updated at 2022-01-29</span><br />
<br />
<pre>
  ___   ___  ____        ____ 
 / _ \ / _ \|  _ \      / ___|
| | | | | | | |_) |____| |    
| |_| | |_| |  __/_____| |___ 
 \___/ \___/|_|         \____|
                              
</pre>
<br />
<span>You can do a little of object-oriented programming in the C Programming Language. However, that is, in my humble opinion, limited. It&#39;s easier to use a different programming language than C for OOP. But still it&#39;s an interesting exercise to try using C for this.</span><br />
<br />
<h2 style='display: inline'>Function pointers</h2><br />
<br />
<span>Let&#39;s have a look at the following sample program. All you have to do is to add a function pointer such as "calculate" to the definition of struct "something_s". Later, during the struct initialization, assign a function address to that function pointer:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#000080">#include</font></b> <font color="#FF0000">&lt;stdio.h&gt;</font>

<b><font color="#0000FF">typedef</font></b> <b><font color="#0000FF">struct</font></b> <font color="#FF0000">{</font>
    <font color="#009900">double</font> <font color="#990000">(*</font>calculate<font color="#990000">)(</font><b><font color="#0000FF">const</font></b> <font color="#009900">double</font><font color="#990000">,</font> <b><font color="#0000FF">const</font></b> <font color="#009900">double</font><font color="#990000">);</font>
    <font color="#009900">char</font> <font color="#990000">*</font>name<font color="#990000">;</font>
<font color="#FF0000">}</font> something_s<font color="#990000">;</font>

<font color="#009900">double</font> <b><font color="#000000">multiplication</font></b><font color="#990000">(</font><b><font color="#0000FF">const</font></b> <font color="#009900">double</font> a<font color="#990000">,</font> <b><font color="#0000FF">const</font></b> <font color="#009900">double</font> b<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">return</font></b> a <font color="#990000">*</font> b<font color="#990000">;</font>
<font color="#FF0000">}</font>

<font color="#009900">double</font> <b><font color="#000000">division</font></b><font color="#990000">(</font><b><font color="#0000FF">const</font></b> <font color="#009900">double</font> a<font color="#990000">,</font> <b><font color="#0000FF">const</font></b> <font color="#009900">double</font> b<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">return</font></b> a <font color="#990000">/</font> b<font color="#990000">;</font>
<font color="#FF0000">}</font>

<font color="#009900">int</font> <b><font color="#000000">main</font></b><font color="#990000">(</font><font color="#009900">void</font><font color="#990000">)</font> <font color="#FF0000">{</font>
    <font color="#008080">something_s</font> mult <font color="#990000">=</font> <font color="#990000">(</font>something_s<font color="#990000">)</font> <font color="#FF0000">{</font>
        <font color="#990000">.</font>calculate <font color="#990000">=</font> multiplication<font color="#990000">,</font>
        <font color="#990000">.</font>name <font color="#990000">=</font> <font color="#FF0000">"Multiplication"</font>
    <font color="#FF0000">}</font><font color="#990000">;</font>

    <font color="#008080">something_s</font> div <font color="#990000">=</font> <font color="#990000">(</font>something_s<font color="#990000">)</font> <font color="#FF0000">{</font>
        <font color="#990000">.</font>calculate <font color="#990000">=</font> division<font color="#990000">,</font>
        <font color="#990000">.</font>name <font color="#990000">=</font> <font color="#FF0000">"Division"</font>
    <font color="#FF0000">}</font><font color="#990000">;</font>

    <b><font color="#0000FF">const</font></b> <font color="#009900">double</font> a <font color="#990000">=</font> <font color="#993399">3</font><font color="#990000">,</font> b <font color="#990000">=</font> <font color="#993399">2</font><font color="#990000">;</font>

    <b><font color="#000000">printf</font></b><font color="#990000">(</font><font color="#FF0000">"%s(%f, %f) =&gt; %f</font><font color="#CC33CC">\n</font><font color="#FF0000">"</font><font color="#990000">,</font> mult<font color="#990000">.</font>name<font color="#990000">,</font> a<font color="#990000">,</font> b<font color="#990000">,</font> mult<font color="#990000">.</font><b><font color="#000000">calculate</font></b><font color="#990000">(</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
    <b><font color="#000000">printf</font></b><font color="#990000">(</font><font color="#FF0000">"%s(%f, %f) =&gt; %f</font><font color="#CC33CC">\n</font><font color="#FF0000">"</font><font color="#990000">,</font> div<font color="#990000">.</font>name<font color="#990000">,</font> a<font color="#990000">,</font> b<font color="#990000">,</font> div<font color="#990000">.</font><b><font color="#000000">calculate</font></b><font color="#990000">(</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
<font color="#FF0000">}</font>
</pre>
<br />
<span>As you can see, you can call the function (pointed by the function pointer) with the same syntax as in C++ or Java:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#000000">printf</font></b><font color="#990000">(</font><font color="#FF0000">"%s(%f, %f) =&gt; %f</font><font color="#CC33CC">\n</font><font color="#FF0000">"</font><font color="#990000">,</font> mult<font color="#990000">.</font>name<font color="#990000">,</font> a<font color="#990000">,</font> b<font color="#990000">,</font> mult<font color="#990000">.</font><b><font color="#000000">calculate</font></b><font color="#990000">(</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
<b><font color="#000000">printf</font></b><font color="#990000">(</font><font color="#FF0000">"%s(%f, %f) =&gt; %f</font><font color="#CC33CC">\n</font><font color="#FF0000">"</font><font color="#990000">,</font> div<font color="#990000">.</font>name<font color="#990000">,</font> a<font color="#990000">,</font> b<font color="#990000">,</font> div<font color="#990000">.</font><b><font color="#000000">calculate</font></b><font color="#990000">(</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
</pre>
<br />
<span>However, that&#39;s just syntactic sugar for:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#000000">printf</font></b><font color="#990000">(</font><font color="#FF0000">"%s(%f, %f) =&gt; %f</font><font color="#CC33CC">\n</font><font color="#FF0000">"</font><font color="#990000">,</font> mult<font color="#990000">.</font>name<font color="#990000">,</font> a<font color="#990000">,</font> b<font color="#990000">,</font> <font color="#990000">(*</font>mult<font color="#990000">.</font>calculate<font color="#990000">)(</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
<b><font color="#000000">printf</font></b><font color="#990000">(</font><font color="#FF0000">"%s(%f, %f) =&gt; %f</font><font color="#CC33CC">\n</font><font color="#FF0000">"</font><font color="#990000">,</font> div<font color="#990000">.</font>name<font color="#990000">,</font> a<font color="#990000">,</font> b<font color="#990000">,</font> <font color="#990000">(*</font>div<font color="#990000">.</font>calculate<font color="#990000">)(</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
</pre>
<br />
<span>Output:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>pbuetow <font color="#990000">~</font>/git/blog/source <font color="#990000">[</font><font color="#993399">38268</font><font color="#990000">]%</font> gcc oop-c-example<font color="#990000">.</font>c -o oop-c-example
pbuetow <font color="#990000">~</font>/git/blog/source <font color="#990000">[</font><font color="#993399">38269</font><font color="#990000">]%</font> <font color="#990000">.</font>/oop-c-example
Multiplication<font color="#990000">(</font><font color="#993399">3.000000</font><font color="#990000">,</font> <font color="#993399">2.000000</font><font color="#990000">)</font> <font color="#990000">=&gt;</font> <font color="#993399">6.000000</font>
Division<font color="#990000">(</font><font color="#993399">3.000000</font><font color="#990000">,</font> <font color="#993399">2.000000</font><font color="#990000">)</font> <font color="#990000">=&gt;</font> <font color="#993399">1.500000</font>
</pre>
<br />
<span>Not complicated at all, but nice to know and helps to make the code easier to read!</span><br />
<br />
<h2 style='display: inline'>That&#39;s not OOP, though</h2><br />
<br />
<span>However, that&#39;s not really how it works in object-oriented languages such as Java and C++. The method call in this example is not a method call as "mult" and "div" in this example are not "message receivers". I mean that the functions can not access the state of the "mult" and "div" struct objects. In C, you would need to do something like this instead if you wanted to access the state of "mult" from within the calculate function, you would have to pass it as an argument:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>mult<font color="#990000">.</font><b><font color="#000000">calculate</font></b><font color="#990000">(</font>mult<font color="#990000">,</font>a<font color="#990000">,</font>b<font color="#990000">));</font>
</pre>
<br />
<h2 style='display: inline'>Real object oriented programming with C</h2><br />
<br />
<span>If you want to take it further, hit "Object-Oriented Programming with ANSI-C" into your favourite internet search engine or follow the link below. It goes as far as writing a C preprocessor in AWK, which takes some object-oriented pseudo-C and transforms it to plain C so that the C compiler can compile it to machine code. This is similar to how the C++ language had its origins.</span><br />
<br />
<a class='textlink' href='https://www.cs.rit.edu/~ats/books/ooc.pdf'>https://www.cs.rit.edu/~ats/books/ooc.pdf</a><br />
<br />
<h2 style='display: inline'>OOP design patterns in the Linux Kernel</h2><br />
<br />
<span>Big C software projects, like Linux, also follow some OOP techniques:</span><br />
<br />
<a class='textlink' href='https://lwn.net/Articles/444910/'>https://lwn.net/Articles/444910/</a><br />
<br />
<span>C is a very old programming language with it&#39;s quirks. This might be one of the reasons why Linux will also let Rust code in.</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Spinning up my own authoritative DNS servers</title>
        <link href="gemini://foo.zone/gemfeed/2016-05-22-spinning-up-my-own-authoritative-dns-servers.gmi" />
        <id>gemini://foo.zone/gemfeed/2016-05-22-spinning-up-my-own-authoritative-dns-servers.gmi</id>
        <updated>2016-05-22T18:59:01+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Finally, I had time to deploy my authoritative DNS servers (master and slave) for my domains 'buetow.org' and 'buetow.zone'. My domain name provider is Schlund Technologies. They allow their customers to edit the DNS records (BIND files) manually. And they also allow you to set your authoritative DNS servers for your domains. From now, I am making use of that option.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Spinning up my own authoritative DNS servers</h1><br />
<br />
<span class='quote'>Published at 2016-05-22T18:59:01+01:00</span><br />
<br />
<h2 style='display: inline'>Background</h2><br />
<br />
<span>Finally, I had time to deploy my authoritative DNS servers (master and slave) for my domains "buetow.org" and "buetow.zone". My domain name provider is Schlund Technologies. They allow their customers to edit the DNS records (BIND files) manually. And they also allow you to set your authoritative DNS servers for your domains. From now, I am making use of that option.</span><br />
<br />
<a class='textlink' href='http://www.schlundtech.de'>Schlund Technologies</a><br />
<br />
<h2 style='display: inline'>All FreeBSD Jails</h2><br />
<br />
<span>To set up my authoritative DNS servers, I installed a FreeBSD Jail dedicated for DNS with Puppet on my root machine as follows:</span><br />
<br />
<pre>
include freebsd

freebsd::ipalias { &#39;2a01:4f8:120:30e8::14&#39;:
  ensure    =&gt; up,
  proto     =&gt; &#39;inet6&#39;,
  preflen   =&gt; &#39;64&#39;,
  interface =&gt; &#39;re0&#39;,
  aliasnum  =&gt; &#39;5&#39;,
}

include jail::freebsd

class { &#39;jail&#39;:
  ensure              =&gt; present,
  jails_config        =&gt; {
    dns                     =&gt; {
      &#39;_ensure&#39;             =&gt; present,
      &#39;_type&#39;               =&gt; &#39;freebsd&#39;,
      &#39;_mirror&#39;             =&gt; &#39;ftp://ftp.de.freebsd.org&#39;,
      &#39;_remote_path&#39;        =&gt; &#39;FreeBSD/releases/amd64/10.1-RELEASE&#39;,
      &#39;_dists&#39;              =&gt; [ &#39;base.txz&#39;, &#39;doc.txz&#39;, ],
      &#39;_ensure_directories&#39; =&gt; [ &#39;/opt&#39;, &#39;/opt/enc&#39; ],
      &#39;host.hostname&#39;       =&gt; "&#39;dns.ian.buetow.org&#39;",
      &#39;ip4.addr&#39;            =&gt; &#39;192.168.0.15&#39;,
      &#39;ip6.addr&#39;            =&gt; &#39;2a01:4f8:120:30e8::15&#39;,
    },
    .
    .
  }
}
</pre>
<br />
<h2 style='display: inline'>PF firewall</h2><br />
<br />
<span>Please note that "dns.ian.buetow.org" is just the Jail name of the master DNS server (and "caprica.ian.buetow.org" the name of the Jail for the slave DNS server) and that I am using the DNS names "dns1.buetow.org" (master) and "dns2.buetow.org" (slave) for the actual service names (these are the DNS servers visible to the public). Please also note that the IPv4 address is an internal one. I have a PF to use NAT and PAT. The DNS ports are being forwarded (TCP and UDP) to that Jail. By default, all ports are blocked, so I am adding an exception rule for the IPv6 address. These are the PF rules in use:</span><br />
<br />
<pre>
% cat /etc/pf.conf
.
.
# dns.ian.buetow.org 
rdr pass on re0 proto tcp from any to $pub_ip port {53} -&gt; 192.168.0.15
rdr pass on re0 proto udp from any to $pub_ip port {53} -&gt; 192.168.0.15
pass in on re0 inet6 proto tcp from any to 2a01:4f8:120:30e8::15 port {53} flags S/SA keep state
pass in on re0 inet6 proto udp from any to 2a01:4f8:120:30e8::15 port {53} flags S/SA keep state
.
.
</pre>
<br />
<h2 style='display: inline'>Puppet managed BIND zone files</h2><br />
<br />
<span>In "manifests/dns.pp" (the Puppet manifest for the Master DNS Jail itself), I configured the BIND DNS server this way:</span><br />
<br />
<pre>
class { &#39;bind_freebsd&#39;:
  config         =&gt; "puppet:///files/bind/named.${::hostname}.conf",
  dynamic_config =&gt; "puppet:///files/bind/dynamic.${::hostname}",
}
</pre>
<br />
<span>The Puppet module is a pretty simple one. It installs the file "/usr/local/etc/named/named.conf" and it populates the "/usr/local/etc/named/dynamicdb" directory with all my zone files.</span><br />
<br />
<span>Once (Puppet-) applied inside of the Jail, I get this:</span><br />
<br />
<pre>
paul uranus:~/git/blog/source [4268]% ssh admin@dns1.buetow.org.buetow.org pgrep -lf named
60748 /usr/local/sbin/named -u bind -c /usr/local/etc/namedb/named.conf
paul uranus:~/git/blog/source [4269]% ssh admin@dns1.buetow.org.buetow.org tail -n 13 /usr/local/etc/namedb/named.conf
zone "buetow.org" {
    type master;
    notify yes;
    allow-update { key "buetoworgkey"; };
    file "/usr/local/etc/namedb/dynamic/buetow.org";
};

zone "buetow.zone" {
    type master;
    notify yes;
    allow-update { key "buetoworgkey"; };
    file "/usr/local/etc/namedb/dynamic/buetow.zone";
};
paul uranus:~/git/blog/source [4277]% ssh admin@dns1.buetow.org.buetow.org cat /usr/local/etc/namedb/dynamic/buetow.org
$TTL 3600
@    IN   SOA   dns1.buetow.org. domains.buetow.org. (
     25       ; Serial
     604800   ; Refresh
     86400    ; Retry
     2419200  ; Expire
     604800 ) ; Negative Cache TTL
; Infrastructure domains
@ IN NS dns1
@ IN NS dns2

buetow.org. 86400 IN A 78.46.80.70
buetow.org. 86400 IN AAAA 2a01:4f8:120:30e8:0:0:0:11
buetow.org. 86400 IN MX 10 mail.ian
dns1 86400 IN A 78.46.80.70
dns1 86400 IN AAAA 2a01:4f8:120:30e8:0:0:0:15
dns2 86400 IN A 164.177.171.32
dns2 86400 IN AAAA 2a03:2500:1:6:20::
.
.
.
.
</pre>
<br />
<span>That is my master DNS server. My slave DNS server runs in another Jail on another bare-metal machine. Everything is set up similar to the master DNS server. However, that server is located in a different DC and different IP subnets. The only difference is the "named.conf". It&#39;s configured to be a slave, and that means that the "dynamicdb" gets populated by BIND itself while doing zone transfers from the master.</span><br />
<br />
<pre>
paul uranus:~/git/blog/source [4279]% ssh admin@dns2.buetow.org tail -n 11 /usr/local/etc/namedb/named.conf
zone "buetow.org" {
    type slave;
    masters { 78.46.80.70; };
    file "/usr/local/etc/namedb/dynamic/buetow.org";
};

zone "buetow.zone" {
    type slave;
    masters { 78.46.80.70; };
    file "/usr/local/etc/namedb/dynamic/buetow.zone";
};
</pre>
<br />
<h2 style='display: inline'>The result</h2><br />
<br />
<span>The result looks like this now:</span><br />
<br />
<pre>
% dig -t ns buetow.org
; &lt;&lt;&gt;&gt; DiG 9.10.3-P4-RedHat-9.10.3-12.P4.fc23 &lt;&lt;&gt;&gt; -t ns buetow.org
;; global options: +cmd
;; Got answer:
;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 37883
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;buetow.org.			IN	NS

;; ANSWER SECTION:
buetow.org.		600	IN	NS	dns2.buetow.org.
buetow.org.		600	IN	NS	dns1.buetow.org.

;; Query time: 41 msec
;; SERVER: 192.168.1.254#53(192.168.1.254)
;; WHEN: Sun May 22 11:34:11 BST 2016
;; MSG SIZE  rcvd: 77

% dig -t any buetow.org @dns1.buetow.org
; &lt;&lt;&gt;&gt; DiG 9.10.3-P4-RedHat-9.10.3-12.P4.fc23 &lt;&lt;&gt;&gt; -t any buetow.org @dns1.buetow.org
;; global options: +cmd
;; Got answer:
;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 49876
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 7

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;buetow.org.			IN	ANY

;; ANSWER SECTION:
buetow.org.		86400	IN	A	78.46.80.70
buetow.org.		86400	IN	AAAA	2a01:4f8:120:30e8::11
buetow.org.		86400	IN	MX	10 mail.ian.buetow.org.
buetow.org.		3600	IN	SOA	dns1.buetow.org. domains.buetow.org. 25 604800 86400 2419200 604800
buetow.org.		3600	IN	NS	dns2.buetow.org.
buetow.org.		3600	IN	NS	dns1.buetow.org.

;; ADDITIONAL SECTION:
mail.ian.buetow.org.	86400	IN	A	78.46.80.70
dns1.buetow.org.	86400	IN	A	78.46.80.70
dns2.buetow.org.	86400	IN	A	164.177.171.32
mail.ian.buetow.org.	86400	IN	AAAA	2a01:4f8:120:30e8::12
dns1.buetow.org.	86400	IN	AAAA	2a01:4f8:120:30e8::15
dns2.buetow.org.	86400	IN	AAAA	2a03:2500:1:6:20::

;; Query time: 42 msec
;; SERVER: 78.46.80.70#53(78.46.80.70)
;; WHEN: Sun May 22 11:34:41 BST 2016
;; MSG SIZE  rcvd: 322
</pre>
<br />
<h2 style='display: inline'>Monitoring</h2><br />
<br />
<span>For monitoring, I am using Icinga2 (I am operating two Icinga2 instances in two different DCs). I may have to post another blog article about Icinga2, but to get the idea, these were the snippets added to my Icinga2 configuration:</span><br />
<br />
<pre>
apply Service "dig" {
    import "generic-service"

    check_command = "dig"
    vars.dig_lookup = "buetow.org"
    vars.timeout = 30

    assign where host.name == "dns.ian.buetow.org" || host.name == "caprica.ian.buetow.org"
}

apply Service "dig6" {
    import "generic-service"

    check_command = "dig"
    vars.dig_lookup = "buetow.org"
    vars.timeout = 30
    vars.check_ipv6 = true

    assign where host.name == "dns.ian.buetow.org" || host.name == "caprica.ian.buetow.org"
}
</pre>
<br />
<h2 style='display: inline'>DNS update workflow</h2><br />
<br />
<span>Whenever I have to change a DNS entry, all I have to do is:</span><br />
<br />
<ul>
<li>Git clone or update the Puppet repository</li>
<li>Update/commit and push the zone file (e.g. "buetow.org")</li>
<li>Wait for Puppet. Puppet will deploy that updated zone file. And it will reload the BIND server.</li>
<li>The BIND server will notify all slave DNS servers (at the moment, only one). And it will transfer the new version of the zone.</li>
</ul><br />
<span>That&#39;s much more comfortable now than manually clicking at some web UIs at Schlund Technologies.</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Offsite backup with ZFS (Part 2)</title>
        <link href="gemini://foo.zone/gemfeed/2016-04-16-offsite-backup-with-zfs-part2.gmi" />
        <id>gemini://foo.zone/gemfeed/2016-04-16-offsite-backup-with-zfs-part2.gmi</id>
        <updated>2016-04-16T22:43:42+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>I enhanced the procedure a bit. From now on, I have two external 2TB USB hard drives. Both are set up precisely the same way. To decrease the probability that both drives will not fail simultaneously, they are of different brands. One drive is kept at a secret location. The other one is held at home, right next to my HP MicroServer.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Offsite backup with ZFS (Part 2)</h1><br />
<br />
<span class='quote'>Published at 2016-04-16T22:43:42+01:00</span><br />
<br />
<pre>
 ________________
|# :           : #|
|  : ZFS/GELI  :  |________________ 
|  :   Offsite : |# :           : #|
|  :  Backup 1 : |  : ZFS/GELI  :  |
|  :___________: |  :   Offsite :  |
|     _________  |  :  Backup 2 :  |
|    | __      | |  :___________:  |
|    ||  |     | |     _________   |
\____||__|_____|_|    | __      |  |
                 |    ||  |     |  |
                 \____||__|_____|__|
</pre>
<br />
<a class='textlink' href='./2016-04-03-offsite-backup-with-zfs.html'>Offsite backup with ZFS Part 1</a><br />
<a class='textlink' href='./2016-04-16-offsite-backup-with-zfs-part2.html'>Offsite backup with ZFS Part 2 (you are reading this atm.)</a><br />
<br />
<span>I enhanced the procedure a bit. From now on, I have two external 2TB USB hard drives. Both are set up precisely the same way. To decrease the probability that both drives will not fail simultaneously, they are of different brands. One drive is kept at a secret location. The other one is held at home, right next to my HP MicroServer.</span><br />
<br />
<span>Whenever I update the offsite backup, I am doing it to the drive, which is kept locally. Afterwards, I bring it to the secret location, swap the drives, and bring the other back home. This ensures that I will always have an offsite backup available at a different location than my home - even while updating one copy of it.</span><br />
<br />
<span>Furthermore, I added scrubbing ("zpool scrub...") to the script. It ensures that the file system is consistent and that there are no bad blocks on the disk and the file system. To increase the reliability, I also run a "zfs set copies=2 zroot". That setting is also synchronized to the offsite ZFS pool. ZFS stores every data block to disk twice now. Yes, it consumes twice as much disk space, making it better fault-tolerant against hardware errors (e.g. only individual disk sectors going bad). </span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Jails and ZFS with Puppet on FreeBSD</title>
        <link href="gemini://foo.zone/gemfeed/2016-04-09-jails-and-zfs-on-freebsd-with-puppet.gmi" />
        <id>gemini://foo.zone/gemfeed/2016-04-09-jails-and-zfs-on-freebsd-with-puppet.gmi</id>
        <updated>2016-04-09T18:29:47+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Over the last couple of years I wrote quite a few Puppet modules in order to manage my personal server infrastructure. One of them manages FreeBSD Jails and another one ZFS file systems. I thought I would give a brief overview in how it looks and feels.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Jails and ZFS with Puppet on FreeBSD</h1><br />
<br />
<span class='quote'>Published at 2016-04-09T18:29:47+01:00</span><br />
<br />
<pre>
            __     __
           (( \---/ ))
            )__   __(
           / ()___() \
           \  /(_)\  /
            \ \_|_/ /
      _______&gt;     &lt;_______
     //\      |&gt;o&lt;|      /\\
     \\/___           ___\//
           |         |
           |         |
           |         |
           |         |
           `--....---&#39;
             \     \
              \     `.     hjw
               \      `.
</pre>
<br />
<span>Over the last couple of years I wrote quite a few Puppet modules in order to manage my personal server infrastructure. One of them manages FreeBSD Jails and another one ZFS file systems. I thought I would give a brief overview in how it looks and feels.</span><br />
<br />
<h2 style='display: inline'>ZFS</h2><br />
<br />
<span>The ZFS module is a pretty basic one. It does not manage ZFS pools yet as I am not creating them often enough which would justify implementing an automation. But let&#39;s see how we can create a ZFS file system (on an already given ZFS pool named ztank):</span><br />
<br />
<span>Puppet snippet:</span><br />
<br />
<pre>
zfs::create { &#39;ztank/foo&#39;:
  ensure     =&gt; present,
  filesystem =&gt; &#39;/srv/foo&#39;,

  require =&gt; File[&#39;/srv&#39;],
}
</pre>
<br />
<span>Puppet run:</span><br />
<br />
<pre>
admin alphacentauri:/opt/git/server/puppet/manifests [1212]% puppet.apply
Password:
Info: Loading facts
Info: Loading facts
Info: Loading facts
Info: Loading facts
Notice: Compiled catalog for alphacentauri.home in environment production in 7.14 seconds
Info: Applying configuration version &#39;1460189837&#39;
Info: mount[files]: allowing * access
Info: mount[restricted]: allowing * access
Notice: /Stage[main]/Main/Node[alphacentauri]/Zfs::Create[ztank/foo]/Exec[ztank/foo_create]/returns: executed successfully
Notice: Finished catalog run in 25.41 seconds
admin alphacentauri:~ [1213]% zfs list | grep foo
ztank/foo                     96K  1.13T    96K  /srv/foo
admin alphacentauri:~ [1214]% df | grep foo
ztank/foo                  1214493520        96 1214493424     0%    /srv/foo
admin alphacentauri:~ [1215]% 
</pre>
<br />
<span>The destruction of the file system just requires to set "ensure" to "absent" in Puppet:</span><br />
<br />
<pre>
zfs::create { &#39;ztank/foo&#39;:
  ensure     =&gt; absent,
  filesystem =&gt; &#39;/srv/foo&#39;,

  require =&gt; File[&#39;/srv&#39;],
}¬
</pre>
<br />
<span>Puppet run:</span><br />
<br />
<pre>
admin alphacentauri:/opt/git/server/puppet/manifests [1220]% puppet.apply
Password:
Info: Loading facts
Info: Loading facts
Info: Loading facts
Info: Loading facts
Notice: Compiled catalog for alphacentauri.home in environment production in 6.14 seconds
Info: Applying configuration version &#39;1460190203&#39;
Info: mount[files]: allowing * access
Info: mount[restricted]: allowing * access
Notice: /Stage[main]/Main/Node[alphacentauri]/Zfs::Create[ztank/foo]/Exec[zfs destroy -r ztank/foo]/returns: executed successfully
Notice: Finished catalog run in 22.72 seconds
admin alphacentauri:/opt/git/server/puppet/manifests [1221]% zfs list | grep foo
zsh: done       zfs list | 
zsh: exit 1     grep foo
admin alphacentauri:/opt/git/server/puppet/manifests [1222:1]% df | grep foo
zsh: done       df | 
zsh: exit 1     grep foo
</pre>
<br />
<h2 style='display: inline'>Jails</h2><br />
<br />
<span>Here is an example in how a FreeBSD Jail can be created. The Jail will have its own public IPv6 address. And it will have its own internal IPv4 address with IPv4 NAT to the internet (this is due to the limitation that the host server only got one public IPv4 address which requires sharing between all the Jails).</span><br />
<br />
<span>Furthermore, Puppet will ensure that the Jail will have its own ZFS file system (internally it is using the ZFS module). Please notice that the NAT requires the packet filter to be setup correctly (not covered in this blog post).</span><br />
<br />
<pre>
include jail::freebsd

# Cloned interface for Jail IPv4 NAT
freebsd::rc_config { &#39;cloned_interfaces&#39;:
  value =&gt; &#39;lo1&#39;,
}
freebsd::rc_config { &#39;ipv4_addrs_lo1&#39;:
  value =&gt; &#39;192.168.0.1-24/24&#39;
}

freebsd::ipalias { &#39;2a01:4f8:120:30e8::17&#39;:
  ensure    =&gt; up,
  proto     =&gt; &#39;inet6&#39;,
  preflen   =&gt; &#39;64&#39;,
  interface =&gt; &#39;re0&#39;,
  aliasnum  =&gt; &#39;8&#39;,
}

class { &#39;jail&#39;:
  ensure              =&gt; present,
  jails_config        =&gt; {
    sync                     =&gt; {
      &#39;_ensure&#39;             =&gt; present,
      &#39;_type&#39;               =&gt; &#39;freebsd&#39;,
      &#39;_mirror&#39;             =&gt; &#39;ftp://ftp.de.freebsd.org&#39;,
      &#39;_remote_path&#39;        =&gt; &#39;FreeBSD/releases/amd64/10.1-RELEASE&#39;,
      &#39;_dists&#39;              =&gt; [ &#39;base.txz&#39;, &#39;doc.txz&#39;, ],
      &#39;_ensure_directories&#39; =&gt; [ &#39;/opt&#39;, &#39;/opt/enc&#39; ],
      &#39;_ensure_zfs&#39;         =&gt; [ &#39;/sync&#39; ],
      &#39;host.hostname&#39;       =&gt; "&#39;sync.ian.buetow.org&#39;",
      &#39;ip4.addr&#39;            =&gt; &#39;192.168.0.17&#39;,
      &#39;ip6.addr&#39;            =&gt; &#39;2a01:4f8:120:30e8::17&#39;,
    },
  }
}
</pre>
<br />
<span>This is how the result looks like:</span><br />
<br />
<pre>
admin sun:/etc [1939]% puppet.apply
Info: Loading facts
Info: Loading facts
Info: Loading facts
Info: Loading facts
Notice: Compiled catalog for sun.ian.buetow.org in environment production in 1.80 seconds
Info: Applying configuration version &#39;1460190986&#39;
Notice: /Stage[main]/Jail/File[/etc/jail.conf]/ensure: created
Info: mount[files]: allowing * access
Info: mount[restricted]: allowing * access
Info: Computing checksum on file /etc/motd
Info: /Stage[main]/Motd/File[/etc/motd]: Filebucketed /etc/motd to puppet with sum fced1b6e89f50ef2c40b0d7fba9defe8
Notice: /Stage[main]/Jail/Jail::Create[sync]/File[/jail/sync]/ensure: created
Notice: /Stage[main]/Jail/Jail::Create[sync]/Zfs::Create[zroot/jail/sync]/Exec[zroot/jail/sync_create]/returns: executed successfully
Notice: /Stage[main]/Jail/Jail::Create[sync]/File[/jail/sync/opt]/ensure: created
Notice: /Stage[main]/Jail/Jail::Create[sync]/File[/jail/sync/opt/enc]/ensure: created
Notice: /Stage[main]/Jail/Jail::Create[sync]/Jail::Ensure_zfs[/sync]/Zfs::Create[zroot/jail/sync/sync]/Exec[zroot/jail/sync/sync_create]/returns: executed successfully
Notice: /Stage[main]/Jail/Jail::Create[sync]/Jail::Freebsd::Create[sync]/File[/jail/sync/.jailbootstrap]/ensure: created
Notice: /Stage[main]/Jail/Jail::Create[sync]/Jail::Freebsd::Create[sync]/File[/etc/fstab.jail.sync]/ensure: created
Notice: /Stage[main]/Jail/Jail::Create[sync]/Jail::Freebsd::Create[sync]/File[/jail/sync/.jailbootstrap/bootstrap.sh]/ensure: created
Notice: /Stage[main]/Jail/Jail::Create[sync]/Jail::Freebsd::Create[sync]/Exec[sync_bootstrap]/returns: executed successfully
Notice: Finished catalog run in 49.72 seconds
admin sun:/etc [1942]% ls -l /jail/sync
total 154
-r--r--r--   1 root  wheel  6198 11 Nov  2014 COPYRIGHT
drwxr-xr-x   2 root  wheel    47 11 Nov  2014 bin
drwxr-xr-x   7 root  wheel    43 11 Nov  2014 boot
dr-xr-xr-x   2 root  wheel     2 11 Nov  2014 dev
drwxr-xr-x  23 root  wheel   101  9 Apr 10:37 etc
drwxr-xr-x   3 root  wheel    50 11 Nov  2014 lib
drwxr-xr-x   3 root  wheel     4 11 Nov  2014 libexec
drwxr-xr-x   2 root  wheel     2 11 Nov  2014 media
drwxr-xr-x   2 root  wheel     2 11 Nov  2014 mnt
drwxr-xr-x   3 root  wheel     3  9 Apr 10:36 opt
dr-xr-xr-x   2 root  wheel     2 11 Nov  2014 proc
drwxr-xr-x   2 root  wheel   143 11 Nov  2014 rescue
drwxr-xr-x   2 root  wheel     6 11 Nov  2014 root
drwxr-xr-x   2 root  wheel   132 11 Nov  2014 sbin
drwxr-xr-x   2 root  wheel     2  9 Apr 10:36 sync
lrwxr-xr-x   1 root  wheel    11 11 Nov  2014 sys -&gt; usr/src/sys
drwxrwxrwt   2 root  wheel     2 11 Nov  2014 tmp
drwxr-xr-x  14 root  wheel    14 11 Nov  2014 usr
drwxr-xr-x  24 root  wheel    24 11 Nov  2014 var
admin sun:/etc [1943]% zfs list | grep sync;df | grep sync
zroot/jail/sync                 162M   343G   162M  /jail/sync
zroot/jail/sync/sync            144K   343G   144K  /jail/sync/sync
/opt/enc                                                 5061624     84248    4572448     2%    /jail/sync/opt/enc
zroot/jail/sync                                        360214972    166372  360048600     0%    /jail/sync
zroot/jail/sync/sync                                   360048744       144  360048600     0%    /jail/sync/sync
admin sun:/etc [1944]% cat /etc/fstab.jail.sync
# Generated by Puppet for a Jail.
# Can contain file systems to be mounted curing jail start.
admin sun:/etc [1945]% cat /etc/jail.conf
# Generated by Puppet

allow.chflags = true;
exec.start = &#39;/bin/sh /etc/rc&#39;;
exec.stop = &#39;/bin/sh /etc/rc.shutdown&#39;;
mount.devfs = true;
mount.fstab = "/etc/fstab.jail.$name";
path = "/jail/$name";

sync {
      host.hostname = &#39;sync.ian.buetow.org&#39;;
      ip4.addr = 192.168.0.17;
      ip6.addr = 2a01:4f8:120:30e8::17;
}
admin sun:/etc [1955]% sudo service jail start sync
Password:
Starting jails: sync.
admin sun:/etc [1956]% jls | grep sync
   103  192.168.0.17    sync.ian.buetow.org           /jail/sync
admin sun:/etc [1957]% sudo jexec 103 /bin/csh
root@sync:/ # ifconfig -a
re0: flags=8843&lt;UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST&gt; metric 0 mtu 1500
     options=8209b&lt;RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,WOL_MAGIC,LINKSTATE&gt;
     ether 50:46:5d:9f:fd:1e
     inet6 2a01:4f8:120:30e8::17 prefixlen 64 
     nd6 options=8021&lt;PERFORMNUD,AUTO_LINKLOCAL,DEFAULTIF&gt;
     media: Ethernet autoselect (1000baseT &lt;full-duplex&gt;)
     status: active
lo0: flags=8049&lt;UP,LOOPBACK,RUNNING,MULTICAST&gt; metric 0 mtu 16384
     options=600003&lt;RXCSUM,TXCSUM,RXCSUM_IPV6,TXCSUM_IPV6&gt;
     nd6 options=21&lt;PERFORMNUD,AUTO_LINKLOCAL&gt;
     lo1: flags=8049&lt;UP,LOOPBACK,RUNNING,MULTICAST&gt; metric 0 mtu 16384
     options=600003&lt;RXCSUM,TXCSUM,RXCSUM_IPV6,TXCSUM_IPV6&gt;
     inet 192.168.0.17 netmask 0xffffffff 
     nd6 options=29&lt;PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL&gt;
</pre>
<br />
<h2 style='display: inline'>Inside-Jail Puppet</h2><br />
<br />
<span>To automatically setup the applications running in the Jail I am using Puppet as well. I wrote a few scripts which bootstrap Puppet inside of a newly created Jail. It is doing the following:</span><br />
<br />
<ul>
<li>Mounts an encrypted container (containing a secret Puppet manifests [git repository])</li>
<li>Activates "pkg-ng", the FreeBSD binary package manager, in the Jail</li>
<li>Installs Puppet plus all dependencies in the Jail</li>
<li>Updates the Jail via "freebsd-update" to the latest version</li>
<li>Restarts the Jail and invokes Puppet.</li>
<li>Puppet then also schedules a periodic cron job for the next Puppet runs.</li>
</ul><br />
<pre>
admin sun:~ [1951]% sudo /opt/snonux/local/etc/init.d/enc activate sync
Starting jails: dns.
The package management tool is not yet installed on your system.
Do you want to fetch and install it now? [y/N]: y
Bootstrapping pkg from pkg+http://pkg.FreeBSD.org/freebsd:10:x86:64/latest, please wait...
Verifying signature with trusted certificate pkg.freebsd.org.2013102301... done
[sync.ian.buetow.org] Installing pkg-1.7.2...
[sync.ian.buetow.org] Extracting pkg-1.7.2: 100%
Updating FreeBSD repository catalogue...
[sync.ian.buetow.org] Fetching meta.txz: 100%    944 B   0.9kB/s    00:01    
[sync.ian.buetow.org] Fetching packagesite.txz: 100%    5 MiB   5.6MB/s    00:01   
Processing entries: 100%
FreeBSD repository update completed. 25091 packages processed.
Updating database digests format: 100%
The following 20 package(s) will be affected (of 0 checked):

  New packages to be INSTALLED:
          git: 2.7.4_1
          expat: 2.1.0_3
          python27: 2.7.11_1
          libffi: 3.2.1
          indexinfo: 0.2.4
          gettext-runtime: 0.19.7
          p5-Error: 0.17024
          perl5: 5.20.3_9
          cvsps: 2.1_1
          p5-Authen-SASL: 2.16_1
          p5-Digest-HMAC: 1.03_1
          p5-GSSAPI: 0.28_1
          curl: 7.48.0_1
          ca_root_nss: 3.22.2
          p5-Net-SMTP-SSL: 1.03
          p5-IO-Socket-SSL: 2.024
          p5-Net-SSLeay: 1.72
          p5-IO-Socket-IP: 0.37
          p5-Socket: 2.021
          p5-Mozilla-CA: 20160104

          The process will require 144 MiB more space.
          30 MiB to be downloaded.
[sync.ian.buetow.org] Fetching git-2.7.4_1.txz: 100%    4 MiB   3.7MB/s    00:01    
[sync.ian.buetow.org] Fetching expat-2.1.0_3.txz: 100%   98 KiB 100.2kB/s    00:01    
[sync.ian.buetow.org] Fetching python27-2.7.11_1.txz: 100%   10 MiB  10.7MB/s    00:01    
[sync.ian.buetow.org] Fetching libffi-3.2.1.txz: 100%   35 KiB  36.2kB/s    00:01    
[sync.ian.buetow.org] Fetching indexinfo-0.2.4.txz: 100%    5 KiB   5.0kB/s    00:01    
[sync.ian.buetow.org] Fetching gettext-runtime-0.19.7.txz: 100%  148 KiB 151.1kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Error-0.17024.txz: 100%   24 KiB  24.8kB/s    00:01    
[sync.ian.buetow.org] Fetching perl5-5.20.3_9.txz: 100%   13 MiB   6.9MB/s    00:02    
[sync.ian.buetow.org] Fetching cvsps-2.1_1.txz: 100%   41 KiB  42.1kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Authen-SASL-2.16_1.txz: 100%   44 KiB  45.1kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Digest-HMAC-1.03_1.txz: 100%    9 KiB   9.5kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-GSSAPI-0.28_1.txz: 100%   41 KiB  41.7kB/s    00:01    
[sync.ian.buetow.org] Fetching curl-7.48.0_1.txz: 100%    2 MiB   2.2MB/s    00:01    
[sync.ian.buetow.org] Fetching ca_root_nss-3.22.2.txz: 100%  324 KiB 331.4kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Net-SMTP-SSL-1.03.txz: 100%   11 KiB  10.8kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-IO-Socket-SSL-2.024.txz: 100%  153 KiB 156.4kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Net-SSLeay-1.72.txz: 100%  234 KiB 239.3kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-IO-Socket-IP-0.37.txz: 100%   27 KiB  27.4kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Socket-2.021.txz: 100%   37 KiB  38.0kB/s    00:01    
[sync.ian.buetow.org] Fetching p5-Mozilla-CA-20160104.txz: 100%  147 KiB 150.8kB/s    00:01    
Checking integrity...
[sync.ian.buetow.org] [1/12] Installing libyaml-0.1.6_2...
[sync.ian.buetow.org] [1/12] Extracting libyaml-0.1.6_2: 100%
[sync.ian.buetow.org] [2/12] Installing libedit-3.1.20150325_2...
[sync.ian.buetow.org] [2/12] Extracting libedit-3.1.20150325_2: 100%
[sync.ian.buetow.org] [3/12] Installing ruby-2.2.4,1...
[sync.ian.buetow.org] [3/12] Extracting ruby-2.2.4,1: 100%
[sync.ian.buetow.org] [4/12] Installing ruby22-gems-2.6.2...
[sync.ian.buetow.org] [4/12] Extracting ruby22-gems-2.6.2: 100%
[sync.ian.buetow.org] [5/12] Installing libxml2-2.9.3...
[sync.ian.buetow.org] [5/12] Extracting libxml2-2.9.3: 100%
[sync.ian.buetow.org] [6/12] Installing dmidecode-3.0...
[sync.ian.buetow.org] [6/12] Extracting dmidecode-3.0: 100%
[sync.ian.buetow.org] [7/12] Installing rubygem-json_pure-1.8.3...
[sync.ian.buetow.org] [7/12] Extracting rubygem-json_pure-1.8.3: 100%
[sync.ian.buetow.org] [8/12] Installing augeas-1.4.0...
[sync.ian.buetow.org] [8/12] Extracting augeas-1.4.0: 100%
[sync.ian.buetow.org] [9/12] Installing rubygem-facter-2.4.4...
[sync.ian.buetow.org] [9/12] Extracting rubygem-facter-2.4.4: 100%
[sync.ian.buetow.org] [10/12] Installing rubygem-hiera1-1.3.4_1...
[sync.ian.buetow.org] [10/12] Extracting rubygem-hiera1-1.3.4_1: 100%
[sync.ian.buetow.org] [11/12] Installing rubygem-ruby-augeas-0.5.0_2...
[sync.ian.buetow.org] [11/12] Extracting rubygem-ruby-augeas-0.5.0_2: 100%
[sync.ian.buetow.org] [12/12] Installing puppet38-3.8.4_1...
===&gt; Creating users and/or groups.
Creating group &#39;puppet&#39; with gid &#39;814&#39;.
Creating user &#39;puppet&#39; with uid &#39;814&#39;.
[sync.ian.buetow.org] [12/12] Extracting puppet38-3.8.4_1: 100%
.
.
.
.
.
Looking up update.FreeBSD.org mirrors... 4 mirrors found.
Fetching public key from update4.freebsd.org... done.
Fetching metadata signature for 10.1-RELEASE from update4.freebsd.org... done.
Fetching metadata index... done.
Fetching 2 metadata files... done.
Inspecting system... done.
Preparing to download files... done.
Fetching 874 patches.....10....20....30....
.
.
.
Applying patches... done.
Fetching 1594 files... 
Installing updates...
done.
Info: Loading facts
Info: Loading facts
Info: Loading facts
Info: Loading facts
Could not retrieve fact=&#39;pkgng_version&#39;, resolution=&#39;&lt;anonymous&gt;&#39;: undefined method `pkgng_enabled&#39; for Facter:Module
Warning: Config file /usr/local/etc/puppet/hiera.yaml not found, using Hiera defaults
Notice: Compiled catalog for sync.ian.buetow.org in environment production in 1.31 seconds
Warning: Found multiple default providers for package: pkgng, gem, pip; using pkgng
Info: Applying configuration version &#39;1460192563&#39;
Notice: /Stage[main]/S_base_freebsd/User[root]/shell: shell changed &#39;/bin/csh&#39; to &#39;/bin/tcsh&#39;
Notice: /Stage[main]/S_user::Root_files/S_user::All_files[root_user]/File[/root/user]/ensure: created
Notice: /Stage[main]/S_user::Root_files/S_user::My_files[root]/File[/root/userfiles]/ensure: created
Notice: /Stage[main]/S_user::Root_files/S_user::My_files[root]/File[/root/.task]/ensure: created
.
.
.
.
Notice: Finished catalog run in 206.09 seconds
</pre>
<br />
<h2 style='display: inline'>Managing multiple Jails</h2><br />
<br />
<span>Of course I am operating multiple Jails on the same host this way with Puppet:</span><br />
<br />
<ul>
<li>A Jail for the MTA</li>
<li>A Jail for the Webserver</li>
<li>A Jail for BIND DNS server</li>
<li>A Jail for syncing data forth and back between various servers</li>
<li>A Jail for other personal (experimental) use</li>
<li>...etc</li>
</ul><br />
<span>All done in a pretty automated manor. </span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Offsite backup with ZFS</title>
        <link href="gemini://foo.zone/gemfeed/2016-04-03-offsite-backup-with-zfs.gmi" />
        <id>gemini://foo.zone/gemfeed/2016-04-03-offsite-backup-with-zfs.gmi</id>
        <updated>2016-04-03T22:43:42+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>When it comes to data storage and potential data loss, I am a paranoid person. It is due to my job and a personal experience I encountered over ten years ago: A single drive failure and loss of all my data (pictures, music, etc.).</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Offsite backup with ZFS</h1><br />
<br />
<span class='quote'>Published at 2016-04-03T22:43:42+01:00</span><br />
<br />
<pre>
 ________________
|# :           : #|
|  : ZFS/GELI  :  |
|  :   Offsite :  |
|  :  Backup   :  |
|  :___________:  |
|     _________   |
|    | __      |  |
|    ||  |     |  |
\____||__|_____|__|
</pre>
<br />
<a class='textlink' href='./2016-04-03-offsite-backup-with-zfs.html'>Offsite backup with ZFS Part 1 (you are reading this atm.)</a><br />
<a class='textlink' href='./2016-04-16-offsite-backup-with-zfs-part2.html'>Offsite backup with ZFS Part 2</a><br />
<br />
<h2 style='display: inline'>Please don&#39;t lose all my pictures again!</h2><br />
<br />
<span>When it comes to data storage and potential data loss, I am a paranoid person. It is due to my job and a personal experience I encountered over ten years ago: A single drive failure and loss of all my data (pictures, music, etc.).</span><br />
<br />
<span>A little about my personal infrastructure: I am running my own (mostly FreeBSD based) root servers (across several countries: Two in Germany, one in Canada, one in Bulgaria) which store all my online data (E-Mail and my Git repositories). I am syncing incremental (and encrypted) ZFS snapshots between these servers forth and back so either data can be recovered from the other server.</span><br />
<br />
<h2 style='display: inline'>Local storage box for offline data</h2><br />
<br />
<span>Also, I am operating a local server (an HP MicroServer) at home in my apartment. Full snapshots of all ZFS volumes are pulled from the "online" servers to the local server every other week and the incremental ZFS snapshots every day. That local server has a ZFS ZMIRROR with three disks configured (local triple redundancy). I keep up to half a year worth of ZFS snapshots of all volumes. That local server also contains all my offline data such as pictures, private documents, videos, books, various other backups, etc.</span><br />
<br />
<span>Once weekly, all the local server data is copied to two external USB drives as a backup (without the historic snapshots). For simplicity, these USB drives are not formatted with ZFS but with good old UFS. This gives me a chance to recover from a (potential) ZFS disaster. ZFS is a complex thing. Sometimes it is good not to trust complicated things!</span><br />
<br />
<h2 style='display: inline'>Storing it at my apartment is not enough</h2><br />
<br />
<span>Now I am thinking about an offsite backup of all this local data. The problem is that all the data remains on a single physical location: My local MicroServer. What happens when the house burns or my server,  including the internal disks and the attached USB drives, gets stolen? My first thought was to back up everything to the "cloud". However, the significant issue here is the limited amount of available upload bandwidth (only 1MBit/s).</span><br />
<br />
<span>The solution is adding another USB drive (2TB) with an encryption container (GELI) and a ZFS pool. The GELI encryption requires a secret key and a secret passphrase. I am updating the data to that drive once every three months (my calendar is reminding me about it), and afterwards, I keep that drive at a secret location outside of my apartment. All the information needed to decrypt (mounting the GELI container) is stored at another (secure) place. Key and passphrase are kept at different sites, though. Even if someone knew of it, he would not be able to decrypt it as some additional insider knowledge would be required as well.</span><br />
<br />
<h2 style='display: inline'>Walking one round less</h2><br />
<br />
<span>I am thinking of buying a second 2TB USB drive and setting it up the same way as the first one. So I could alternate the backups. One drive would be at the secret location, and the other drive would be at home. And these drives would swap place after each cycle. This would give some security about the failure of that drive, and I would have to go to the secret location only once (swapping the drives) instead of twice (picking that drive up to update the data + bringing it back to the remote location).</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Run Debian on your phone with Debroid</title>
        <link href="gemini://foo.zone/gemfeed/2015-12-05-run-debian-on-your-phone-with-debroid.gmi" />
        <id>gemini://foo.zone/gemfeed/2015-12-05-run-debian-on-your-phone-with-debroid.gmi</id>
        <updated>2015-12-05T16:12:57+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>You can use the following tutorial to install a full-blown Debian GNU/Linux Chroot on an LG G3 D855 CyanogenMod 13 (Android 6). First of all, you need to have root permissions on your phone, and you also need to have the developer mode activated. The following steps have been tested on Linux (Fedora 23).</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Run Debian on your phone with Debroid</h1><br />
<br />
<span class='quote'>Published at 2015-12-05T16:12:57+00:00; Updated at 2021-05-16</span><br />
<br />
<pre>
 ____       _               _     _ 
|  _ \  ___| |__  _ __ ___ (_) __| |
| | | |/ _ \ &#39;_ \| &#39;__/ _ \| |/ _` |
| |_| |  __/ |_) | | | (_) | | (_| |
|____/ \___|_.__/|_|  \___/|_|\__,_|
                                    
</pre>
<br />
<span>You can use the following tutorial to install a full-blown Debian GNU/Linux Chroot on an LG G3 D855 CyanogenMod 13 (Android 6). First of all, you need to have root permissions on your phone, and you also need to have the developer mode activated. The following steps have been tested on Linux (Fedora 23).</span><br />
<br />
<a href='./2015-12-05-run-debian-on-your-phone-with-debroid/Deboroid.png'><img src='./2015-12-05-run-debian-on-your-phone-with-debroid/Deboroid.png' /></a><br />
<br />
<h2 style='display: inline'>Foreword</h2><br />
<br />
<span>A couple of years have passed since I last worked on Debroid. Currently, I am using the Termux app on Android, which is less sophisticated than a fully blown Debian installation but sufficient for my current requirements. The content of this site may be still relevant, and it would also work with more recent versions of Debian and Android. I would expect that some minor modifications need to be made, though. </span><br />
<br />
<h2 style='display: inline'>Step by step guide</h2><br />
<br />
<span>All scripts mentioned here can be found on GitHub at:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/debroid'>https://codeberg.org/snonux/debroid</a><br />
<br />
<h3 style='display: inline'>First debootstrap stage</h3><br />
<br />
<span>This is to be performed on a Fedora Linux machine (could work on a Debian too, but Fedora is just what I use on my Laptop). The following steps prepare an initial Debian base image, which can then be transferred to the phone.</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>sudo dnf install debootstrap
<i><font color="#9A1900"># 5g</font></i>
dd <b><font color="#0000FF">if</font></b><font color="#990000">=</font>/dev/zero <font color="#009900">of</font><font color="#990000">=</font>jessie<font color="#990000">.</font>img <font color="#009900">bs</font><font color="#990000">=</font><font color="#009900">$[</font> <font color="#993399">1024</font> <font color="#990000">*</font> <font color="#993399">1024</font> <font color="#990000">]</font> <font color="#990000">\</font>
  <font color="#009900">count</font><font color="#990000">=</font><font color="#009900">$[</font> <font color="#993399">1024</font> <font color="#990000">*</font> <font color="#993399">5</font> <font color="#990000">]</font>

<i><font color="#9A1900"># Show used loop devices</font></i>
sudo losetup -f
<i><font color="#9A1900"># Store the next free one to $loop</font></i>
<font color="#009900">loop</font><font color="#990000">=</font>loopN
sudo losetup /dev<font color="#990000">/</font><font color="#009900">$loop</font> jessie<font color="#990000">.</font>img

mkdir jessie
sudo mkfs<font color="#990000">.</font>ext4 /dev<font color="#990000">/</font><font color="#009900">$loop</font>
sudo mount /dev<font color="#990000">/</font><font color="#009900">$loop</font> jessie
sudo debootstrap --foreign --variant<font color="#990000">=</font>minbase <font color="#990000">\</font>
  --arch armel jessie jessie<font color="#990000">/</font> <font color="#990000">\</font>
  http<font color="#990000">:</font>//http<font color="#990000">.</font>debian<font color="#990000">.</font>net/debian
sudo umount jessie
</pre>
<br />
<h3 style='display: inline'>Copy Debian image to the phone</h3><br />
<br />
<span>Now setup the Debian image on an external SD card on the Phone via Android Debugger as follows:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>adb root <font color="#990000">&amp;&amp;</font> adb wait-for-device <font color="#990000">&amp;&amp;</font> adb shell
mkdir -p /storage/sdcard<font color="#993399">1</font>/Linux/jessie
<b><font color="#0000FF">exit</font></b>

<i><font color="#9A1900"># Sparse image problem, may be too big for copying otherwise</font></i>
gzip jessie<font color="#990000">.</font>img
<i><font color="#9A1900"># Copy over</font></i>
adb push jessie<font color="#990000">.</font>img<font color="#990000">.</font>gz /storage/sdcard<font color="#993399">1</font>/Linux/jessie<font color="#990000">.</font>img<font color="#990000">.</font>gz
adb shell
cd /storage/sdcard<font color="#993399">1</font>/Linux
gunzip jessie<font color="#990000">.</font>img<font color="#990000">.</font>gz

<i><font color="#9A1900"># Show used loop devices</font></i>
losetup -f
<i><font color="#9A1900"># Store the next free one to $loop</font></i>
<font color="#009900">loop</font><font color="#990000">=</font>loopN

<i><font color="#9A1900"># Use the next free one (replace the loop number)</font></i>
losetup /dev/block<font color="#990000">/</font><font color="#009900">$loop</font> <font color="#009900">$(pwd)</font>/jessie<font color="#990000">.</font>img
mount -t ext4 /dev/block<font color="#990000">/</font><font color="#009900">$loop</font> <font color="#009900">$(pwd)</font>/jessie

<i><font color="#9A1900"># Bind-Mound proc, dev, sys`</font></i>
busybox mount --bind /proc <font color="#009900">$(pwd)</font>/jessie/proc
busybox mount --bind /dev <font color="#009900">$(pwd)</font>/jessie/dev
busybox mount --bind /dev/pts <font color="#009900">$(pwd)</font>/jessie/dev/pts
busybox mount --bind /sys <font color="#009900">$(pwd)</font>/jessie/sys

<i><font color="#9A1900"># Bind-Mound the rest of Android</font></i>
mkdir -p <font color="#009900">$(pwd)</font>/jessie/storage/sdcard{<font color="#993399">0</font><font color="#990000">,</font><font color="#993399">1</font>}
busybox mount --bind /storage/emulated <font color="#990000">\</font>
  <font color="#009900">$(pwd)</font>/jessie/storage/sdcard<font color="#993399">0</font>
busybox mount --bind /storage/sdcard<font color="#993399">1</font> <font color="#990000">\</font>
  <font color="#009900">$(pwd)</font>/jessie/storage/sdcard<font color="#993399">1</font>

<i><font color="#9A1900"># Check mounts</font></i>
mount <font color="#990000">|</font> grep jessie
</pre>
<br />
<h3 style='display: inline'>Second debootstrap stage</h3><br />
<br />
<span>This is to be performed on the Android phone itself (inside a Debian chroot):</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>chroot <font color="#009900">$(pwd)</font>/jessie /bin/bash -l
<b><font color="#0000FF">export</font></b> <font color="#009900">PATH</font><font color="#990000">=</font>/bin<font color="#990000">:</font>/usr/bin<font color="#990000">:</font>/usr/local/bin<font color="#990000">:</font>/sbin<font color="#990000">:</font>/usr/sbin<font color="#990000">:</font>/usr/local/sbin
/debootstrap/debootstrap --second-stage
<b><font color="#0000FF">exit</font></b> <i><font color="#9A1900"># Leave chroot</font></i>
<b><font color="#0000FF">exit</font></b> <i><font color="#9A1900"># Leave adb shell</font></i>
</pre>
<br />
<h3 style='display: inline'>Setup of various scripts</h3><br />
<br />
<span>jessie.sh deals with all the loopback mount magic and so on. It will be run later every time you start Debroid on your phone.</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><i><font color="#9A1900"># Install script jessie.sh</font></i>
adb push storage/sdcard<font color="#993399">1</font>/Linux/jessie<font color="#990000">.</font>sh /storage/sdcard/Linux/jessie<font color="#990000">.</font>sh
adb shell
cd /storage/sdcard<font color="#993399">1</font>/Linux
sh jessie<font color="#990000">.</font>sh enter

<i><font color="#9A1900"># Bashrc</font></i>
cat <font color="#990000">&lt;&lt;</font>END <font color="#990000">&gt;~/.</font>bashrc
<b><font color="#0000FF">export</font></b> <font color="#009900">PATH</font><font color="#990000">=</font>/usr/local/sbin<font color="#990000">:</font>/usr/local/bin<font color="#990000">:</font>/usr/sbin<font color="#990000">:</font>/usr/bin<font color="#990000">:</font>/sbin<font color="#990000">:</font>/bin<font color="#990000">:</font><font color="#009900">$PATH</font>
<b><font color="#0000FF">export</font></b> <font color="#009900">EDITOR</font><font color="#990000">=</font>vim
hostname <font color="#009900">$(</font>cat /etc/hostname<font color="#990000">)</font>
END

<i><font color="#9A1900"># Fixing an error message while loading the profile</font></i>
sed -i s<i><font color="#9A1900">#id#/usr/bin/id# /etc/profile</font></i>

<i><font color="#9A1900"># Setting the hostname</font></i>
echo phobos <font color="#990000">&gt;</font> /etc/hostname
echo <font color="#993399">127.0</font><font color="#990000">.</font><font color="#993399">0.1</font> phobos <font color="#990000">&gt;</font> /etc/hosts
hostname phobos

<i><font color="#9A1900"># Apt-sources</font></i>
cat <font color="#990000">&lt;&lt;</font>END <font color="#990000">&gt;</font> sources<font color="#990000">.</font>list
deb http<font color="#990000">:</font>//ftp<font color="#990000">.</font>uk<font color="#990000">.</font>debian<font color="#990000">.</font>org/debian<font color="#990000">/</font> jessie main contrib non-free
deb-src http<font color="#990000">:</font>//ftp<font color="#990000">.</font>uk<font color="#990000">.</font>debian<font color="#990000">.</font>org/debian<font color="#990000">/</font> jessie main contrib non-free
END
apt-get update
apt-get upgrade
apt-get dist-upgrade
<b><font color="#0000FF">exit</font></b> <i><font color="#9A1900"># Exit chroot</font></i>
</pre>
<br />
<h3 style='display: inline'>Entering Debroid and enable a service</h3><br />
<br />
<span>This enters Debroid on your phone and starts the example service uptimed:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>sh jessie<font color="#990000">.</font>sh enter

<i><font color="#9A1900"># Setup example serice uptimed</font></i>
apt-get install uptimed
cat <font color="#990000">&lt;&lt;</font>END <font color="#990000">&gt;</font> /etc/rc<font color="#990000">.</font>debroid
<b><font color="#0000FF">export</font></b> <font color="#009900">PATH</font><font color="#990000">=</font>/usr/local/sbin<font color="#990000">:</font>/usr/local/bin<font color="#990000">:</font>/usr/sbin<font color="#990000">:</font>/usr/bin<font color="#990000">:</font>/sbin<font color="#990000">:</font>/bin<font color="#990000">:</font><font color="#009900">$PATH</font>
service uptimed status <font color="#990000">&amp;&gt;</font>/dev/null <font color="#990000">||</font> service uptimed start
<b><font color="#0000FF">exit</font></b> <font color="#993399">0</font>
END

chmod <font color="#993399">0755</font> /etc/rc<font color="#990000">.</font>debroid
<b><font color="#0000FF">exit</font></b> <i><font color="#9A1900"># Exit chroot</font></i>
<b><font color="#0000FF">exit</font></b> <i><font color="#9A1900"># Exit adb shell</font></i>
</pre>
<br />
<h3 style='display: inline'>Include to Android startup:</h3><br />
<br />
<span>If you want to start Debroid automatically whenever your phone starts, then do the following:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>adb push data/local/userinit<font color="#990000">.</font>sh /data/local/userinit<font color="#990000">.</font>sh
adb shell
chmod <font color="#990000">+</font>x /data/local/userinit<font color="#990000">.</font>sh
<b><font color="#0000FF">exit</font></b>
</pre>
<br />
<span>Reboot &amp; test!  Enjoy!</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>The fibonacci.pl.raku.c Polyglot</title>
        <link href="gemini://foo.zone/gemfeed/2014-03-24-the-fibonacci.pl.c-polyglot.gmi" />
        <id>gemini://foo.zone/gemfeed/2014-03-24-the-fibonacci.pl.c-polyglot.gmi</id>
        <updated>2014-03-24T21:32:53+00:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>The fibonacci.pl.raku.c Polyglot</h1><br />
<br />
<span class='quote'>Published at 2014-03-24T21:32:53+00:00; Updated at 2022-04-23</span><br />
<br />
<span>In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.</span><br />
<br />
<a class='textlink' href='https://en.wikipedia.org/wiki/Polyglot_(computing)'>https://en.wikipedia.org/wiki/Polyglot_(computing)</a><br />
<br />
<h2 style='display: inline'>The Fibonacci numbers</h2><br />
<br />
<span>For fun, I programmed my own Polyglot, which is both valid Perl, Raku, C and C++ code (I have added C++ and Raku support in 2022). The exciting part about C and C++ is that $ is a valid character to start variable names with:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><i><font color="#9A1900">#include &lt;stdio.h&gt;</font></i>

<i><font color="#9A1900">#define $arg function_argument</font></i>
<i><font color="#9A1900">#define my int</font></i>
<i><font color="#9A1900">#define sub int</font></i>
<i><font color="#9A1900">#define BEGIN int main(void)</font></i>

<b><font color="#0000FF">my</font></b> <font color="#009900">$arg</font><font color="#990000">;</font>

<b><font color="#0000FF">sub</font></b> <b><font color="#000000">hello</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">printf</font></b><font color="#990000">(</font><font color="#FF0000">"Hello, welcome to the Fibonacci Numbers!\n"</font><font color="#990000">);</font>
    <b><font color="#0000FF">printf</font></b><font color="#990000">(</font><font color="#FF0000">"This program is all, valid C and C++ and Perl and Raku code!\n"</font><font color="#990000">);</font>
    <b><font color="#0000FF">printf</font></b><font color="#990000">(</font><font color="#FF0000">"It calculates all fibonacci numbers from 0 to 9!\n\n"</font><font color="#990000">);</font>
    <b><font color="#0000FF">return</font></b> <font color="#993399">0</font><font color="#990000">;</font>
<font color="#FF0000">}</font>

<b><font color="#0000FF">sub</font></b> <b><font color="#000000">fibonacci</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">my</font></b> <font color="#009900">$n</font> <font color="#990000">=</font> <font color="#009900">$arg</font><font color="#990000">;</font>

    <b><font color="#0000FF">if</font></b> <font color="#990000">(</font><font color="#009900">$n</font> <font color="#990000">&lt;</font> <font color="#993399">2</font><font color="#990000">)</font> <font color="#FF0000">{</font>
        <b><font color="#0000FF">return</font></b> <font color="#009900">$n</font><font color="#990000">;</font>
    <font color="#FF0000">}</font>

    <font color="#009900">$arg</font> <font color="#990000">=</font> <font color="#009900">$n</font> <font color="#990000">-</font> <font color="#993399">1</font><font color="#990000">;</font>
    <b><font color="#0000FF">my</font></b> <font color="#009900">$fib1</font> <font color="#990000">=</font> <b><font color="#000000">fibonacci</font></b><font color="#990000">();</font>
    <font color="#009900">$arg</font> <font color="#990000">=</font> <font color="#009900">$n</font> <font color="#990000">-</font> <font color="#993399">2</font><font color="#990000">;</font>
    <b><font color="#0000FF">my</font></b> <font color="#009900">$fib2</font> <font color="#990000">=</font> <b><font color="#000000">fibonacci</font></b><font color="#990000">();</font>

    <b><font color="#0000FF">return</font></b> <font color="#009900">$fib1</font> <font color="#990000">+</font> <font color="#009900">$fib2</font><font color="#990000">;</font>
<font color="#FF0000">}</font>

BEGIN <font color="#FF0000">{</font>
    <b><font color="#000000">hello</font></b><font color="#990000">();</font>
    <b><font color="#0000FF">my</font></b> <font color="#009900">$i</font> <font color="#990000">=</font> <font color="#993399">0</font><font color="#990000">;</font>

    <b><font color="#0000FF">while</font></b> <font color="#990000">(</font><font color="#009900">$i</font> <font color="#990000">&lt;=</font> <font color="#993399">10</font><font color="#990000">)</font> <font color="#FF0000">{</font>
        <font color="#009900">$arg</font> <font color="#990000">=</font> <font color="#009900">$i</font><font color="#990000">;</font>
        <b><font color="#0000FF">printf</font></b><font color="#990000">(</font><font color="#FF0000">"fib(%d) = %d\n"</font><font color="#990000">,</font> <font color="#009900">$i</font><font color="#990000">,</font> <b><font color="#000000">fibonacci</font></b><font color="#990000">());</font>
        <font color="#009900">$i</font><font color="#990000">++;</font>
    <font color="#FF0000">}</font>
<font color="#FF0000">}</font>
</pre>
<br />
<span>You can find the full source code at GitHub:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/perl-c-fibonacci'>https://codeberg.org/snonux/perl-c-fibonacci</a><br />
<br />
<h3 style='display: inline'>Let&#39;s run it with C and C++</h3><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#990000">%</font> gcc fibonacci<font color="#990000">.</font>pl<font color="#990000">.</font>raku<font color="#990000">.</font>c -o fibonacci
<font color="#990000">%</font> <font color="#990000">.</font>/fibonacci
Hello<font color="#990000">,</font> welcome to the Fibonacci Numbers<font color="#990000">!</font>
This program is all<font color="#990000">,</font> valid C and C<font color="#990000">++</font> and Perl and Raku code<font color="#990000">!</font>
It calculates all fibonacci numbers from <font color="#993399">0</font> to <font color="#993399">9</font><font color="#990000">!</font>

fib<font color="#990000">(</font><font color="#993399">0</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">0</font>
fib<font color="#990000">(</font><font color="#993399">1</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">2</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">3</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">2</font>
fib<font color="#990000">(</font><font color="#993399">4</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">3</font>
fib<font color="#990000">(</font><font color="#993399">5</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">5</font>
fib<font color="#990000">(</font><font color="#993399">6</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">8</font>
fib<font color="#990000">(</font><font color="#993399">7</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">13</font>
fib<font color="#990000">(</font><font color="#993399">8</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">21</font>
fib<font color="#990000">(</font><font color="#993399">9</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">34</font>
fib<font color="#990000">(</font><font color="#993399">10</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">55</font>

<font color="#990000">%</font> g<font color="#990000">++</font> fibonacci<font color="#990000">.</font>pl<font color="#990000">.</font>raku<font color="#990000">.</font>c -o fibonacci
<font color="#990000">%</font> <font color="#990000">.</font>/fibonacci
Hello<font color="#990000">,</font> welcome to the Fibonacci Numbers<font color="#990000">!</font>
This program is all<font color="#990000">,</font> valid C and C<font color="#990000">++</font> and Perl and Raku code<font color="#990000">!</font>
It calculates all fibonacci numbers from <font color="#993399">0</font> to <font color="#993399">9</font><font color="#990000">!</font>

fib<font color="#990000">(</font><font color="#993399">0</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">0</font>
fib<font color="#990000">(</font><font color="#993399">1</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">2</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">3</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">2</font>
fib<font color="#990000">(</font><font color="#993399">4</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">3</font>
fib<font color="#990000">(</font><font color="#993399">5</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">5</font>
fib<font color="#990000">(</font><font color="#993399">6</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">8</font>
fib<font color="#990000">(</font><font color="#993399">7</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">13</font>
fib<font color="#990000">(</font><font color="#993399">8</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">21</font>
fib<font color="#990000">(</font><font color="#993399">9</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">34</font>
fib<font color="#990000">(</font><font color="#993399">10</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">55</font>
</pre>
<br />
<h3 style='display: inline'>Let&#39;s run it with Perl and Raku</h3><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><font color="#990000">%</font> perl fibonacci<font color="#990000">.</font>pl<font color="#990000">.</font>raku<font color="#990000">.</font>c
Hello<font color="#990000">,</font> welcome to the Fibonacci Numbers<font color="#990000">!</font>
This program is all<font color="#990000">,</font> valid C and C<font color="#990000">++</font> and Perl and Raku code<font color="#990000">!</font>
It calculates all fibonacci numbers from <font color="#993399">0</font> to <font color="#993399">9</font><font color="#990000">!</font>

fib<font color="#990000">(</font><font color="#993399">0</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">0</font>
fib<font color="#990000">(</font><font color="#993399">1</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">2</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">3</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">2</font>
fib<font color="#990000">(</font><font color="#993399">4</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">3</font>
fib<font color="#990000">(</font><font color="#993399">5</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">5</font>
fib<font color="#990000">(</font><font color="#993399">6</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">8</font>
fib<font color="#990000">(</font><font color="#993399">7</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">13</font>
fib<font color="#990000">(</font><font color="#993399">8</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">21</font>
fib<font color="#990000">(</font><font color="#993399">9</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">34</font>
fib<font color="#990000">(</font><font color="#993399">10</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">55</font>

<font color="#990000">%</font> raku fibonacci<font color="#990000">.</font>pl<font color="#990000">.</font>raku<font color="#990000">.</font>c
Hello<font color="#990000">,</font> welcome to the Fibonacci Numbers<font color="#990000">!</font>
This program is all<font color="#990000">,</font> valid C and C<font color="#990000">++</font> and Perl and Raku code<font color="#990000">!</font>
It calculates all fibonacci numbers from <font color="#993399">0</font> to <font color="#993399">9</font><font color="#990000">!</font>

fib<font color="#990000">(</font><font color="#993399">0</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">0</font>
fib<font color="#990000">(</font><font color="#993399">1</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">2</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">1</font>
fib<font color="#990000">(</font><font color="#993399">3</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">2</font>
fib<font color="#990000">(</font><font color="#993399">4</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">3</font>
fib<font color="#990000">(</font><font color="#993399">5</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">5</font>
fib<font color="#990000">(</font><font color="#993399">6</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">8</font>
fib<font color="#990000">(</font><font color="#993399">7</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">13</font>
fib<font color="#990000">(</font><font color="#993399">8</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">21</font>
fib<font color="#990000">(</font><font color="#993399">9</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">34</font>
fib<font color="#990000">(</font><font color="#993399">10</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#993399">55</font>
</pre>
<br />
<span>It&#39;s entertaining to play with :-).</span><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>Perl Daemon (Service Framework)</title>
        <link href="gemini://foo.zone/gemfeed/2011-05-07-perl-daemon-service-framework.gmi" />
        <id>gemini://foo.zone/gemfeed/2011-05-07-perl-daemon-service-framework.gmi</id>
        <updated>2011-05-07T22:26:02+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>PerlDaemon is a minimal daemon for Linux and other Unix like operating systems programmed in Perl. It is a minimal but pretty functional and fairly generic service framework. This means that it does not do anything useful other than providing a framework for starting, stopping, configuring and logging. To do something useful, a module (written in Perl) must be provided.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>Perl Daemon (Service Framework)</h1><br />
<br />
<span class='quote'>Published at 2011-05-07T22:26:02+01:00; Updated at 2021-05-07</span><br />
<br />
<pre>
   a&#39;!   _,,_ a&#39;!   _,,_     a&#39;!   _,,_
     \\_/    \  \\_/    \      \\_/    \.-,
      \, /-( /&#39;-,\, /-( /&#39;-,    \, /-( /
      //\ //\\   //\ //\\       //\ //\\jrei
</pre>
<br />
<span>PerlDaemon is a minimal daemon for Linux and other Unix like operating systems programmed in Perl. It is a minimal but pretty functional and fairly generic service framework. This means that it does not do anything useful other than providing a framework for starting, stopping, configuring and logging. To do something useful, a module (written in Perl) must be provided.</span><br />
<br />
<h2 style='display: inline'>Features</h2><br />
<br />
<span>PerlDaemon supports:</span><br />
<br />
<ul>
<li>Automatic daemonizing</li>
<li>Logging</li>
<li>log rotation (via SIGHUP)</li>
<li>Clean shutdown support (SIGTERM)</li>
<li>Pid file support (incl. check on startup)</li>
<li>Easy to configure</li>
<li>Easy to extend</li>
<li>Multi-instance support (just use a different directory for each instance).</li>
</ul><br />
<h2 style='display: inline'>Quick Guide</h2><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><i><font color="#9A1900"># Starting</font></i>
 <font color="#990000">.</font>/bin/perldaemon start <font color="#990000">(</font>or shortcut <font color="#990000">.</font>/control start<font color="#990000">)</font>

<i><font color="#9A1900"># Stopping</font></i>
 <font color="#990000">.</font>/bin/perldaemon stop <font color="#990000">(</font>or shortcut <font color="#990000">.</font>/control stop<font color="#990000">)</font>

<i><font color="#9A1900"># Alternatively: Starting in foreground </font></i>
<font color="#990000">.</font>/bin/perldaemon start daemon<font color="#990000">.</font><font color="#009900">daemonize</font><font color="#990000">=</font>no <font color="#990000">(</font>or shortcut <font color="#990000">.</font>/control foreground<font color="#990000">)</font>
</pre>
<br />
<span>To stop a daemon from running in foreground mode, "Ctrl+C" must be hit. To see more available startup options run "./control" without any argument.</span><br />
<br />
<h2 style='display: inline'>How to configure</h2><br />
<br />
<span>The daemon instance can be configured in "./conf/perldaemon.conf". If you want to change a property only once, it is also possible to specify it on the command line (which will take precedence over the config file). All available config properties can be displayed via "./control keys":</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>pb@titania<font color="#990000">:~</font>/svn/utils/perldaemon/trunk$ <font color="#990000">.</font>/control keys
<i><font color="#9A1900"># Path to the logfile</font></i>
daemon<font color="#990000">.</font><font color="#009900">logfile</font><font color="#990000">=.</font>/log/perldaemon<font color="#990000">.</font>log

<i><font color="#9A1900"># The amount of seconds until the next event look takes place</font></i>
daemon<font color="#990000">.</font><font color="#009900">loopinterval</font><font color="#990000">=</font><font color="#993399">1</font>

<i><font color="#9A1900"># Path to the modules dir</font></i>
daemon<font color="#990000">.</font>modules<font color="#990000">.</font><font color="#009900">dir</font><font color="#990000">=.</font>/lib/PerlDaemonModules

<i><font color="#9A1900"># Specifies either the daemon should run in daemon or foreground mode</font></i>
daemon<font color="#990000">.</font><font color="#009900">daemonize</font><font color="#990000">=</font>yes

<i><font color="#9A1900"># Path to the pidfile</font></i>
daemon<font color="#990000">.</font><font color="#009900">pidfile</font><font color="#990000">=.</font>/run/perldaemon<font color="#990000">.</font>pid

<i><font color="#9A1900"># Each module should run every run interval seconds</font></i>
daemon<font color="#990000">.</font>modules<font color="#990000">.</font><font color="#009900">runinterval</font><font color="#990000">=</font><font color="#993399">3</font>

<i><font color="#9A1900"># Path to the alive file (is touched every loop interval seconds, usable for monitoring)</font></i>
daemon<font color="#990000">.</font><font color="#009900">alivefile</font><font color="#990000">=.</font>/run/perldaemon<font color="#990000">.</font>alive

<i><font color="#9A1900"># Specifies the working directory</font></i>
daemon<font color="#990000">.</font><font color="#009900">wd</font><font color="#990000">=./</font>
</pre>
<br />
<h2 style='display: inline'>Example </h2><br />
<br />
<span>So let&#39;s start the daemon with a loop interval of 10 seconds:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>$ <font color="#990000">.</font>/control keys <font color="#990000">|</font> grep daemon<font color="#990000">.</font>loopinterval
daemon<font color="#990000">.</font><font color="#009900">loopinterval</font><font color="#990000">=</font><font color="#993399">1</font>
$ <font color="#990000">.</font>/control keys daemon<font color="#990000">.</font><font color="#009900">loopinterval</font><font color="#990000">=</font><font color="#993399">10</font> <font color="#990000">|</font> grep daemon<font color="#990000">.</font>loopinterval
daemon<font color="#990000">.</font><font color="#009900">loopinterval</font><font color="#990000">=</font><font color="#993399">10</font>
$ <font color="#990000">.</font>/control start daemon<font color="#990000">.</font><font color="#009900">loopinterval</font><font color="#990000">=</font><font color="#993399">10</font><font color="#990000">;</font> sleep <font color="#993399">10</font><font color="#990000">;</font> tail -n <font color="#993399">2</font> log/perldaemon<font color="#990000">.</font>log
Starting daemon now<font color="#990000">...</font>
Mon Jun <font color="#993399">13</font> <font color="#993399">11</font><font color="#990000">:</font><font color="#993399">29</font><font color="#990000">:</font><font color="#993399">27</font> <font color="#993399">2011</font> <font color="#990000">(</font>PID <font color="#993399">2838</font><font color="#990000">):</font> Triggering PerlDaemonModules<font color="#990000">::</font>ExampleModule 
<font color="#990000">(</font>last triggered before <font color="#993399">10</font><font color="#990000">.</font>002106s<font color="#990000">;</font> carry<font color="#990000">:</font> <font color="#993399">7</font><font color="#990000">.</font>002106s<font color="#990000">;</font> wanted interval<font color="#990000">:</font> 3s<font color="#990000">)</font>
Mon Jun <font color="#993399">13</font> <font color="#993399">11</font><font color="#990000">:</font><font color="#993399">29</font><font color="#990000">:</font><font color="#993399">27</font> <font color="#993399">2011</font> <font color="#990000">(</font>PID <font color="#993399">2838</font><font color="#990000">):</font> ExampleModule Test <font color="#993399">2</font>
$ <font color="#990000">.</font>/control stop
Stopping daemon now<font color="#990000">...</font>
</pre>
<br />
<span>If you want to change that property forever, either edit perldaemon.conf or do this:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>$ <font color="#990000">.</font>/control keys daemon<font color="#990000">.</font><font color="#009900">loopinterval</font><font color="#990000">=</font><font color="#993399">10</font> <font color="#990000">&gt;</font> new<font color="#990000">.</font>conf<font color="#990000">;</font> mv new<font color="#990000">.</font>conf conf/perldaemon<font color="#990000">.</font>conf
</pre>
<br />
<h2 style='display: inline'>HiRes event loop</h2><br />
<br />
<span>PerlDaemon uses <span class='inlinecode'>Time::HiRes</span> to make sure that all the events run incorrect intervals. For each loop run, a time carry value is recorded and added to the next loop run to catch up on lost time.</span><br />
<br />
<h2 style='display: inline'>Writing your own modules</h2><br />
<br />
<h3 style='display: inline'>Example module</h3><br />
<br />
<span>This is one of the example modules you will find in the source code. It should be pretty self-explanatory if you know Perl :-).</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">package</font></b> PerlDaemonModules<font color="#990000">::</font>ExampleModule<font color="#990000">;</font>

<b><font color="#0000FF">use</font></b> strict<font color="#990000">;</font>
<b><font color="#0000FF">use</font></b> warnings<font color="#990000">;</font>

<b><font color="#0000FF">sub</font></b> <b><font color="#000000">new</font></b> <font color="#990000">(</font>${body}lt;font color="#990000">)</font> <font color="#FF0000">{</font>
  <b><font color="#0000FF">my</font></b> <font color="#990000">(</font><font color="#009900">$class</font><font color="#990000">,</font> <font color="#009900">$conf</font><font color="#990000">)</font> <font color="#990000">=</font> <font color="#009900">@_</font><font color="#990000">;</font>

  <b><font color="#0000FF">my</font></b> <font color="#009900">$self</font> <font color="#990000">=</font> <b><font color="#0000FF">bless</font></b> <font color="#FF0000">{</font> conf <font color="#990000">=&gt;</font> <font color="#009900">$conf</font> <font color="#FF0000">}</font><font color="#990000">,</font> <font color="#009900">$class</font><font color="#990000">;</font>

  <i><font color="#9A1900"># Store some private module stuff</font></i>
  <font color="#009900">$self</font><font color="#990000">-&gt;</font><font color="#FF0000">{</font>counter<font color="#FF0000">}</font> <font color="#990000">=</font> <font color="#993399">0</font><font color="#990000">;</font>

  <b><font color="#0000FF">return</font></b> <font color="#009900">$self</font><font color="#990000">;</font>
<font color="#FF0000">}</font>

<i><font color="#9A1900"># Runs periodically in a loop (set interval in perldaemon.conf)</font></i>
<b><font color="#0000FF">sub</font></b> <b><font color="#0000FF">do</font></b> <font color="#990000">(</font>{body}lt;font color="#990000">)</font> <font color="#FF0000">{</font>
  <b><font color="#0000FF">my</font></b> <font color="#009900">$self</font> <font color="#990000">=</font> <b><font color="#0000FF">shift</font></b><font color="#990000">;</font>
  <b><font color="#0000FF">my</font></b> <font color="#009900">$conf</font> <font color="#990000">=</font> <font color="#009900">$self</font><font color="#990000">-&gt;</font><font color="#FF0000">{</font>conf<font color="#FF0000">}</font><font color="#990000">;</font>
  <b><font color="#0000FF">my</font></b> <font color="#009900">$logger</font> <font color="#990000">=</font> <font color="#009900">$conf</font><font color="#990000">-&gt;</font><font color="#FF0000">{</font>logger<font color="#FF0000">}</font><font color="#990000">;</font>

  <i><font color="#9A1900"># Calculate some private module stuff</font></i>
  <b><font color="#0000FF">my</font></b> <font color="#009900">$count</font> <font color="#990000">=</font> <font color="#990000">++</font><font color="#009900">$self</font><font color="#990000">-&gt;</font><font color="#FF0000">{</font>counter<font color="#FF0000">}</font><font color="#990000">;</font>

  <font color="#009900">$logger</font><font color="#990000">-&gt;</font><b><font color="#000000">logmsg</font></b><font color="#990000">(</font><font color="#FF0000">"ExampleModule Test $count"</font><font color="#990000">);</font>
<font color="#FF0000">}</font>

<font color="#993399">1</font><font color="#990000">;</font>
</pre>
<br />
<h3 style='display: inline'>Your own module</h3><br />
<br />
<span>Want to give it some better use? It&#39;s just as easy as:</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre> cd <font color="#990000">.</font>/lib/PerlDaemonModules<font color="#990000">/</font>
 cp ExampleModule<font color="#990000">.</font>pm YourModule<font color="#990000">.</font>pm
 vi YourModule<font color="#990000">.</font>pm
 cd -
 <font color="#990000">.</font>/bin/perldaemon restart <font color="#990000">(</font>or shortcurt <font color="#990000">.</font>/control restart<font color="#990000">)</font>
</pre>
<br />
<span>Now watch <span class='inlinecode'>./log/perldaemon.log</span> closely. It is a good practice to test your modules in &#39;foreground mode&#39; (see above how to do that).</span><br />
<br />
<span>BTW: You can install as many modules within the same instance as desired. But they are run in sequential order (in future, they can also run in parallel using several threads or processes).</span><br />
<br />
<h2 style='display: inline'>May the source be with you</h2><br />
<br />
<span>You can find PerlDaemon (including the examples) at:</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/perldaemon'>https://codeberg.org/snonux/perldaemon</a><br />
<br />
<span>Other related posts are:</span><br />
<br />
<a class='textlink' href='./2022-05-27-perl-is-still-a-great-choice.html'>2022-05-27 Perl is still a great choice</a><br />
<a class='textlink' href='./2011-05-07-perl-daemon-service-framework.html'>2011-05-07 Perl Daemon (Service Framework) (You are currently reading this)</a><br />
<a class='textlink' href='./2008-06-26-perl-poetry.html'>2008-06-26 Perl Poetry</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
    <entry>
        <title>The Fype Programming Language</title>
        <link href="gemini://foo.zone/gemfeed/2010-05-09-the-fype-programming-language.gmi" />
        <id>gemini://foo.zone/gemfeed/2010-05-09-the-fype-programming-language.gmi</id>
        <updated>2010-05-09T12:48:29+01:00</updated>
        <author>
            <name>Paul Buetow</name>
            <email>paul@dev.buetow.org</email>
        </author>
        <summary>Fype is an interpreted programming language created by me for learning and fun. The interpreter is written in C. It has been tested on FreeBSD and NetBSD and may also work on other Unix like operating systems such as Linux based ones. Besides learning and fun, there is no other use case of why Fype exists as many other programming languages are much faster and more powerful.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <h1 style='display: inline'>The Fype Programming Language</h1><br />
<br />
<span class='quote'>Published at 2010-05-09T12:48:29+01:00; Updated at 2021-05-05</span><br />
<br />
<pre>
      ____                                      _        __       
     / / _|_   _ _ __   ___    _   _  ___  __ _| |__    / _|_   _ 
    / / |_| | | | &#39;_ \ / _ \  | | | |/ _ \/ _` | &#39;_ \  | |_| | | |
 _ / /|  _| |_| | |_) |  __/  | |_| |  __/ (_| | | | |_|  _| |_| |
(_)_/ |_|  \__, | .__/ \___|   \__, |\___|\__,_|_| |_(_)_|  \__, |
           |___/|_|            |___/                        |___/ 
</pre>
<br />
<span>Fype is an interpreted programming language created by me for learning and fun. The interpreter is written in C. It has been tested on FreeBSD and NetBSD and may also work on other Unix like operating systems such as Linux based ones. Besides learning and fun, there is no other use case of why Fype exists as many other programming languages are much faster and more powerful.</span><br />
<br />
<span>The Fype syntax is straightforward and uses a maximum look ahead of 1 and an effortless top-down parsing mechanism. Fype is parsing and interpreting its code simultaneously. This means that syntax errors are only detected during program runtime. </span><br />
<br />
<span>Fype is a recursive acronym and means "Fype is For Your Program Execution" or "Fype is Free Yak Programmed for ELF". You could also say, "It&#39;s not a hype - it&#39;s Fype!".</span><br />
<br />
<h2 style='display: inline'>Object-oriented C style</h2><br />
<br />
<span>The Fype interpreter is written in an object-oriented style of C. Each "main component" has its own .h and .c file. There is a struct type for each (most components at least) component, which can be initialized using a "COMPONENT_new" function and destroyed using a "COMPONENT_delete" function. Method calls follow the same schema, e.g. "COMPONENT_METHODNAME". There is no such as class inheritance and polymorphism involved. </span><br />
<br />
<span>To give you an idea of how it works here as an example is a snippet from the main Fype "class header":</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><b><font color="#0000FF">typedef</font></b> <b><font color="#0000FF">struct</font></b> <font color="#FF0000">{</font>
   <font color="#008080">Tupel</font> <font color="#990000">*</font>p_tupel_argv<font color="#990000">;</font> <i><font color="#9A1900">// Contains command line options</font></i>
   <font color="#008080">List</font> <font color="#990000">*</font>p_list_token<font color="#990000">;</font> <i><font color="#9A1900">// Initial list of token</font></i>
   <font color="#008080">Hash</font> <font color="#990000">*</font>p_hash_syms<font color="#990000">;</font> <i><font color="#9A1900">// Symbol table</font></i>
   <font color="#009900">char</font> <font color="#990000">*</font>c_basename<font color="#990000">;</font>
<font color="#FF0000">}</font> Fype<font color="#990000">;</font>
</pre>
<br />
<span>And here is a snippet from the primary Fype "class implementation":</span><br />
<br />
<!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre>Fype<font color="#990000">*</font>
<b><font color="#000000">fype_new</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
   <font color="#008080">Fype</font> <font color="#990000">*</font>p_fype <font color="#990000">=</font> <b><font color="#000000">malloc</font></b><font color="#990000">(</font><b><font color="#0000FF">sizeof</font></b><font color="#990000">(</font>Fype<font color="#990000">));</font>

   p_fype<font color="#990000">-&gt;</font>p_hash_syms <font color="#990000">=</font> <b><font color="#000000">hash_new</font></b><font color="#990000">(</font><font color="#993399">512</font><font color="#990000">);</font>
   p_fype<font color="#990000">-&gt;</font>p_list_token <font color="#990000">=</font> <b><font color="#000000">list_new</font></b><font color="#990000">();</font>
   p_fype<font color="#990000">-&gt;</font>p_tupel_argv <font color="#990000">=</font> <b><font color="#000000">tupel_new</font></b><font color="#990000">();</font>
   p_fype<font color="#990000">-&gt;</font>c_basename <font color="#990000">=</font> NULL<font color="#990000">;</font>

   <b><font color="#000000">garbage_init</font></b><font color="#990000">();</font>

   <b><font color="#0000FF">return</font></b> <font color="#990000">(</font>p_fype<font color="#990000">);</font>
<font color="#FF0000">}</font>

<font color="#009900">void</font>
<b><font color="#000000">fype_delete</font></b><font color="#990000">(</font><font color="#008080">Fype</font> <font color="#990000">*</font>p_fype<font color="#990000">)</font> <font color="#FF0000">{</font>
   <b><font color="#000000">argv_tupel_delete</font></b><font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>p_tupel_argv<font color="#990000">);</font>

   <b><font color="#000000">hash_iterate</font></b><font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>p_hash_syms<font color="#990000">,</font> symbol_cleanup_hash_syms_cb<font color="#990000">);</font>
   <b><font color="#000000">hash_delete</font></b><font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>p_hash_syms<font color="#990000">);</font>

   <b><font color="#000000">list_iterate</font></b><font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>p_list_token<font color="#990000">,</font> token_ref_down_cb<font color="#990000">);</font>
   <b><font color="#000000">list_delete</font></b><font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>p_list_token<font color="#990000">);</font>

   <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>c_basename<font color="#990000">)</font>
      <b><font color="#000000">free</font></b><font color="#990000">(</font>p_fype<font color="#990000">-&gt;</font>c_basename<font color="#990000">);</font>

   <b><font color="#000000">garbage_destroy</font></b><font color="#990000">();</font>
<font color="#FF0000">}</font>

<font color="#009900">int</font>
<b><font color="#000000">fype_run</font></b><font color="#990000">(</font><font color="#009900">int</font> i_argc<font color="#990000">,</font> <font color="#009900">char</font> <font color="#990000">**</font>pc_argv<font color="#990000">)</font> <font color="#FF0000">{</font>
   <font color="#008080">Fype</font> <font color="#990000">*</font>p_fype <font color="#990000">=</font> <b><font color="#000000">fype_new</font></b><font color="#990000">();</font>

   <i><font color="#9A1900">// argv: Maintains command line options</font></i>
   <b><font color="#000000">argv_run</font></b><font color="#990000">(</font>p_fype<font color="#990000">,</font> i_argc<font color="#990000">,</font> pc_argv<font color="#990000">);</font>

   <i><font color="#9A1900">// scanner: Creates a list of token</font></i>
   <b><font color="#000000">scanner_run</font></b><font color="#990000">(</font>p_fype<font color="#990000">);</font>

   <i><font color="#9A1900">// interpret: Interpret the list of token</font></i>
   <b><font color="#000000">interpret_run</font></b><font color="#990000">(</font>p_fype<font color="#990000">);</font>

   <b><font color="#000000">fype_delete</font></b><font color="#990000">(</font>p_fype<font color="#990000">);</font>

   <b><font color="#0000FF">return</font></b> <font color="#990000">(</font><font color="#993399">0</font><font color="#990000">);</font>
<font color="#FF0000">}</font>
</pre>
<br />
<h2 style='display: inline'>Data types</h2><br />
<br />
<span>Fype uses auto type conversion. However, if you want to know what&#39;s going on, you may take a look at the following basic data types:</span><br />
<ul>
<li>integer - Specifies a number</li>
<li>double - Specifies a double-precision number</li>
<li>string - Specifies a string</li>
<li>number - May be an integer or a double number</li>
<li>any- May be any type above</li>
<li>void - No type</li>
<li>identifier - It&#39;s a variable name or a procedure name, or a function name</li>
</ul><br />
<span>There is no boolean type, but we can use the integer values 0 for false and 1 for true. There is support for explicit type casting too.</span><br />
<br />
<h2 style='display: inline'>Syntax</h2><br />
<br />
<h3 style='display: inline'>Comments</h3><br />
<br />
<span>Text from a # character until the end of the current line is considered being a comment. Multi-line comments may start with an #* and with a *# anywhere. Exceptions are if those signs are inside of strings.</span><br />
<br />
<h3 style='display: inline'>Variables</h3><br />
<br />
<span>Variables are defined with the "my" keyword (inspired by Perl :-). If you don&#39;t assign a value during declaration, it uses the default integer value 0. Variables may be changed during program runtime. Variables may be deleted using the "undef" keyword! Example:</span><br />
<br />
<pre>
my foo = 1 + 2;
say foo; 

my bar = 12, baz = foo;
say 1 + bar;
say bar;

my baz;
say baz; # Will print out 0
</pre>
<br />
<span>You may use the "defined" keyword to check if an identifier has been defined or not:</span><br />
<br />
<pre>
ifnot defined foo {
	say "No foo yet defined";
}

my foo = 1;

if defined foo {
	put "foo is defined and has the value ";
	say foo;
}
</pre>
<br />
<h3 style='display: inline'>Synonyms</h3><br />
<br />
<span>Each variable can have as many synonyms as wished. A synonym is another name to access the content of a specific variable. Here is an example of how to use it:</span><br />
<br />
<pre>
my foo = "foo";
my bar = \foo;
foo = "bar";

# The synonym variable should now also set to "bar"
assert "bar" == bar;
</pre>
<br />
<span>Synonyms can be used for all kind of identifiers. It&#39;s not limited to standard variables but can also be used for function and procedure names (more about functions and procedures later).</span><br />
<br />
<pre>
# Create a new procedure baz
proc baz { say "I am baz"; }

# Make a synonym baz, and undefine baz
my bay = \baz;

undef baz;

# bay still has a reference of the original procedure baz
bay; # this prints aut "I am baz" 
</pre>
<br />
<span>The "syms" keyword gives you the total number of synonyms pointing to a specific value:</span><br />
<br />
<pre>
my foo = 1;
say syms foo; # Prints 1

my baz = \foo; 
say syms foo; # Prints 2
say syms baz; # Prints 2

undef baz;
say syms foo; # Prints 1
</pre>
<br />
<h2 style='display: inline'>Statements and expressions</h2><br />
<br />
<span>A Fype program is a list of statements. Each keyword, expression or function call is part of a statement. Each statement is ended with a semicolon. Example:</span><br />
<br />
<pre>
my bar = 3, foo = 1 + 2; 
say foo;
exit foo - bar;
</pre>
<br />
<h3 style='display: inline'>Parenthesis</h3><br />
<br />
<span>All parenthesis for function arguments is optional. They help to make the code better readable. They also help to force the precedence of expressions.</span><br />
<br />
<h3 style='display: inline'>Basic expressions</h3><br />
<br />
<span>Any "any" value holding a string will be automatically converted to an integer value.</span><br />
<br />
<pre>
(any) &lt;any&gt; + &lt;any&gt;
(any) &lt;any&gt; - &lt;any&gt;
(any) &lt;any&gt; * &lt;any&gt;
(any) &lt;any&gt; / &lt;any&gt;
(integer) &lt;any&gt; == &lt;any&gt;
(integer) &lt;any&gt; != &lt;any&gt;
(integer) &lt;any&gt; &lt;= &lt;any&gt;
(integer) &lt;any&gt; gt &lt;any&gt;
(integer) &lt;any&gt; &lt;&gt; &lt;any&gt;
(integer) &lt;any&gt; gt &lt;any&gt;
(integer) not &lt;any&gt;
</pre>
<br />
<h3 style='display: inline'>Bitwise expressions</h3><br />
<br />
<pre>
(integer) &lt;any&gt; :&lt; &lt;any&gt;
(integer) &lt;any&gt; :&gt; &lt;any&gt;
(integer) &lt;any&gt; and &lt;any&gt;
(integer) &lt;any&gt; or &lt;any&gt;
(integer) &lt;any&gt; xor &lt;any&gt;
</pre>
<br />
<h3 style='display: inline'>Numeric expressions</h3><br />
<br />
<pre>
(number) neg &lt;number&gt;
</pre>
<br />
<span>... returns the negative value of "number":</span><br />
<br />
<pre>
(integer) no &lt;integer&gt;
</pre>
<br />
<span>... returns 1 if the argument is 0; otherwise, it will return 0! If no argument is given, then 0 is returned!</span><br />
<br />
<pre>
(integer) yes &lt;integer&gt;
</pre>
<br />
<span>... always returns 1. The parameter is optional. Example:</span><br />
<br />
<pre>
# Prints out 1, because foo is not defined
if yes { say no defined foo; } 
</pre>
<br />
<h2 style='display: inline'>Control statements</h2><br />
<br />
<span>Control statements available in Fype:</span><br />
<br />
<pre>
if &lt;expression&gt; { &lt;statements&gt; }
</pre>
<br />
<span>... runs the statements if the expression evaluates to a true value.</span><br />
<br />
<pre>
ifnot &lt;expression&gt; { &lt;statements&gt; }
</pre>
<br />
<span>... runs the statements if the expression evaluates to a false value.</span><br />
<br />
<pre>
while &lt;expression&gt; { &lt;statements&gt; }
</pre>
<br />
<span>... runs the statements as long as the expression evaluates to a true value.</span><br />
<br />
<pre>
until &lt;expression&gt; { &lt;statements&gt; }
</pre>
<br />
<span>... runs the statements as long as the expression evaluates to a false value.</span><br />
<br />
<h2 style='display: inline'>Scopes</h2><br />
<br />
<span>A new scope starts with an { and ends with an }. An exception is a procedure, which does not use its own scope (see later in this manual). Control statements and functions support scopes.  The "scope" function prints out all available symbols at the current scope. Here is a small example:</span><br />
<br />
<pre>
my foo = 1;

{
	# Prints out 1
	put defined foo;
	{
		my bar = 2;

		# Prints out 1
		put defined bar;

		# Prints out all available symbols at this
		# point to stdout. Those are: bar and foo
		scope;
	}

	# Prints out 0
	put defined bar;

	my baz = 3;
}

# Prints out 0
say defined bar;
</pre>
<br />
<span>Another example including an actual output:</span><br />
<br />
<pre>
./fype -e ’my global; func foo { my var4; func bar { my var2, var3; func baz { my var1; scope; } baz; } bar; } foo;’
Scopes:
Scope stack size: 3
Global symbols:
SYM_VARIABLE: global (id=00034, line=-0001, pos=-001, type=TT_INTEGER, dval=0.000000, refs=-1)
SYM_FUNCTION: foo
Local symbols:
SYM_VARIABLE: var1 (id=00038, line=-0001, pos=-001, type=TT_INTEGER, dval=0.000000, refs=-1)
1 level(s) up:
SYM_VARIABLE: var2 (id=00036, line=-0001, pos=-001, type=TT_INTEGER, dval=0.000000, refs=-1)
SYM_VARIABLE: var3 (id=00037, line=-0001, pos=-001, type=TT_INTEGER, dval=0.000000, refs=-1)
SYM_FUNCTION: baz
2 level(s) up:
SYM_VARIABLE: var4 (id=00035, line=-0001, pos=-001, type=TT_INTEGER, dval=0.000000, refs=-1)
SYM_FUNCTION: bar
</pre>
<br />
<h2 style='display: inline'>Definedness </h2><br />
<br />
<pre>
(integer) defined &lt;identifier&gt;
</pre>
<br />
<span>... returns 1 if "identifier" has been defined. Returns 0 otherwise.</span><br />
<br />
<pre>
(integer) undef &lt;identifier&gt;
</pre>
<br />
<span>... tries to undefine/delete the "identifier". Returns 1 if it succeeded, otherwise 0 is returned.</span><br />
<br />
<h2 style='display: inline'>System </h2><br />
<br />
<span>These are some system and interpreter specific built-in functions supported:</span><br />
<br />
<pre>
(void) end
</pre>
<br />
<span>... exits the program with the exit status of 0.</span><br />
<br />
<pre>
(void) exit &lt;integer&gt;
</pre>
<br />
<span>... exits the program with the specified exit status.</span><br />
<br />
<pre>
(integer) fork
</pre>
<br />
<span>... forks a subprocess. It returns 0 for the child process and the PID of the child process otherwise! Example:</span><br />
<br />
<pre>
my pid = fork;

if pid {
	put "I am the parent process; child has the pid ";
	say pid;

} ifnot pid {
	say "I am the child process";
}
</pre>
<br />
<span>To execute the garbage collector do:</span><br />
<br />
<pre>
(integer) GC
</pre>
<br />
<span>It returns the number of items freed! You may wonder why most of the time, it will produce a value of 0! Fype tries to free not needed memory ASAP. This may change in future versions to gain faster execution speed!</span><br />
<br />
<h3 style='display: inline'>I/O </h3><br />
<br />
<pre>
(any) put &lt;any&gt;
</pre>
<br />
<span>... prints out the argument</span><br />
<br />
<pre>
(any) say &lt;any&gt;
</pre>
<br />
<span>is the same as put, but also includes an ending newline.</span><br />
<br />
<pre>
(void) ln
</pre>
<br />
<span>... just prints a new line.</span><br />
<br />
<h2 style='display: inline'>Procedures and functions</h2><br />
<br />
<h3 style='display: inline'>Procedures</h3><br />
<br />
<span>A procedure can be defined with the "proc" keyword and deleted with the "undef" keyword. A procedure does not return any value and does not support parameter passing. It&#39;s using already defined variables (e.g. global variables). A procedure does not have its own namespace. It&#39;s using the calling namespace. It is possible to define new variables inside of a procedure in the current namespace.</span><br />
<br />
<pre>
proc foo {
	say 1 + a * 3 + b;
	my c = 6;
}

my a = 2, b = 4;

foo; # Run the procedure. Print out "11\n"
say c; # Print out "6\n";
</pre>
<br />
<h3 style='display: inline'>Nested procedures</h3><br />
<br />
<span>It&#39;s possible to define procedures inside of procedures. Since procedures don&#39;t have their own scope, nested procedures will be available to the current scope as soon as the main procedure has run the first time. You may use the "defined" keyword to check if a procedure has been defined or not.</span><br />
<br />
<pre>
proc foo {
	say "I am foo";

	undef bar;
	proc bar {
		say "I am bar";
	}
}

# Here bar would produce an error because 
# the proc is not yet defined!
# bar; 

foo; # Here the procedure foo will define the procedure bar!
bar; # Now the procedure bar is defined!
foo; # Here the procedure foo will redefine bar again!
</pre>
<br />
<h3 style='display: inline'>Functions</h3><br />
<br />
<span>A function can be defined with the "func" keyword and deleted with the "undef" keyword. Function do not yet return values and do not yet supports parameter passing. It&#39;s using local (lexical scoped) variables. If a certain variable does not exist, when It&#39;s using already defined variables (e.g. one scope above). </span><br />
<br />
<pre>
func foo {
	say 1 + a * 3 + b;
	my c = 6;
}

my a = 2, b = 4;

foo; # Run the procedure. Print out "11\n"
say c; # Will produce an error because c is out of scope!
</pre>
<br />
<h3 style='display: inline'>Nested functions</h3><br />
<br />
<span>Nested functions work the same way the nested procedures work, except that nested functions will not be available anymore after the function has been left!</span><br />
<br />
<pre>
func foo {
	func bar {
		say "Hello i am nested";
	}

	bar; # Calling nested
}

foo;
bar; # Will produce an error because bar is out of scope!
</pre>
<br />
<h2 style='display: inline'>Arrays</h2><br />
<br />
<span>Some progress on arrays has been made too. The following example creates a multidimensional array "foo". Its first element is the return value of the func which is "bar". The fourth value is a string" 3" converted to a double number. The last element is an anonymous array which itself contains another anonymous array as its final element:</span><br />
<br />
<pre>
func bar { say ”bar” }
my foo = [bar, 1, 4/2, double ”3”, [”A”, [”BA”, ”BB”]]];
say foo;
</pre>
<br />
<span>It produces the following output:</span><br />
<br />
<pre>
% ./fype arrays.fy
bar
01
2
3.000000
A
BA
BB
</pre>
<br />
<h2 style='display: inline'>Fancy stuff</h2><br />
<br />
<span>Fancy stuff like OOP or Unicode or threading is not planed. But fancy stuff like function pointers and closures may be considered.:) </span><br />
<br />
<h2 style='display: inline'>May the source be with you</h2><br />
<br />
<span>You can find all of this on the GitHub page. There is also an "examples" folders containing some Fype scripts!</span><br />
<br />
<a class='textlink' href='https://codeberg.org/snonux/fype'>https://codeberg.org/snonux/fype</a><br />
<br />
<span>E-Mail your comments to paul at buetow.org :-)</span><br />
<br />
<a class='textlink' href='../'>Back to the main site</a><br />
            </div>
        </content>
    </entry>
</feed>