<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>devncode</title><description>Every post answers one precise question about infrastructure or code, with the real config, the commands and what broke.</description><link>https://devncode.it/</link><item><title>Why Docker&apos;s published ports bypass your firewall</title><link>https://devncode.it/docker-published-ports-firewall/</link><guid isPermaLink="true">https://devncode.it/docker-published-ports-firewall/</guid><description>Docker&apos;s DNAT sends a published port through FORWARD, never INPUT. On a server that is also the router, that broke the LAN, opened ports, and hid one bug.</description><pubDate>Sat, 17 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The server from &lt;a href=&quot;https://devncode.it/run-homelab-like-production/&quot;&gt;part 1&lt;/a&gt; is also the router of the house. One interface sits on the public internet, the host firewall is nftables, and its &lt;code&gt;input&lt;/code&gt; chain drops everything that is not on a short list. About a hundred containers run next to it, and some of them publish ports. That combination taught me three things about Docker&apos;s firewall rules, the last one while writing this post.&lt;/p&gt;
&lt;h2&gt;Where a published port really goes&lt;/h2&gt;
&lt;p&gt;A published port is not a socket on the host. Docker implements &lt;code&gt;-p 2222:22&lt;/code&gt; with a NAT rule: a packet that arrives for port 2222 has its destination rewritten to the container&apos;s address and port 22, before the kernel decides where it goes. After that rewrite the packet is not for the host anymore, so it is forwarded, and the &lt;code&gt;input&lt;/code&gt; chain, where host firewalls put their rules, never sees it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;WAN, tcp to :2222
  nat PREROUTING   Docker&apos;s DNAT: destination becomes 172.19.0.13:22
  filter FORWARD   DOCKER-USER, then Docker&apos;s own chains, then the container
  filter INPUT     never reached: this is where the host firewall waits
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Docker&apos;s documentation says it plainly about ufw: published ports &lt;a href=&quot;https://docs.docker.com/engine/network/packet-filtering-firewalls/#docker-and-ufw&quot;&gt;bypass its rules entirely&lt;/a&gt;. The same goes for a hand-written nftables &lt;code&gt;input&lt;/code&gt; chain. A stray &lt;code&gt;ports: [&quot;8080:8080&quot;]&lt;/code&gt; in any compose file is open to the internet, and nothing in the firewall rules mentions it.&lt;/p&gt;
&lt;h2&gt;Docker owns the FORWARD chain&lt;/h2&gt;
&lt;p&gt;The first lesson came after a power outage: the server came back up, and we couldn&apos;t browse the internet from the LAN. It took some investigation to find out why.&lt;/p&gt;
&lt;p&gt;When Docker enables IP forwarding, it also sets the policy of the iptables &lt;code&gt;FORWARD&lt;/code&gt; chain to &lt;code&gt;DROP&lt;/code&gt;, and then only accepts what goes to and from its own bridges. On a normal host that is harmless. On a router, forwarding LAN traffic to the internet is the whole job. My nftables &lt;code&gt;forward&lt;/code&gt; chain accepted it, but Docker&apos;s &lt;code&gt;FORWARD&lt;/code&gt; chain hangs from the same point in the kernel, and one chain dropping a packet is enough. The rules I had added by hand to fix it once were gone after the reboot.&lt;/p&gt;
&lt;p&gt;Docker leaves one chain alone, &lt;code&gt;DOCKER-USER&lt;/code&gt;, which it runs before its own rules. A small script fills it with the router&apos;s rules, and a systemd unit runs it after Docker and again every time Docker restarts:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Unit]
Description=Seed DOCKER-USER with LAN/VPN → WAN forwarding rules
After=docker.service
Requires=docker.service
PartOf=docker.service

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/opt/router/docker-forward.sh
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;PartOf=&lt;/code&gt; runs the script again whenever Docker restarts, and here that happens on purpose. The nftables configuration starts with &lt;code&gt;flush ruleset&lt;/code&gt;, which also wipes the tables Docker built, so after a firewall reload the router role restarts Docker to rebuild them, and &lt;code&gt;DOCKER-USER&lt;/code&gt; comes back empty. The script checks each rule with &lt;code&gt;iptables -C&lt;/code&gt; before inserting it, so running it twice changes nothing.&lt;/p&gt;
&lt;h2&gt;Published means public&lt;/h2&gt;
&lt;p&gt;The second lesson came from a periodic port scan of my own public address: a port that a container had published was reachable from the internet, with nothing in the firewall that said so.&lt;/p&gt;
&lt;p&gt;The fix lives in the same chain. Everything new that comes from the WAN is dropped before it reaches a bridge, except an explicit list of ports that are public on purpose: Traefik on 80 and 443, the torrent client, and Forgejo&apos;s SSH. Replies to connections that started inside still pass. Since &lt;code&gt;-I&lt;/code&gt; inserts at the top, the block is written back to front: the &lt;code&gt;DROP&lt;/code&gt; goes in first and ends up last.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ensure_rule -i &quot;$WAN_IF&quot; -j DROP
{% for p in docker_wan_published_tcp | default([80, 443, forgejo_ssh_port | default(2222), 51413]) %}
ensure_rule -i &quot;$WAN_IF&quot; -p tcp -m conntrack --ctorigdstport {{ p }} -j ACCEPT
{% endfor %}
ensure_rule -i &quot;$WAN_IF&quot; -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The ports that are only for the LAN get a second layer in their compose files: they are published on the server&apos;s LAN address, like &lt;code&gt;&quot;{{ server_ip }}:53:53/udp&quot;&lt;/code&gt; for the DNS server, so Docker does not rewrite anything that arrives on the public interface in the first place.&lt;/p&gt;
&lt;h2&gt;The rule that never matched&lt;/h2&gt;
&lt;p&gt;That &lt;code&gt;--ctorigdstport&lt;/code&gt; is new. Until today the rule said &lt;code&gt;--dport&lt;/code&gt;, and preparing this post I looked at the counters of the chain:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;iptables -L DOCKER-USER -n -v --line-numbers
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These are the rules for the public interface:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;num   pkts bytes target     prot opt in     out     source               destination
3    2348M 4290G ACCEPT     all  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
4      22M 1311M ACCEPT     tcp  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:51413
5        0     0 ACCEPT     tcp  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:2222
6     972K   46M ACCEPT     tcp  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443
7     876K   40M ACCEPT     tcp  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80
8      16M 1542M ACCEPT     udp  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0            udp dpt:51413
9    10427  610K DROP       all  --  eno1.835 *       0.0.0.0/0            0.0.0.0/0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zero packets on 2222, in almost a month. The other public ports had no problem because Traefik and the torrent client use the same number outside and inside: 443 is 443 on both sides of the NAT. Forgejo is published as &lt;code&gt;2222:22&lt;/code&gt;, and by the time a packet reaches &lt;code&gt;DOCKER-USER&lt;/code&gt; the DNAT has already happened, so it carries port 22. The rule waited for a 2222 that never came, the packet fell through to the &lt;code&gt;DROP&lt;/code&gt;, and git over SSH had been closed from outside since the day the rule went in.&lt;/p&gt;
&lt;p&gt;Docker&apos;s documentation &lt;a href=&quot;https://docs.docker.com/engine/network/firewall-iptables/#match-the-original-ip-and-ports-for-requests&quot;&gt;describes exactly this&lt;/a&gt;: to match what the client asked for, use the conntrack extension, which remembers the original destination. With &lt;code&gt;-m conntrack --ctorigdstport&lt;/code&gt;, the list in the script means what it says, the ports on the host, whatever the container listens on. The docs warn that conntrack matching may cost some performance. Here it is one rule per public port.&lt;/p&gt;
&lt;h2&gt;How to check yours&lt;/h2&gt;
&lt;p&gt;Three commands tell you where you stand:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;iptables -t nat -S DOCKER
iptables -L DOCKER-USER -n -v
nft list ruleset
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first lists every port Docker forwards and where it goes, which is your real list of open ports. The second shows your own rules with their counters: a rule that should match and stays at zero is lying to you. The third shows the rest of the firewall, but no rule in your &lt;code&gt;input&lt;/code&gt; chain will ever see a published port. And from outside, a port scan of your own address is still the only test that sees what the internet sees.&lt;/p&gt;
</content:encoded></item><item><title>Authelia to authentik behind Traefik, without downtime</title><link>https://devncode.it/authelia-to-authentik-traefik/</link><guid isPermaLink="true">https://devncode.it/authelia-to-authentik-traefik/</guid><description>How I moved about twenty Traefik services and five OIDC apps from Authelia to authentik with both running side by side, and the traps that report success.</description><pubDate>Fri, 16 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I wanted a web interface to manage the users of my homelab, and above all the special cases: &lt;code&gt;user1&lt;/code&gt; should see three services and not the other twenty. In Authelia that is an ordered list of rules in a YAML file. authentik looked like the simplest option with a real interface for it, so in September 2026 I moved.&lt;/p&gt;
&lt;p&gt;Traefik sits in front of about twenty services that have no login of their own, and before it passes a request on, it asks the identity provider who is calling. Five more apps (Forgejo, Mealie, Grimmory, Dockhand and Tessera) have real accounts and log in with OIDC. Authelia did both jobs, configured from the Ansible repo of &lt;a href=&quot;https://devncode.it/ansible-homelab-repo-structure/&quot;&gt;part 2&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Without downtime, here, means that the two ran side by side for one night, and a service moved only after the new path had worked on it.&lt;/p&gt;
&lt;h2&gt;Start authentik next to Authelia, protecting nothing&lt;/h2&gt;
&lt;p&gt;Since &lt;a href=&quot;https://docs.goauthentik.io/releases/2025.10&quot;&gt;release 2025.10&lt;/a&gt; authentik keeps its cache, its tasks and the embedded outpost in PostgreSQL, and Redis is gone. The stack is a server and a worker against the PostgreSQL I already run, and right after the first deploy they used 639 MB together.&lt;/p&gt;
&lt;p&gt;authentik&apos;s own login page has a router with no forward-auth on it, so whatever happened to Authelia, I could always reach authentik.&lt;/p&gt;
&lt;p&gt;Groups, users, providers and applications are YAML blueprints in the repo. Passwords and second factors live only in authentik&apos;s database.&lt;/p&gt;
&lt;h2&gt;Move one harmless service, then the rest&lt;/h2&gt;
&lt;p&gt;For a few hours Traefik had both middlewares, &lt;code&gt;authelia@file&lt;/code&gt; and &lt;code&gt;authentik@file&lt;/code&gt;, and a service moved by changing which one its router mounts. The first was storyscraper, picked because nothing depends on it.&lt;/p&gt;
&lt;p&gt;Forward-auth needs one more route. After the login, authentik sends the browser to &lt;code&gt;https://&amp;lt;service&amp;gt;/outpost.goauthentik.io/callback&lt;/code&gt; to set the cookie on the service&apos;s own host. That request has to land on authentik whatever the host, with a priority high enough to beat each service&apos;s &lt;code&gt;Host()&lt;/code&gt; rule. If the route is missing, you log in fine and then get a 404 on the way back. authentik&apos;s &lt;a href=&quot;https://docs.goauthentik.io/add-secure-apps/providers/proxy/server_traefik&quot;&gt;Traefik example&lt;/a&gt; adds one such router per application; I wrote a single one for every host:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;traefik.http.routers.authentik-outpost.rule: &quot;HostRegexp(`^.+$`) &amp;amp;&amp;amp; PathPrefix(`/outpost.goauthentik.io/`)&quot;
traefik.http.routers.authentik-outpost.priority: &quot;1000&quot;
traefik.http.routers.authentik-outpost.entrypoints: &quot;websecure&quot;
traefik.http.routers.authentik-outpost.service: &quot;authentik&quot;
traefik.http.routers.authentik-outpost.middlewares: &quot;{{ traefik_noauth_middlewares }}&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When the login on storyscraper worked end to end, 21 routers moved in one commit. A search and replace on the templates missed four of them: three used the middleware variable inside a Jinja condition, and one overrode it in its own list entry. grep said the job was done. Traefik&apos;s API, asked for the middlewares of the routers that were really running, found the four.&lt;/p&gt;
&lt;p&gt;Grafana and Paperless went last, because they are the only two that read the user from a header, and authentik&apos;s headers have other names. Moving their middleware without touching their configuration would have kept them up, with no idea who is logged in. Grafana has auto sign-up on, so a wrong header there creates new users instead of failing:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;GF_AUTH_PROXY_ENABLED: &quot;true&quot;
GF_AUTH_PROXY_HEADER_NAME: &quot;Remote-User&quot;
GF_AUTH_PROXY_HEADER_NAME: &quot;X-authentik-username&quot;
GF_AUTH_PROXY_HEADER_PROPERTY: &quot;username&quot;
GF_AUTH_PROXY_AUTO_SIGN_UP: &quot;true&quot;
GF_AUTH_PROXY_HEADERS: &quot;Email:Remote-Email Name:Remote-Name&quot;
GF_AUTH_PROXY_HEADERS: &quot;Email:X-authentik-email Name:X-authentik-name Groups:X-authentik-groups&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Paperless finds its admin by username, so before the deploy I checked that my username in authentik was the same as &lt;code&gt;PAPERLESS_ADMIN_USER&lt;/code&gt;. If the two had differed, Paperless would have created a second, empty account and logged me into that one.&lt;/p&gt;
&lt;p&gt;Between the commit that started authentik and the one that moved the last forward-auth service there are 37 minutes. One service came back later. Lumora, one of my own apps, only looked at &lt;code&gt;Remote-User&lt;/code&gt;. Behind authentik that header never arrived, every API call got a 401, and the frontend showed an empty page instead of an error. Lumora went back to Authelia until a new release of the app read &lt;code&gt;X-authentik-username&lt;/code&gt; first and fell back to &lt;code&gt;Remote-User&lt;/code&gt;. Traefik only overwrites the headers listed in &lt;code&gt;authResponseHeaders&lt;/code&gt;, so a client can still send its own &lt;code&gt;Remote-User&lt;/code&gt; and the app gets it untouched. Lumora&apos;s routers now strip it.&lt;/p&gt;
&lt;h2&gt;One provider per service&lt;/h2&gt;
&lt;p&gt;My first version used a single provider for the whole domain, authentik&apos;s &lt;code&gt;forward_domain&lt;/code&gt; mode, because it is the closest thing to Authelia&apos;s catch-all rule on &lt;code&gt;*.example.com&lt;/code&gt;. For my case it was wrong. authentik&apos;s docs say it directly: domain-level forward auth &quot;&lt;a href=&quot;https://docs.goauthentik.io/add-secure-apps/providers/proxy/&quot;&gt;cannot enforce different application-level authorization rules for each protected application&lt;/a&gt;&quot;. Whoever can log in reaches everything, and &lt;code&gt;user1&lt;/code&gt; was the reason for the migration. I redid it the same evening.&lt;/p&gt;
&lt;p&gt;Now every service has its own provider in &lt;code&gt;forward_single&lt;/code&gt; mode and its own application, generated from one list in the inventory:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  - {slug: seerr, name: &quot;Seerr&quot;, host: &quot;{{ seerr_host }}&quot;, groups: [homelab-admins]}
  - {slug: shelfmark, name: &quot;Shelfmark&quot;, host: &quot;{{ shelfmark_host }}&quot;, groups: [homelab-admins, limited]}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The blueprint turns each entry into a provider, an application, and one policy binding per group:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{% for app in authentik_protected_apps %}
  - model: authentik_providers_proxy.proxyprovider
    id: provider-{{ app.slug }}
    identifiers:
      name: &quot;forward-auth-{{ app.slug }}&quot;
    attrs:
      mode: forward_single
      external_host: &quot;https://{{ app.host }}&quot;
  # ...
{% for group in app.groups %}
  - model: authentik_policies.policybinding
    identifiers:
      target: !KeyOf app-{{ app.slug }}
      order: {{ loop.index0 }}
    attrs:
      group: !Find [authentik_core.group, [name, {{ group }}]]
      enabled: true
{% endfor %}
{% endfor %}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;external_host&lt;/code&gt; has to match the router&apos;s &lt;code&gt;Host()&lt;/code&gt; exactly. In single mode it is how the outpost knows which application a request is for.&lt;/p&gt;
&lt;p&gt;In Authelia the first matching rule won, and &lt;code&gt;user1&lt;/code&gt;&apos;s access was written by exclusion: a policy that denied the &lt;code&gt;limited&lt;/code&gt; group everything except Grimmory. In authentik each application has its own bindings, and they say who gets in. It is easier to read, with one trap: an application with no bindings at all is open to every logged-in user, and nothing in the interface flags it. That is why every entry in the list declares its groups.&lt;/p&gt;
&lt;h2&gt;Blueprints that report success&lt;/h2&gt;
&lt;p&gt;A blueprint with status &lt;code&gt;successful&lt;/code&gt; has not necessarily done anything. That night I found three ways.&lt;/p&gt;
&lt;p&gt;A &lt;code&gt;!Find&lt;/code&gt; inside &lt;code&gt;identifiers&lt;/code&gt; is not resolved. The object is not created, and the blueprint reports success anyway. This is why &lt;code&gt;group&lt;/code&gt; sits in &lt;code&gt;attrs&lt;/code&gt; in the bindings above.&lt;/p&gt;
&lt;p&gt;Files apply in name order, and that order matters. The brand blueprint looked up the recovery flow with a &lt;code&gt;!Find&lt;/code&gt;, the recovery flow was in a file that came later, and the brand ended up without a recovery link, again with no error. The file is now called &lt;code&gt;15-flows-recovery.yaml&lt;/code&gt;. The &lt;a href=&quot;https://docs.goauthentik.io/customize/blueprints/&quot;&gt;blueprint docs&lt;/a&gt; say the order is not guaranteed at all and suggest meta models when blueprints depend on each other.&lt;/p&gt;
&lt;p&gt;An OIDC provider created by a blueprint has no grant types. The UI fills in defaults; a blueprint gets the model&apos;s default, an empty list. Every login failed with &lt;code&gt;Invalid grant_type for provider&lt;/code&gt; in authentik&apos;s log, and the application showed a generic &quot;Invalid credentials&quot;. I spent an hour checking the secret, the redirect URI, the scopes and the bindings before I opened authentik&apos;s log, where the answer was written. The field is now explicit:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;      grant_types:
        - authorization_code
        - refresh_token
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Blueprints were not the only thing that night that said &quot;done&quot; without doing it. An Ansible task in the Forgejo role reported &lt;code&gt;changed&lt;/code&gt; after a delete that had failed, and that one I wrote myself: the delete and the &lt;code&gt;echo&lt;/code&gt; that &lt;code&gt;changed_when&lt;/code&gt; looked for were joined with &lt;code&gt;;&lt;/code&gt; instead of &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;. From that night on, a step counts as done only after a check on the host.&lt;/p&gt;
&lt;h2&gt;The OIDC apps, one at a time&lt;/h2&gt;
&lt;p&gt;The six OIDC providers came up next to Authelia&apos;s and stayed unused until each app was pointed at the new issuer.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Achtung&lt;/strong&gt;
A new issuer means a new &lt;code&gt;sub&lt;/code&gt; claim. An app that stored the old &lt;code&gt;sub&lt;/code&gt; at the first login will not recognise you: it creates a duplicate user, or rejects the login. Look in the app&apos;s database before you move it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;All the providers use &lt;code&gt;sub_mode: user_username&lt;/code&gt;, so &lt;code&gt;sub&lt;/code&gt; carries the username instead of an opaque ID, and most apps find their user again. Tessera did not. It had stored Authelia&apos;s opaque &lt;code&gt;sub&lt;/code&gt; in &lt;code&gt;app_user.subject&lt;/code&gt;, and after the switch every login failed with &quot;Invalid credentials&quot;. One &lt;code&gt;UPDATE&lt;/code&gt; fixed it.&lt;/p&gt;
&lt;p&gt;Forgejo got a second authentication source next to Authelia&apos;s, and as long as both were active I could log in with either. After the first login through authentik, &lt;code&gt;external_login_user&lt;/code&gt; had two rows pointing to the same user. Grimmory worked on the first try by luck: it still stores the old &lt;code&gt;sub&lt;/code&gt; and issuer, but it matches users on &lt;code&gt;preferred_username&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The sixth provider was for Seerr, and I had copied it from Authelia without checking. Seerr has no OIDC at all: its only logins are Plex, Jellyfin and local accounts. I removed the provider.&lt;/p&gt;
&lt;h2&gt;Prove Authelia is unused, then delete it&lt;/h2&gt;
&lt;p&gt;The repo said nothing used Authelia anymore. Before deleting it, I asked Authelia&apos;s own database. The last successful authentication was my login to Grimmory at 02:58, right before it moved, and there is nothing after it. Then I listed every OIDC client that ever received a token:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT client_id, max(requested_at), count(*) FROM oauth2_access_token_session
GROUP BY client_id ORDER BY 2 DESC;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Seerr is not in the result: its client never issued a token in the whole history of the instance. Two other clients belonged to services I had removed from the repo months before, and they were still registered in the IdP. Seerr&apos;s client would have joined them.&lt;/p&gt;
&lt;p&gt;Then the destructive steps, in this order: a full &lt;code&gt;pg_dump&lt;/code&gt; of Authelia&apos;s database and a tarball of its configuration, both in a folder restic backs up; &lt;code&gt;DROP DATABASE&lt;/code&gt;; the ZFS dataset; the eleven keys in the vault. To roll back there is that dump and the role in git history. The TOTP registrations inside the dump can&apos;t be decrypted anymore, because the encryption key was one of the deleted vault keys. That is on purpose: the second factors were set up again on authentik.&lt;/p&gt;
&lt;h2&gt;What came after&lt;/h2&gt;
&lt;p&gt;authentik does not stop brute force out of the box. It keeps a reputation score per login, -1 for a failure and +1 for a success, and nothing uses it until a policy does. The first layer is a fail2ban jail on authentik&apos;s JSON log in journald, where the address field is &lt;code&gt;client_ip&lt;/code&gt; (Authelia&apos;s was &lt;code&gt;remote_ip&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;The second layer is a reputation policy, and its threshold reads backwards: the policy passes when the score is at or below the threshold, that is, when the IP looks bad. Bind it to the login flow as an access check and you get the opposite of what you want. Here it decides whether a deny stage runs. The threshold is -10 and not -5, because the policy has no exception for the LAN, and at -5 five wrong passwords in a row lock you out for a day. It also needs &lt;code&gt;evaluate_on_plan: false&lt;/code&gt;: authentik caches flow plans, and in my test an IP at -15 got through on a plan built while it was still clean.&lt;/p&gt;
&lt;p&gt;The default &lt;code&gt;session_duration&lt;/code&gt; is &lt;code&gt;seconds=0&lt;/code&gt;, and it does not mean &quot;expire now&quot;. It ties the session to the browser&apos;s, so the cookie lives until the browser is closed, and many browsers never are. Sessions now end after seven days, including the one created at the end of a password recovery.&lt;/p&gt;
&lt;p&gt;A month later, I&apos;m happy with authentik. Two services still ask for a second login behind the forward-auth. Seerr has no OIDC and does not read identity headers, so the second login is the only way it can work. Questarr has its own JWT, and I haven&apos;t found OIDC support in it.&lt;/p&gt;
</content:encoded></item><item><title>Rust smart pointers: when to use Box, Rc, Arc and RefCell</title><link>https://devncode.it/rust-smart-pointers/</link><guid isPermaLink="true">https://devncode.it/rust-smart-pointers/</guid><description>Why Rust needs Box, Rc, Arc and RefCell, what each one costs, how they compare with garbage-collected languages, and their strange parts.</description><pubDate>Thu, 15 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In Java or Python you never think about who owns an object. You create it, you pass it around, and the runtime keeps it alive as long as somebody points to it. Rust has no garbage collector, so that question has an answer at compile time, and smart pointers are how you change the answer when the default doesn&apos;t fit.&lt;/p&gt;
&lt;p&gt;This post is for people who know a garbage-collected language and little Rust. The examples are small programs written for this post, and every error and output in it comes from the compiler. Two pieces of real code come from my side projects: &lt;a href=&quot;https://github.com/marcocot/search_engine&quot;&gt;a small search engine&lt;/a&gt; with a B-tree index, and &lt;a href=&quot;https://github.com/marcocot/exploring_crdt&quot;&gt;a CRDT experiment&lt;/a&gt; with a TCP server.&lt;/p&gt;
&lt;h2&gt;One owner, and nothing else keeps a value alive&lt;/h2&gt;
&lt;p&gt;The rule is short. Every value has exactly one owner, a variable or a field. When the owner goes out of scope, the value is dropped, right there, with no collector running later. You can lend the value with a reference, &lt;code&gt;&amp;amp;T&lt;/code&gt; to read or &lt;code&gt;&amp;amp;mut T&lt;/code&gt; to change it, and the compiler checks that no reference outlives the owner, and that nobody reads while somebody else writes.&lt;/p&gt;
&lt;p&gt;In Java, every object variable is a reference to something on the heap, and the garbage collector decides when it dies. CPython counts references on every object and frees it when the count reaches zero, with a separate collector for cycles. Rust does neither by default. Most of the time the one-owner rule is enough, and it costs nothing at runtime. A smart pointer is a type that owns a value and behaves like a reference to it, for the cases where the rule is not enough. You already use two of them: &lt;code&gt;String&lt;/code&gt; and &lt;code&gt;Vec&lt;/code&gt; own their data on the heap and free it when they are dropped.&lt;/p&gt;
&lt;h2&gt;Box: one owner, on the heap&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;Box&amp;lt;T&amp;gt;&lt;/code&gt; is the simplest one, almost banal: it puts a value on the heap and owns it. There is still exactly one owner, the box. What changes is the size of the thing you store: the box itself has a fixed size, whatever is inside it, and that matters in two situations.&lt;/p&gt;
&lt;p&gt;The first is a type that contains itself. Here is a binary tree where a node holds its children directly:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Node {
    value: i32,
    left: Option&amp;lt;Node&amp;gt;,
    right: Option&amp;lt;Node&amp;gt;,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To know the size of a &lt;code&gt;Node&lt;/code&gt;, the compiler needs the size of a &lt;code&gt;Node&lt;/code&gt;. It says so, and it suggests the fix:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;error[E0072]: recursive type `Node` has infinite size
 --&amp;gt; tree.rs:1:1
  |
1 | struct Node {
  | ^^^^^^^^^^^
2 |     value: i32,
3 |     left: Option&amp;lt;Node&amp;gt;,
  |                  ---- recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&amp;amp;`) to break the cycle
  |
3 |     left: Option&amp;lt;Box&amp;lt;Node&amp;gt;&amp;gt;,
  |                  ++++    +
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With &lt;code&gt;Option&amp;lt;Box&amp;lt;Node&amp;gt;&amp;gt;&lt;/code&gt; a node holds a pointer to its children, the size is known, and the tree works. &lt;a href=&quot;https://github.com/marcocot/search_engine/blob/master/src/btree.rs&quot;&gt;My search engine&apos;s B-tree&lt;/a&gt; is built the same way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pub struct BTreeMap&amp;lt;K, V&amp;gt;
where
    K: Ord + Clone,
    V: Clone,
{
    root: Option&amp;lt;Box&amp;lt;Node&amp;lt;K, V&amp;gt;&amp;gt;&amp;gt;,
}

struct Node&amp;lt;K, V&amp;gt;
where
    K: Ord + Clone,
    V: Clone,
{
    keys: Vec&amp;lt;K&amp;gt;,
    values: Vec&amp;lt;V&amp;gt;,
    children: Vec&amp;lt;Box&amp;lt;Node&amp;lt;K, V&amp;gt;&amp;gt;&amp;gt;,
    leaf: bool,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Writing this post, I noticed that two of those boxes don&apos;t do anything. &lt;code&gt;Vec&lt;/code&gt; is already a smart pointer: on the stack it is three words, the pointer, the length and the capacity, and its elements live on the heap. So &lt;code&gt;Vec&amp;lt;Node&amp;gt;&lt;/code&gt; has a known size too, and the compiler accepts it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Node {
    keys: Vec&amp;lt;i32&amp;gt;,
    children: Vec&amp;lt;Node&amp;gt;,
}

fn main() {
    let tree = Node { keys: vec![10], children: vec![Node { keys: vec![1, 5], children: vec![] }] };
    println!(&quot;{} children, size of Node: {} bytes&quot;, tree.children.len(), std::mem::size_of::&amp;lt;Node&amp;gt;());
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;1 children, size of Node: 48 bytes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The extra &lt;code&gt;Box&lt;/code&gt; around each child costs one more allocation and one more pointer to follow on every step down the tree. So &lt;code&gt;Box&lt;/code&gt; is needed where a type would contain itself directly, not wherever there is recursion.&lt;/p&gt;
&lt;h3&gt;Why you write &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The second situation is the one you meet in the first week. A function that reads a file and parses a number can fail in two ways, with two different error types: &lt;code&gt;std::io::Error&lt;/code&gt; and &lt;code&gt;std::num::ParseIntError&lt;/code&gt;. In Java you would write &lt;code&gt;throws Exception&lt;/code&gt; and return either. In Python you just raise. In Rust the return type has to say what comes back.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;dyn Error&lt;/code&gt; means &quot;any type that implements the &lt;code&gt;Error&lt;/code&gt; trait&quot;. The catch is that those types have different sizes, so the compiler cannot reserve space for &quot;any&quot; of them on the stack. Try to return one by value:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use std::error::Error;

fn parse(text: &amp;amp;str) -&amp;gt; Result&amp;lt;u16, dyn Error&amp;gt; {
    Ok(text.parse::&amp;lt;u16&amp;gt;()?)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;error[E0277]: the size for values of type `(dyn std::error::Error + &apos;static)` cannot be known at compilation time
 --&amp;gt; dyn_error_by_value.rs:3:25
  |
3 | fn parse(text: &amp;amp;str) -&amp;gt; Result&amp;lt;u16, dyn Error&amp;gt; {
  |                         ^^^^^^^^^^^^^^^^^^^^^^ doesn&apos;t have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `(dyn std::error::Error + &apos;static)`
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Put it in a box and the size is known again: a &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt; is two pointers, one to the error and one to the table of its methods. The &lt;code&gt;?&lt;/code&gt; operator does the rest. On an error it converts it into the function&apos;s error type with the &lt;code&gt;From&lt;/code&gt; trait, and the standard library implements that conversion from any error into &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use std::error::Error;
use std::fs;

fn read_port(path: &amp;amp;str) -&amp;gt; Result&amp;lt;u16, Box&amp;lt;dyn Error&amp;gt;&amp;gt; {
    let text = fs::read_to_string(path)?; // std::io::Error
    let port = text.trim().parse::&amp;lt;u16&amp;gt;()?; // std::num::ParseIntError
    Ok(port)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With a file containing &lt;code&gt;80800&lt;/code&gt; and then with a missing file, the same function returns two different errors:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;error: number too large to fit in target type
error: No such file or directory (os error 2)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The price is the same as Java&apos;s &lt;code&gt;throws Exception&lt;/code&gt;: the caller no longer knows which error it got without asking. For a &lt;code&gt;main&lt;/code&gt; or a small tool that only prints the error, that&apos;s fine. A library usually defines its own error type instead.&lt;/p&gt;
&lt;h2&gt;Rc: several owners, one thread&lt;/h2&gt;
&lt;p&gt;Sometimes a value has no single owner. Two parts of a program both need the same configuration, and neither outlives the other in a way the compiler can see. &lt;code&gt;Rc&amp;lt;T&amp;gt;&lt;/code&gt;, reference counted, is CPython&apos;s model, opt-in and for one value: &lt;code&gt;Rc::clone&lt;/code&gt; doesn&apos;t copy the data, it adds an owner and increments a counter, and the value is dropped when the last owner goes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use std::rc::Rc;

struct Config {
    name: String,
}

fn main() {
    let config = Rc::new(Config { name: String::from(&quot;prod&quot;) });
    let api = Rc::clone(&amp;amp;config);
    let worker = Rc::clone(&amp;amp;config);
    println!(&quot;{} owners of {}&quot;, Rc::strong_count(&amp;amp;config), worker.name);
    drop(api);
    println!(&quot;{} owners left&quot;, Rc::strong_count(&amp;amp;config));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;3 owners of prod
2 owners left
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Rc&lt;/code&gt; and &lt;code&gt;Arc&lt;/code&gt; were what confused me at first, because they look like they break the one-owner rule. They don&apos;t, really. The &lt;code&gt;Rc&lt;/code&gt; is the owner, and it owns the counter along with the value. What you get from it is shared, read-only access, so the other half of the rules still holds: if several places can see a value, none of them can change it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use std::rc::Rc;

fn main() {
    let names = Rc::new(vec![String::from(&quot;a&quot;)]);
    let other = Rc::clone(&amp;amp;names);
    other.push(String::from(&quot;b&quot;));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;error[E0596]: cannot borrow data in an `Rc` as mutable
 --&amp;gt; rc_mutate.rs:6:5
  |
6 |     other.push(String::from(&quot;b&quot;));
  |     ^^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc&amp;lt;Vec&amp;lt;String&amp;gt;&amp;gt;`
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;RefCell: the borrow check moves to runtime&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;RefCell&amp;lt;T&amp;gt;&lt;/code&gt; is the way out, and the rules don&apos;t go away with it: it checks them while the program runs instead of when it compiles. &lt;code&gt;borrow()&lt;/code&gt; hands out a read borrow, &lt;code&gt;borrow_mut()&lt;/code&gt; a write borrow, and the cell keeps count. &lt;code&gt;Rc&amp;lt;RefCell&amp;lt;T&amp;gt;&amp;gt;&lt;/code&gt; is the usual pair: several owners, and changes through any of them.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let names = Rc::new(RefCell::new(vec![String::from(&quot;a&quot;)]));
    let other = Rc::clone(&amp;amp;names);
    other.borrow_mut().push(String::from(&quot;b&quot;));
    println!(&quot;{:?}&quot;, names.borrow());

    let first = names.borrow_mut();
    let second = names.borrow_mut(); // compiles, panics at runtime
    println!(&quot;{} {}&quot;, first.len(), second.len());
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first half works. The second compiles fine and stops the program, because two writers at once is exactly what the compiler would have refused:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[&quot;a&quot;, &quot;b&quot;]

thread &apos;main&apos; (87) panicked at refcell.rs:11:24:
RefCell already borrowed
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is the cost of &lt;code&gt;RefCell&lt;/code&gt;: a small counter on every borrow, and a mistake that shows up in production instead of in the editor. If you have seen Java throw a &lt;code&gt;ConcurrentModificationException&lt;/code&gt; when a list changes during a loop, it&apos;s the same idea: a check at runtime for something the code should never do.&lt;/p&gt;
&lt;h2&gt;Arc and Mutex: the same, across threads&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;Rc&lt;/code&gt; updates its counter without any synchronization, which is why it&apos;s cheap. Send one to another thread and the compiler stops you:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;error[E0277]: `Rc&amp;lt;i32&amp;gt;` cannot be sent between threads safely
 --&amp;gt; rc_thread.rs:6:32
  |
6 |     let handle = thread::spawn(move || println!(&quot;{counter}&quot;));
  |                  ------------- -------^^^^^^^^^^^^^^^^^^^^^^
  |                  |             |
  |                  |             `Rc&amp;lt;i32&amp;gt;` cannot be sent between threads safely
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Arc&amp;lt;T&amp;gt;&lt;/code&gt; is the atomic version: same idea, a counter updated with atomic instructions, so it&apos;s safe to share between threads and a little more expensive. Like &lt;code&gt;Rc&lt;/code&gt;, it only gives read access. To change the value from several threads you add a lock, &lt;code&gt;Mutex&amp;lt;T&amp;gt;&lt;/code&gt;, and you can only reach the data by taking it. Java&apos;s &lt;code&gt;synchronized&lt;/code&gt; works on the honour system; here, code that forgets the lock doesn&apos;t compile.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/marcocot/exploring_crdt/blob/master/src/network/server.rs&quot;&gt;The CRDT server&lt;/a&gt; keeps the shared state in one &lt;code&gt;Arc&amp;lt;Mutex&amp;lt;…&amp;gt;&amp;gt;&lt;/code&gt;. Each new client gets its own clone of the &lt;code&gt;Arc&lt;/code&gt;, which moves into the task that serves it. The same function returns &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt;, because binding the socket and accepting a connection fail with errors of their own:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pub async fn run(port: u16) -&amp;gt; Result&amp;lt;(), Box&amp;lt;dyn std::error::Error&amp;gt;&amp;gt; {
    let listener = TcpListener::bind(format!(&quot;127.0.0.1:{port}&quot;)).await?;
    println!(&quot;CRDT server listening on 127.0.0.1:{port}&quot;);

    let state = Arc::new(Mutex::new(ServerState {
        next_client_id: 1,
        counter: GCounter::new(),
        rga_ops: Vec::new(),
        clients: HashMap::new(),
    }));

    loop {
        let (socket, addr) = listener.accept().await?;
        println!(&quot;New connection from {addr}&quot;);

        let state = Arc::clone(&amp;amp;state);
        tokio::spawn(async move {
            if let Err(e) = handle_client(socket, state).await {
                eprintln!(&quot;Client error: {e}&quot;);
            }
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Mutex&lt;/code&gt; here is tokio&apos;s, which you lock with &lt;code&gt;.await&lt;/code&gt;: a task waiting for it gives the thread back to the other tasks instead of blocking it.&lt;/p&gt;
&lt;h2&gt;The strange parts&lt;/h2&gt;
&lt;p&gt;A few behaviours surprise everybody once:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;A &lt;code&gt;RefCell&lt;/code&gt; borrow lasts until the end of the scope, not until its last use.&lt;/strong&gt; The compiler is smart about plain references and ends a borrow where you stop using it. A &lt;code&gt;RefCell&lt;/code&gt; borrow is a value, a guard, and it is dropped at the closing brace:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let count = names.borrow().len(); // the guard is dropped at the end of this line
names.borrow_mut().push(format!(&quot;{count}&quot;));

let view = names.borrow(); // this guard lives until the end of main
println!(&quot;first: {}&quot;, view[0]);
names.borrow_mut().push(String::from(&quot;c&quot;)); // view is not used again, still panics
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;thread &apos;main&apos; (113) panicked at guard.rs:11:11:
RefCell already borrowed
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The fix is to keep a borrow inside one expression, or to close it with &lt;code&gt;drop(view)&lt;/code&gt; before borrowing again.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;A &lt;code&gt;Mutex&lt;/code&gt; doesn&apos;t let the same thread lock it twice.&lt;/strong&gt; It is not reentrant: the second &lt;code&gt;lock()&lt;/code&gt; in the thread that already holds it &lt;a href=&quot;https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.lock&quot;&gt;never returns&lt;/a&gt;; it might deadlock or panic. Java&apos;s &lt;code&gt;synchronized&lt;/code&gt; is reentrant, so this one catches people who come from there.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Every &lt;code&gt;lock()&lt;/code&gt; returns a &lt;code&gt;Result&lt;/code&gt;, and that is why you see &lt;code&gt;.lock().unwrap()&lt;/code&gt; everywhere.&lt;/strong&gt; If a thread panics while it holds the lock, the mutex is marked as poisoned, and the next &lt;code&gt;lock()&lt;/code&gt; returns an error instead of the data, because the data might be half-updated. It&apos;s still reachable on purpose: &lt;code&gt;into_inner()&lt;/code&gt; on the error hands it over.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt; cannot cross threads.&lt;/strong&gt; It says nothing about whether the error inside is safe to send, so &lt;code&gt;thread::spawn&lt;/code&gt; refuses it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;error[E0277]: `dyn std::error::Error` cannot be sent between threads safely
 --&amp;gt; error_send.rs:9:18
  |
9 |     let handle = thread::spawn(|| work());
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^ `dyn std::error::Error` cannot be sent between threads safely
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The answer is to promise it in the type, &lt;code&gt;Box&amp;lt;dyn Error + Send + Sync&amp;gt;&lt;/code&gt;. The CRDT server does exactly that for the function that runs inside each spawned task, &lt;code&gt;handle_client&lt;/code&gt;, while &lt;code&gt;run&lt;/code&gt; keeps the plain &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Two &lt;code&gt;Rc&lt;/code&gt; that point to each other are never freed.&lt;/strong&gt; The counters never reach zero, and nothing in Rust comes to collect the cycle the way CPython&apos;s collector would. For the compiler this is still safe: a leak is wasted memory, not a dangling pointer. The tool against it is &lt;code&gt;Weak&amp;lt;T&amp;gt;&lt;/code&gt;, a pointer that doesn&apos;t count as an owner. In a tree the parents own the children with &lt;code&gt;Rc&lt;/code&gt;, and a child points back to its parent with &lt;code&gt;Weak&lt;/code&gt;. &lt;code&gt;upgrade()&lt;/code&gt; gives the parent back if it still exists, and &lt;code&gt;None&lt;/code&gt; once it is gone.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;Rc::clone(&amp;amp;x)&lt;/code&gt; and &lt;code&gt;x.clone()&lt;/code&gt; do the same thing.&lt;/strong&gt; The first form is the convention because it reads as what it is, a counter increment, while &lt;code&gt;.clone()&lt;/code&gt; on other types usually means a deep copy.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Which one, and what it costs&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Type&lt;/th&gt;
&lt;th&gt;Owners&lt;/th&gt;
&lt;th&gt;Threads&lt;/th&gt;
&lt;th&gt;Changes the value&lt;/th&gt;
&lt;th&gt;Rules checked&lt;/th&gt;
&lt;th&gt;Cost&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Box&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;one&lt;/td&gt;
&lt;td&gt;like &lt;code&gt;T&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;yes, through the owner&lt;/td&gt;
&lt;td&gt;at compile time&lt;/td&gt;
&lt;td&gt;one allocation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Rc&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;many&lt;/td&gt;
&lt;td&gt;one&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;at compile time&lt;/td&gt;
&lt;td&gt;a counter update on clone and drop&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Arc&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;many&lt;/td&gt;
&lt;td&gt;many&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;at compile time&lt;/td&gt;
&lt;td&gt;an atomic counter update&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;RefCell&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;n/a&lt;/td&gt;
&lt;td&gt;one&lt;/td&gt;
&lt;td&gt;yes, through a shared reference&lt;/td&gt;
&lt;td&gt;at runtime, it panics&lt;/td&gt;
&lt;td&gt;a borrow counter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Mutex&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;n/a&lt;/td&gt;
&lt;td&gt;many&lt;/td&gt;
&lt;td&gt;yes, while locked&lt;/td&gt;
&lt;td&gt;at runtime, it blocks&lt;/td&gt;
&lt;td&gt;a lock&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Let the compiler tell you&lt;/h2&gt;
&lt;p&gt;You don&apos;t have to pick one in advance. Start with plain ownership and references, and the compiler tells you when that&apos;s not enough, in a few recognisable ways:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;E0072&lt;/code&gt;, a type with infinite size: put a &lt;code&gt;Box&lt;/code&gt; where the type contains itself.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;the size … cannot be known at compilation time&lt;/code&gt; on a &lt;code&gt;dyn Trait&lt;/code&gt;: put it in a &lt;code&gt;Box&lt;/code&gt;, like &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A value that two parts of the program need to own: &lt;code&gt;Rc&lt;/code&gt;, or &lt;code&gt;Arc&lt;/code&gt; if threads are involved.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;E0596&lt;/code&gt;, cannot borrow data in an &lt;code&gt;Rc&lt;/code&gt; as mutable: add &lt;code&gt;RefCell&lt;/code&gt;, or &lt;code&gt;Mutex&lt;/code&gt; for threads.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;E0277&lt;/code&gt;, cannot be sent between threads safely: replace &lt;code&gt;Rc&lt;/code&gt; with &lt;code&gt;Arc&lt;/code&gt;, and &lt;code&gt;Box&amp;lt;dyn Error&amp;gt;&lt;/code&gt; with &lt;code&gt;Box&amp;lt;dyn Error + Send + Sync&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>What the ZFS ARC does with your RAM, and what a cap costs</title><link>https://devncode.it/zfs-arc-max-homelab/</link><guid isPermaLink="true">https://devncode.it/zfs-arc-max-homelab/</guid><description>I ignored the ZFS ARC for three years. It was allowed 97% of my RAM. What it is, why it matters next to containers, and what capping it cost, measured.</description><pubDate>Thu, 15 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;For three and a half years I ran ZFS on my homelab server without ever asking what its cache was allowed to do. When I finally looked, the answer was: almost all of the RAM. This post is what I have learned about the ARC since then, with ten days of data from before and after I capped it.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Achtung&lt;/strong&gt;
If you never set &lt;code&gt;zfs_arc_max&lt;/code&gt;, current OpenZFS on Linux lets the ARC grow to the larger of &quot;all RAM minus 1 GiB&quot; and &quot;5/8 of RAM&quot;. On a box that also runs containers, pick that number yourself.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The machine is small: an i5-6500T with 4 cores, 31 GiB of RAM, and one Samsung 850 EVO that holds the root filesystem, the ZFS pool and the swap. Around seventy containers run on it, each with its own memory limit.&lt;/p&gt;
&lt;p&gt;What made me look was an outage. On September 21 Traefik went from 85 to 371 MB in less than two minutes and hit its container limit of 384 MB, and with the proxy dead every web service was unreachable. That kill came from Traefik&apos;s own cgroup limit; the ARC had nothing to do with it. But it was the afternoon I went through the memory of the whole box, and the ARC was the biggest surprise.&lt;/p&gt;
&lt;h2&gt;What the ARC is&lt;/h2&gt;
&lt;p&gt;The ARC, Adaptive Replacement Cache, is the read cache ZFS keeps in RAM. &quot;Adaptive&quot; because it tracks two kinds of blocks, the ones read recently and the ones read often, and keeps moving the boundary between them depending on which kind pays off.&lt;/p&gt;
&lt;p&gt;Three things about it I did not know:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It lives outside the kernel&apos;s page cache. ZFS manages that memory itself. The kernel can ask for it back under memory pressure, and the ARC then shrinks its target in small steps: by default each step takes off about 0.8% of its size.&lt;/li&gt;
&lt;li&gt;Its default limit is huge. With &lt;code&gt;zfs_arc_max&lt;/code&gt; left at 0, OpenZFS uses the larger of RAM minus 1 GiB and 5/8 of RAM. On my 31 GiB that was an &lt;code&gt;arc_c_max&lt;/code&gt; of 30.24 GiB, 97% of the RAM.&lt;/li&gt;
&lt;li&gt;Lowering the limit at runtime does not shrink it. The man page says it plainly: reducing &lt;code&gt;zfs_arc_max&lt;/code&gt; below the current size &quot;will not cause the ARC to shrink without memory pressure&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Why it matters on this box&lt;/h2&gt;
&lt;p&gt;Seventy containers share 31 GiB, and each has a memory limit that covers its own processes. The ARC is not inside any of those limits. When several containers need memory at the same time, the kernel first has to win it back from a cache that returns it slowly, and until then it swaps, on the same SSD that holds everything else, or kills something.&lt;/p&gt;
&lt;p&gt;Most of the time the ARC was harmless. Its median size was 8.4 GiB. But its peaks reached 15 GiB, and peaks are exactly when the containers need memory too.&lt;/p&gt;
&lt;h2&gt;The cap&lt;/h2&gt;
&lt;p&gt;The limit is a module option, so it survives a reboot. Because changing it at runtime does not shrink the cache, the Ansible role also writes the new value to &lt;code&gt;/sys/module/zfs/parameters/zfs_arc_max&lt;/code&gt;, and the cache gives memory back the next time the kernel asks:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;options zfs zfs_arc_max={{ zfs_arc_max_bytes }}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;zfs_arc_max_bytes&lt;/code&gt; is 8589934592: 8 GiB, just under the old median and about a quarter of the RAM.&lt;/p&gt;
&lt;h2&gt;What the cap changed&lt;/h2&gt;
&lt;p&gt;I compared September 11 to 20 with September 22 to October 1, skipping the day of the change. The numbers come from node-exporter&apos;s ZFS metrics, exported from Prometheus before its 30-day retention dropped them:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;ARC&lt;/th&gt;
&lt;th&gt;Before the cap&lt;/th&gt;
&lt;th&gt;After the cap&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Median size&lt;/td&gt;
&lt;td&gt;8.44 GiB&lt;/td&gt;
&lt;td&gt;8.81 GiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;99th percentile&lt;/td&gt;
&lt;td&gt;13.86 GiB&lt;/td&gt;
&lt;td&gt;10.18 GiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Maximum&lt;/td&gt;
&lt;td&gt;14.99 GiB&lt;/td&gt;
&lt;td&gt;10.96 GiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Hits per second&lt;/td&gt;
&lt;td&gt;21,464&lt;/td&gt;
&lt;td&gt;22,062&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Misses per second&lt;/td&gt;
&lt;td&gt;19.6&lt;/td&gt;
&lt;td&gt;298&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Hit ratio&lt;/td&gt;
&lt;td&gt;99.91%&lt;/td&gt;
&lt;td&gt;98.67%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The cap did what I wanted: the peaks dropped by about 4 GiB, and the typical size did not move.&lt;/p&gt;
&lt;p&gt;It also has a price, and I did not expect it to be this visible. The workload read the same amount, about 22,000 hits a second, but misses went from 20 to almost 300 a second. A hit ratio of 98.67% sounds fine; it means fifteen times more reads going to disk. Reads do not wear an SSD the way writes do, and I did not notice any difference in daily use, so for now I keep the cap.&lt;/p&gt;
&lt;h2&gt;The ARC still goes over its limit&lt;/h2&gt;
&lt;p&gt;This one I have not solved. After the cap, the ARC&apos;s target (&lt;code&gt;arc_c&lt;/code&gt;) stays between 6.3 and 8 GiB, as it should. Its real size does not: it sits above 8 GiB in almost every sample, and peaked at 11 GiB.&lt;/p&gt;
&lt;p&gt;According to the man page the ARC starts evicting as soon as it is 0.2% over its target, and blocks new allocations at 0.6%. Sitting above 8 GiB for days, up to 37% over, is something else. My guess is memory the ARC cannot evict at that moment, such as metadata for files that are open. I have not checked it yet: the next step is a breakdown with &lt;code&gt;arc_summary&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;How I measured&lt;/h2&gt;
&lt;p&gt;Prometheus keeps 30 days, so three weeks after the change I exported every series I needed through its HTTP API (&lt;code&gt;/api/v1/query_range&lt;/code&gt;, one sample every five minutes) into gzipped JSON. A small Python script compares the two windows. Gauges get an average and percentiles. Counters, like hits and misses, get an average rate, and a drop between two samples counts as a counter reset:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def counter_rate(points, period):
    &quot;&quot;&quot;Average per-second increase, skipping counter resets.&quot;&quot;&quot;
    pts = window(points, period)
    total = sum(max(b - a, 0) for (_, a), (_, b) in zip(pts, pts[1:]))
    span = pts[-1][0] - pts[0][0] if len(pts) &amp;gt; 1 else float(&quot;nan&quot;)
    return total / span
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;The rest of that afternoon&lt;/h2&gt;
&lt;p&gt;The ARC was one of ten changes I made on the same day. That was a mistake for the measurement: I wanted an aggressive plan, and I got data that cannot separate most of them. Briefly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;TRIM clearly works. &lt;code&gt;fstrim&lt;/code&gt; never reached the pool, because ZFS does not implement the &lt;code&gt;FITRIM&lt;/code&gt; ioctl it uses, and the SSD had gone untrimmed for three and a half years. With &lt;code&gt;autotrim=on&lt;/code&gt; and a monthly &lt;code&gt;zpool trim&lt;/code&gt;, discards went from 5.5 to 140 GB a day.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;performance&lt;/code&gt; governor raised the average clock from 2.30 to 2.84 GHz. I did not feel it.&lt;/li&gt;
&lt;li&gt;I/O stalls dropped from 5.3% to 3.0% of the time. The scheduler, TRIM, &lt;code&gt;atime&lt;/code&gt; and &lt;code&gt;recordsize&lt;/code&gt; all touch the same disk, so I cannot say which one did it.&lt;/li&gt;
&lt;li&gt;Writes to the SSD stayed at about 280 GB a day: turning off &lt;code&gt;atime&lt;/code&gt; and capping the journal did nothing visible. What writes that much is a question for another post.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Load and swap went up in the same days, for a reason unrelated to this tuning. That is another post too.&lt;/p&gt;
&lt;h2&gt;What I would do differently&lt;/h2&gt;
&lt;p&gt;Next time I change one thing, wait for a few days of data, check it, and only then move to the next. And I will read the defaults of anything that holds on to memory before I run it for three years.&lt;/p&gt;
</content:encoded></item><item><title>Time Machine backups on a Samba share in Docker</title><link>https://devncode.it/time-machine-samba-docker/</link><guid isPermaLink="true">https://devncode.it/time-machine-samba-docker/</guid><description>Samba in Docker as a Time Machine target: getting the Mac to find it, the cap and stalled verification that broke it, and the alerts I run now.</description><pubDate>Wed, 14 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I found out my Time Machine backups were broken right around my upgrade to macOS 27: every attempt was failing. That one is on me. I set the backup up in April, saw the first one complete, and never tested it again.&lt;/p&gt;
&lt;p&gt;My homelab server is also my NAS, so the Mac backs up to it over the LAN. Samba runs in Docker on that server and exports a Time Machine share that lives on a USB disk. This post covers the share, what it took for the Mac to find it, the two faults that stopped it in September, and the alerts I run now.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Achtung&lt;/strong&gt;
&lt;code&gt;fruit:time machine max size&lt;/code&gt; must leave room for a full backup, not only for the next incremental. Mine did not, and the day macOS decided it needed a full copy, the copy never fit.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;The share&lt;/h2&gt;
&lt;p&gt;The image is &lt;code&gt;ghcr.io/servercontainers/samba&lt;/code&gt;. It runs Samba, Avahi and wsdd2 in one container and builds &lt;code&gt;smb.conf&lt;/code&gt; from environment variables. A Time Machine share needs the &lt;code&gt;fruit&lt;/code&gt; VFS module, which speaks Apple&apos;s SMB extensions, stacked with &lt;code&gt;streams_xattr&lt;/code&gt;, plus &lt;code&gt;fruit:time machine = yes&lt;/code&gt; to advertise it as a backup target.&lt;/p&gt;
&lt;p&gt;These are the lines of the compose file that matter for Time Machine:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;services:
  samba:
    image: ghcr.io/servercontainers/samba:latest
    environment:
      MODEL: &quot;TimeCapsule&quot;
      SAMBA_GLOBAL_CONFIG_interfaces: &quot;wan0&quot;
      SAMBA_GLOBAL_CONFIG_bind_SPACE_interfaces_SPACE_only: &quot;yes&quot;
      SAMBA_VOLUME_CONFIG_timemachine: |
        [TimeMachine]
          path = /shares/timemachine
          read only = no
          valid users = {{ samba_user }}
          vfs objects = fruit streams_xattr
          fruit:time machine = yes
          fruit:time machine max size = {{ samba_timemachine_max_size }}
    cap_add:
      - NET_ADMIN
      - NET_RAW
    volumes:
      - &quot;{{ samba_timemachine_path }}:/shares/timemachine&quot;
      - &quot;{{ samba_config_dir }}/avahi-daemon.conf:/etc/avahi/avahi-daemon.conf:ro&quot;
    network_mode: host
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Two details of the image cost me a fix each. Option names with a space are written with &lt;code&gt;_SPACE_&lt;/code&gt;: my first version used double underscores, and the day after I corrected them. And &lt;code&gt;network_mode: host&lt;/code&gt; is not optional: Avahi and wsdd2 announce the share with multicast on the LAN, and from a bridged container nobody hears them. &lt;code&gt;MODEL&lt;/code&gt; is only the model Avahi announces, which decides the icon Finder shows.&lt;/p&gt;
&lt;h2&gt;Making the Mac find it&lt;/h2&gt;
&lt;p&gt;Samba was up on March 30, but the Mac listed the share only on April 18. Three problems, in the order I hit them:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Avahi was off.&lt;/strong&gt; The image disables it when &lt;code&gt;AVAHI_DISABLE&lt;/code&gt; is set, whatever the value. I had the variable in the compose file, so mDNS never started, and without mDNS the share never shows up in Time Machine&apos;s list of disks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The dbus socket.&lt;/strong&gt; To get Avahi running I bind-mounted the host&apos;s &lt;code&gt;/var/run/dbus&lt;/code&gt; into the container. Avahi started, the Mac found the share on April 18, and the first full backup ran that same day. Five days later something else on the host broke: &lt;code&gt;hostnamectl&lt;/code&gt; failed, and so did the Ansible tasks that go through dbus. Sharing that directory had let the container delete the host&apos;s system bus socket.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Docker interfaces.&lt;/strong&gt; With host networking Avahi sees every veth interface Docker creates and removes. Every new container brought a new interface, Avahi reconfigured itself each time, and the announcement on the LAN never settled.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The fix for the last two is a small &lt;code&gt;avahi-daemon.conf&lt;/code&gt;, mounted over the image&apos;s own:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[server]
use-ipv4=yes
use-ipv6=yes
allow-interfaces={{ router_lan_nic | default(&apos;wan0&apos;) }}
enable-dbus=no
ratelimit-interval-usec=1000000
ratelimit-burst=1000

[publish]
publish-hinfo=no
publish-workstation=no
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;allow-interfaces&lt;/code&gt; pins Avahi to the LAN interface, &lt;code&gt;enable-dbus=no&lt;/code&gt; lets it run without the host&apos;s dbus. The two capabilities in the compose file belong to wsdd2, the Windows discovery daemon: without &lt;code&gt;NET_ADMIN&lt;/code&gt; and &lt;code&gt;NET_RAW&lt;/code&gt; it cannot set up its multicast sockets.&lt;/p&gt;
&lt;h2&gt;What broke in September&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Date&lt;/th&gt;
&lt;th&gt;What happened&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;2026-04-18&lt;/td&gt;
&lt;td&gt;First full backup. macOS verifies the new bundle.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;April to September&lt;/td&gt;
&lt;td&gt;Hourly incrementals succeed.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2026-09-14, 04:03 UTC&lt;/td&gt;
&lt;td&gt;Last successful backup.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2026-09-15&lt;/td&gt;
&lt;td&gt;I notice that every backup fails.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;code&gt;backupd&lt;/code&gt; stayed in &lt;code&gt;PreparingSourceVolumes&lt;/code&gt;: no CPU use, nothing in the logs. Two separate problems were behind it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The verification came due.&lt;/strong&gt; macOS re-verifies network backups now and then. The last verification of my bundle dated from April 18, almost five months earlier, and the bundle held 720G of history. Running that check over SMB, on a USB disk with shingled (SMR) recording, never finished, and no backup could start until it did.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The full copy did not fit.&lt;/strong&gt; The bundle held 720 GiB and the cap was 1 TiB, which left the Mac about 326 GB of free space (macOS counts in decimal units). The full copy &lt;code&gt;backupd&lt;/code&gt; had planned was 413 GB. Instead of copying, it kept deleting old snapshots to make room, at about 700 KB/s on that disk, and the copy never started.&lt;/p&gt;
&lt;p&gt;One wrong turn is worth telling. When I wrote the monitoring, I first read &lt;code&gt;VerificationState = 1&lt;/code&gt; in the bundle&apos;s &lt;code&gt;MachineID.plist&lt;/code&gt; as &quot;this bundle is damaged&quot; and planned to alert on it. Then the collector ran on the real share, and the bundle created that morning reported &lt;code&gt;1&lt;/code&gt; too. What separates a healthy bundle from mine is the date of the last verification, not the flag. The check on the empty replacement bundle finished in 25 seconds. So the old bundle was intact. At 720G, verifying it over SMB on this disk never finished.&lt;/p&gt;
&lt;h2&gt;Raising the cap&lt;/h2&gt;
&lt;p&gt;The cap does not live in the bundle. Samba uses it to report a smaller disk to the Mac (the &lt;code&gt;vfs_fruit&lt;/code&gt; man page says it &quot;limits the reported disksize&quot;), so changing it needs no work on the bundle: the Mac reads the new size the next time it mounts the share.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;samba_timemachine_max_size: 1T
samba_timemachine_max_size: 2T
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I stopped at 2T because of the disk: it had 1.9T free with the bundle already taking 720G, so 2T is a cap the disk can actually honour. The man page also warns that the cap is an estimate built from the bundle&apos;s band files only. Anything else stored on the same disk is invisible to it, so keep the cap below the space the disk really has.&lt;/p&gt;
&lt;p&gt;I deleted the old bundle and let the Mac start a new one.&lt;/p&gt;
&lt;h2&gt;Alerts that would have caught it&lt;/h2&gt;
&lt;p&gt;Everything else on the server had monitoring. The Time Machine share had none. Now a systemd timer runs a Python collector every five minutes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Unit]
Description=Refresh Time Machine backup metrics every 5 minutes

[Timer]
OnBootSec=2min
OnUnitActiveSec=5min
AccuracySec=30s

[Install]
WantedBy=timers.target
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The collector reads the plists inside each sparsebundle and writes a file for node-exporter&apos;s textfile collector. The completion dates of the snapshots sit at different key paths depending on the macOS release, so it walks the whole plist instead of trusting one path:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def collect_dates(node, out):
    if isinstance(node, dict):
        for key, value in node.items():
            if key.endswith(&quot;SnapshotCompletionDate&quot;) and hasattr(value, &quot;timestamp&quot;):
                out.append(value.timestamp())
            else:
                collect_dates(value, out)
    elif isinstance(node, list):
        for item in node:
            collect_dates(item, out)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The bundle size comes from &lt;code&gt;st_blocks&lt;/code&gt;, not &lt;code&gt;st_size&lt;/code&gt;: band files are sparse, and their size would overcount.&lt;/p&gt;
&lt;p&gt;One trap in this script. Ansible renders it through Jinja before copying it to the server, to fill in the share path and the cap. Two opening braces in a row, anywhere in the file and even in a comment, start a Jinja expression and break the deploy, and doubled braces are what &lt;code&gt;str.format&lt;/code&gt; uses to print a literal brace. The script sticks to &lt;code&gt;%&lt;/code&gt;-formatting, and a test rejects any &lt;code&gt;{{&lt;/code&gt; other than the variables Ansible is meant to fill.&lt;/p&gt;
&lt;p&gt;Grafana turns the metrics into six alerts, each aimed at one of the ways this went wrong. They started as Prometheus rules, and those never reached anyone, as &lt;a href=&quot;https://devncode.it/homelab-monitoring-prometheus-loki-grafana/&quot;&gt;part 4&lt;/a&gt; explains:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Alert&lt;/th&gt;
&lt;th&gt;Fires when&lt;/th&gt;
&lt;th&gt;What it would have caught&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Time Machine Backup Missed&lt;/td&gt;
&lt;td&gt;no completed snapshot for 48 hours&lt;/td&gt;
&lt;td&gt;the September outage, without me finding it by hand&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Time Machine Never Completed&lt;/td&gt;
&lt;td&gt;a bundle holds no snapshot for 24 hours&lt;/td&gt;
&lt;td&gt;a first backup that never finishes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Time Machine Verification Overdue&lt;/td&gt;
&lt;td&gt;the last verification is older than 90 days&lt;/td&gt;
&lt;td&gt;the real cause, about two months before it stalled anything&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Time Machine Bundle Near Cap&lt;/td&gt;
&lt;td&gt;the bundle passes 70% of the cap&lt;/td&gt;
&lt;td&gt;the 720G-of-1T situation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Time Machine No Bundle&lt;/td&gt;
&lt;td&gt;the share holds no bundle at all&lt;/td&gt;
&lt;td&gt;an empty share&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Time Machine Metrics Stale&lt;/td&gt;
&lt;td&gt;the collector&apos;s last run is over 30 minutes old, for another 30 minutes&lt;/td&gt;
&lt;td&gt;a collector that stopped, leaving numbers that look fine forever&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The last one matters more than it looks. The collector replaces its file atomically, and node-exporter keeps serving the last file it finds, so a stopped timer makes nothing disappear: the numbers freeze. The rules built on &lt;code&gt;time()&lt;/code&gt; still fire on a frozen timestamp, but a frozen size or snapshot count looks healthy forever. The freshness check catches that case, and &lt;code&gt;noDataState: Alerting&lt;/code&gt; makes it fire for a file that was never written too:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;      - uid: timemachine-metrics-stale
        title: Time Machine Metrics Stale
        condition: C
        noDataState: Alerting
        execErrState: OK
        data:
          - refId: A
            relativeTimeRange: { from: 300, to: 0 }
            datasourceUid: prometheus
            model:
              expr: &quot;time() - timemachine_collector_last_run_timestamp_seconds&quot;
              instant: true
              refId: A
          - refId: C
            relativeTimeRange: { from: 300, to: 0 }
            datasourceUid: __expr__
            model:
              type: threshold
              expression: A
              conditions:
                - evaluator: { type: gt, params: [1800] }
              refId: C
        for: 30m
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;The test I skipped in April&lt;/h2&gt;
&lt;p&gt;I recently formatted the Mac and restored it from this share, and it went smoothly. That restore is the test I should have run in April, right after the first backup completed. The alerts tell me when backups stop. Only a restore tells me they are usable.&lt;/p&gt;
</content:encoded></item><item><title>Monitoring a homelab with Prometheus, Loki and Grafana</title><link>https://devncode.it/homelab-monitoring-prometheus-loki-grafana/</link><guid isPermaLink="true">https://devncode.it/homelab-monitoring-prometheus-loki-grafana/</guid><description>Metrics in Prometheus, logs from the systemd journal into Loki, a Grafana dashboard per service, and alerts on Telegram that stay few enough to read.</description><pubDate>Tue, 13 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The monitoring runs on the same server it watches, and like everything else since &lt;a href=&quot;https://devncode.it/ansible-homelab-repo-structure/&quot;&gt;part 2&lt;/a&gt;, it lives in the repo: the exporters, the dashboards as JSON, the alert rules, the Telegram contact point. Prometheus collects numbers, Loki collects logs, and Grafana shows both and decides when to write to me.&lt;/p&gt;
&lt;p&gt;&amp;lt;figure style=&quot;margin:2rem 0&quot;&amp;gt;
&amp;lt;svg viewBox=&quot;0 0 440 436&quot; role=&quot;img&quot; aria-labelledby=&quot;hlm-title hlm-desc&quot; style=&quot;display:block;width:100%;max-width:440px;height:auto;margin:0 auto;font-family:var(--font-sans)&quot;&amp;gt;
&amp;lt;title id=&quot;hlm-title&quot;&amp;gt;Metrics, logs, dashboards and alerts&amp;lt;/title&amp;gt;
&amp;lt;desc id=&quot;hlm-desc&quot;&amp;gt;On the left, exporters and the files written by host jobs feed Prometheus, which scrapes every 30 seconds and keeps 30 days. On the right, the systemd journal holds host and container logs; Alloy ships them to Loki, which keeps 30 days. Grafana reads both, for dashboards and alert rules, and sends the alerts to Telegram.&amp;lt;/desc&amp;gt;
&amp;lt;defs&amp;gt;&amp;lt;marker id=&quot;hlm-arrow&quot; viewBox=&quot;0 0 8 8&quot; refX=&quot;7&quot; refY=&quot;4&quot; markerWidth=&quot;7&quot; markerHeight=&quot;7&quot; orient=&quot;auto&quot;&amp;gt;&amp;lt;path d=&quot;M0,0 L8,4 L0,8 z&quot; style=&quot;fill:var(--muted)&quot;/&amp;gt;&amp;lt;/marker&amp;gt;&amp;lt;/defs&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--muted);font-size:13px;letter-spacing:0.04em&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;22&quot;&amp;gt;METRICS&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;22&quot;&amp;gt;LOGS&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g style=&quot;fill:var(--code-bg);stroke:var(--rule);stroke-width:1&quot;&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;36&quot; width=&quot;190&quot; height=&quot;80&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;36&quot; width=&quot;190&quot; height=&quot;80&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;150&quot; width=&quot;190&quot; height=&quot;60&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;150&quot; width=&quot;190&quot; height=&quot;60&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;130&quot; y=&quot;360&quot; width=&quot;180&quot; height=&quot;60&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;250&quot; width=&quot;400&quot; height=&quot;70&quot; rx=&quot;6&quot; style=&quot;fill:var(--code-bg);stroke:var(--accent);stroke-width:1.5&quot;/&amp;gt;
&amp;lt;g style=&quot;stroke:var(--muted);stroke-width:1.5;fill:none&quot;&amp;gt;
&amp;lt;line x1=&quot;115&quot; y1=&quot;116&quot; x2=&quot;115&quot; y2=&quot;148&quot; marker-end=&quot;url(#hlm-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;116&quot; x2=&quot;325&quot; y2=&quot;148&quot; marker-end=&quot;url(#hlm-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;115&quot; y1=&quot;210&quot; x2=&quot;115&quot; y2=&quot;248&quot; marker-end=&quot;url(#hlm-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;210&quot; x2=&quot;325&quot; y2=&quot;248&quot; marker-end=&quot;url(#hlm-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;220&quot; y1=&quot;320&quot; x2=&quot;220&quot; y2=&quot;358&quot; marker-end=&quot;url(#hlm-arrow)&quot;/&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--fg);font-size:15px;font-weight:600&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;60&quot;&amp;gt;Exporters&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;60&quot;&amp;gt;systemd journal&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;176&quot;&amp;gt;Prometheus&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;176&quot;&amp;gt;Alloy → Loki&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;276&quot;&amp;gt;Grafana&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;386&quot;&amp;gt;Telegram&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--muted);font-size:13px&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;82&quot;&amp;gt;host, containers, disks,&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;102&quot;&amp;gt;pings, our apps, .prom files&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;82&quot;&amp;gt;host logs, and container&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;102&quot;&amp;gt;logs via the log driver&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;198&quot;&amp;gt;every 30 s, 30 days&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;198&quot;&amp;gt;30 days&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;298&quot;&amp;gt;a dashboard per service&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;314&quot;&amp;gt;alert rules, thresholds on the panels&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;408&quot;&amp;gt;grouped, repeated every 12 h&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;/svg&amp;gt;
&amp;lt;/figure&amp;gt;&lt;/p&gt;
&lt;h2&gt;Metrics: everything ends up in Prometheus&lt;/h2&gt;
&lt;p&gt;Prometheus scrapes every 30 seconds and keeps 30 days. Most of what it reads comes from the usual exporters: node-exporter for the host, cAdvisor for the containers, smartctl-exporter for the disks, a blackbox exporter that pings the gateway and two public DNS servers, the PostgreSQL exporter. Our own apps expose their own &lt;code&gt;/metrics&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The cheapest part is a feature of node-exporter, the textfile collector: it publishes whatever it finds in &lt;code&gt;.prom&lt;/code&gt; files in one directory. So every job on the host (the backup, its weekly check, the monthly restore drill, the Time Machine check, the UPS, the router) ends by writing a few lines like these:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;backup_last_run_timestamp_seconds{repo=&quot;s3&quot;} 1792027558
backup_last_run_success{repo=&quot;s3&quot;} 1
backup_last_run_duration_seconds{repo=&quot;s3&quot;} 291
backup_repository_size_bytes{repo=&quot;s3&quot;} 30305935097
backup_snapshot_count{repo=&quot;s3&quot;} 30
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A shell script that writes five lines is now a time series, with a dashboard and an alert, and no extra service to run.&lt;/p&gt;
&lt;h2&gt;Logs: the journal, then Loki&lt;/h2&gt;
&lt;p&gt;Docker&apos;s log driver is &lt;code&gt;journald&lt;/code&gt;, so every container writes into the systemd journal, next to the host&apos;s own logs, with the container&apos;s name attached. Grafana Alloy reads the journal and ships everything to Loki, which keeps 30 days. Container lines get a &lt;code&gt;container&lt;/code&gt; label, host lines get the systemd unit.&lt;/p&gt;
&lt;p&gt;Before, Alloy asked the Docker API for the container logs. dockerd answered by reading the journal itself, once for each of the hundred or so containers, and woke every one of those readers up for each new line. It cost dockerd 14.1 seconds of CPU per minute, against 2.6 after the change, and Loki got every container line twice. On a 4-core box that is not a detail, as &lt;a href=&quot;https://devncode.it/homelab-deploy-forgejo-semaphore/&quot;&gt;part 3&lt;/a&gt; showed for the CI.&lt;/p&gt;
&lt;p&gt;Logs can raise alerts too. A few rules query Loki instead of Prometheus, like this one for the API behind TreniTardi, which counts the lines with a Python traceback or an error level in the last ten minutes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;sum(count_over_time({container=~&quot;trenitardi-api.*&quot;} |~ &quot;(?i)(traceback|\&quot;level\&quot;: \&quot;(error|critical)\&quot;)&quot; [10m]))
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;A dashboard for every service&lt;/h2&gt;
&lt;p&gt;Every service gets a Grafana dashboard, and the JSON lives in the repo next to everything else. I look at Grafana often, and I admit that nice dashboards are a bit of a fetish. This is part of the one for the internet connection, with the speed tests, the WAN and DHCP status, and the connection tracking table that made the server the router in &lt;a href=&quot;https://devncode.it/run-homelab-like-production/&quot;&gt;part 1&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://devncode.it/assets/posts/grafana-internet-dashboard.png&quot; alt=&quot;The Internet Speed dashboard in Grafana: average download 935 Mbps and upload 830 Mbps over 24 hours, ping 7.25 ms, WAN and DHCP up, 14 DHCP leases, and 4,362 connection tracking entries out of 262,144, 1.66% used.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;When a panel shows a metric that has an alert, the panel draws the alert&apos;s threshold as a line, the same value that sends the message.&lt;/p&gt;
&lt;h2&gt;Alerts: Grafana writes to Telegram&lt;/h2&gt;
&lt;p&gt;The alert rules are in the repo too, in one file, and Grafana evaluates them. Each one is a query and a threshold. Telegram receives them because it is convenient: we never looked at the alternatives, maybe one day we will.&lt;/p&gt;
&lt;p&gt;Until recently there was a second set of rules in Prometheus. Prometheus had no Alertmanager, so those rules were evaluated and their alerts never reached anyone, including the Time Machine ones from &lt;a href=&quot;https://devncode.it/time-machine-samba-docker/&quot;&gt;part 5&lt;/a&gt;. The ones worth keeping moved to Grafana, duplicates and noise were deleted, and now alerts live in one place.&lt;/p&gt;
&lt;p&gt;The notification policy decides how much Telegram I get. Alerts are grouped by folder and name, and a firing alert repeats every 12 hours. One alert depends on a data feed that goes stale on its own several times a week, so it has its own route: no &quot;resolved&quot; message, and one reminder a day:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;policies:
  - orgId: 1
    receiver: telegram
    group_by:
      - grafana_folder
      - alertname
    group_wait: 30s
    group_interval: 5m
    repeat_interval: 12h
    routes:
      - receiver: telegram-no-resolve
        object_matchers:
          - [&quot;alertname&quot;, &quot;=&quot;, &quot;TreniTardi Italo Real Time Stale&quot;]
        repeat_interval: 24h
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the 30 days before I wrote this, Grafana raised 55 alerts, about two a day. The ones that made me act were about hardware: a disk running out of space, and the SMART alerts. For bad sectors the rule watches the growth, not the total: the backup disk has carried the same count of reallocated sectors for at least a month, and an alert on the total would fire forever.&lt;/p&gt;
&lt;p&gt;A collector that stops writing is a failure too: the Time Machine rule treats missing data as an alert, so a dead check cannot look like a healthy one. A few rules run every minute instead of every five, because a memory burst like the one that killed Traefik is over before a slower rule looks again.&lt;/p&gt;
&lt;h2&gt;What I would add&lt;/h2&gt;
&lt;p&gt;Nothing, for now. I&apos;m happy with it. Time Machine in &lt;a href=&quot;https://devncode.it/time-machine-samba-docker/&quot;&gt;part 5&lt;/a&gt; is the whole loop on one service: the metrics a script writes, the dashboard, and the alerts that come from it.&lt;/p&gt;
</content:encoded></item><item><title>Homelab deploys with Forgejo Actions and Semaphore</title><link>https://devncode.it/homelab-deploy-forgejo-semaphore/</link><guid isPermaLink="true">https://devncode.it/homelab-deploy-forgejo-semaphore/</guid><description>The base infrastructure deploys from my laptop, one Ansible tag at a time. Our own apps deploy from a git tag through Forgejo Actions and Semaphore.</description><pubDate>Mon, 12 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The repo from &lt;a href=&quot;https://devncode.it/ansible-homelab-repo-structure/&quot;&gt;part 2&lt;/a&gt; has two kinds of things to deploy. The infrastructure: Traefik, Plex, the databases, the monitoring, everything the house runs on. And the apps we write ourselves, like the backend of &lt;a href=&quot;https://apps.apple.com/it/app/trenitardi-treni-in-ritardo/id6816269238&quot;&gt;TreniTardi&lt;/a&gt;, a free iPhone app that tells you how late your regional train will be before it leaves. They take two different roads to the server, on purpose.&lt;/p&gt;
&lt;p&gt;&amp;lt;figure style=&quot;margin:2rem 0&quot;&amp;gt;
&amp;lt;svg viewBox=&quot;0 0 440 476&quot; role=&quot;img&quot; aria-labelledby=&quot;hld-title hld-desc&quot; style=&quot;display:block;width:100%;max-width:440px;height:auto;margin:0 auto;font-family:var(--font-sans)&quot;&amp;gt;
&amp;lt;title id=&quot;hld-title&quot;&amp;gt;Two deploy paths to one server&amp;lt;/title&amp;gt;
&amp;lt;desc id=&quot;hld-desc&quot;&amp;gt;On the left, the infrastructure: from the laptop, a dry run and then a deploy of one Ansible tag, followed by a check script. On the right, our apps: a git tag starts Forgejo Actions, which tests, builds the image, makes a release and calls a Semaphore webhook; Semaphore runs the app&apos;s Ansible role on the server.&amp;lt;/desc&amp;gt;
&amp;lt;defs&amp;gt;&amp;lt;marker id=&quot;hld-arrow&quot; viewBox=&quot;0 0 8 8&quot; refX=&quot;7&quot; refY=&quot;4&quot; markerWidth=&quot;7&quot; markerHeight=&quot;7&quot; orient=&quot;auto&quot;&amp;gt;&amp;lt;path d=&quot;M0,0 L8,4 L0,8 z&quot; style=&quot;fill:var(--muted)&quot;/&amp;gt;&amp;lt;/marker&amp;gt;&amp;lt;/defs&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--muted);font-size:13px;letter-spacing:0.04em&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;22&quot;&amp;gt;INFRASTRUCTURE&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;22&quot;&amp;gt;OUR APPS&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g style=&quot;fill:var(--code-bg);stroke:var(--rule);stroke-width:1&quot;&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;36&quot; width=&quot;190&quot; height=&quot;80&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;36&quot; width=&quot;190&quot; height=&quot;56&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;122&quot; width=&quot;190&quot; height=&quot;76&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;228&quot; width=&quot;190&quot; height=&quot;56&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;404&quot; width=&quot;190&quot; height=&quot;56&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;314&quot; width=&quot;400&quot; height=&quot;60&quot; rx=&quot;6&quot; style=&quot;fill:var(--code-bg);stroke:var(--accent);stroke-width:1.5&quot;/&amp;gt;
&amp;lt;g style=&quot;stroke:var(--muted);stroke-width:1.5;fill:none&quot;&amp;gt;
&amp;lt;line x1=&quot;115&quot; y1=&quot;116&quot; x2=&quot;115&quot; y2=&quot;312&quot; marker-end=&quot;url(#hld-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;92&quot; x2=&quot;325&quot; y2=&quot;120&quot; marker-end=&quot;url(#hld-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;198&quot; x2=&quot;325&quot; y2=&quot;226&quot; marker-end=&quot;url(#hld-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;284&quot; x2=&quot;325&quot; y2=&quot;312&quot; marker-end=&quot;url(#hld-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;115&quot; y1=&quot;374&quot; x2=&quot;115&quot; y2=&quot;402&quot; marker-end=&quot;url(#hld-arrow)&quot;/&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--fg);font-size:15px;font-weight:600&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;62&quot;&amp;gt;Laptop&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;60&quot;&amp;gt;git tag&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;146&quot;&amp;gt;Forgejo Actions&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;252&quot;&amp;gt;Semaphore&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;338&quot;&amp;gt;Server&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;428&quot;&amp;gt;deploy-verify.sh&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--muted);font-size:13px&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;84&quot;&amp;gt;make deploy-check&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;104&quot;&amp;gt;make deploy-tags&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;80&quot;&amp;gt;pushed to Forgejo&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;168&quot;&amp;gt;test, build the image&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;188&quot;&amp;gt;release, call the webhook&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;272&quot;&amp;gt;runs the app&apos;s role&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;360&quot;&amp;gt;ansible-playbook --tags &amp;lt;role&amp;gt;&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;448&quot;&amp;gt;status, HTTP, logs&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;/svg&amp;gt;
&amp;lt;/figure&amp;gt;&lt;/p&gt;
&lt;h2&gt;The infrastructure: by hand, one tag at a time&lt;/h2&gt;
&lt;p&gt;For now we prefer to deploy the base infrastructure by hand, from the laptop. Nothing in the infrastructure deploys itself: a push to the repo only runs the checks on Forgejo Actions, yamllint, ansible-lint and the offline tests, and stops there.&lt;/p&gt;
&lt;p&gt;A deploy is three commands. The dry run first, when the change is risky: &lt;code&gt;--check --diff&lt;/code&gt; shows what Ansible would change, file by file, without changing it. Then the deploy of one role through its tag, as in part 2. Then the check:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;make deploy-check
make deploy-tags TAGS=plex
scripts/deploy-verify.sh plex
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;deploy-verify.sh&lt;/code&gt; asks the server three things. Are the containers running? Does the service answer over its real domain, with a 200, 302 or 401, and not a 500, a 502 or a refused connection? Did any container log an error in the last five minutes?&lt;/p&gt;
&lt;h2&gt;Our apps: a git tag is a deploy&lt;/h2&gt;
&lt;p&gt;The apps live in their own repos, and pushing a tag is the whole release. One workflow on Forgejo Actions runs in steps, and each one starts only if the previous one passed: the tests, the build of the image and its push to Forgejo&apos;s own registry, the release with the changelog, and the deploy. The deploy step is just a call to Semaphore:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  deploy:
    name: Deploy via Semaphore
    needs: publish
    runs-on: ubuntu-latest
    container:
      image: docker:cli
    steps:
      - name: Trigger Semaphore deploy
        run: |
          apk add --no-cache curl
          curl -fsS -X POST &quot;${{ secrets.SEMAPHORE_WEBHOOK_URL }}&quot; \
            -H &quot;X-Semaphore-Token: ${{ secrets.SEMAPHORE_WEBHOOK_TOKEN }}&quot; \
            -H &quot;Content-Type: application/json&quot; \
            -d &quot;{\&quot;ref\&quot;:\&quot;${{ github.ref }}\&quot;}&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://semaphoreui.com/&quot;&gt;Semaphore&lt;/a&gt; is a web UI that runs Ansible. It lives on the same server, and it has one template per app: the same playbook as the laptop, limited to that app&apos;s tag. Its own Ansible role deploys it, together with an encrypted copy of the vault and the password to open it, so a webhook deploy runs the same playbook and the same role that &lt;code&gt;make deploy-tags&lt;/code&gt; runs from the laptop.&lt;/p&gt;
&lt;p&gt;It fits our infrastructure well, but I&apos;m not convinced by it. For our case it may be overkill, and the infrastructure doesn&apos;t use it at all.&lt;/p&gt;
&lt;h2&gt;The CI runs on the server it deploys to&lt;/h2&gt;
&lt;p&gt;Forgejo and its Actions runner live on the same 4-core machine as everything else. Every CI job is a handful of containers: the job, and the services it asks for, like a throwaway PostgreSQL for the tests. And the runner creates those containers itself, outside of compose, so the resource classes from part 2 never reached them.&lt;/p&gt;
&lt;p&gt;They ran with Docker&apos;s default CPU weight, 1024. Every class except &lt;code&gt;critical&lt;/code&gt; is below it, so when the CPU was busy, the CI won over the services. With four jobs at a time the load average went to about 40, and the CPU pressure said that two thirds of the time something was waiting for a core. With two jobs, the CI still took 7 core-hours a day.&lt;/p&gt;
&lt;p&gt;Now the runner takes one job at a time, and every job container gets the weight of the &lt;code&gt;low&lt;/code&gt; class, at most one and a half cores, and 5 GB of memory with no swap, so a runaway test cannot push the rest of the server out of RAM:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;runner:
  capacity: 1
container:
  network: &quot;&quot;
  options: &quot;--memory=5g --memory-swap=5g --cpus=1.5 --cpu-shares=192&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A job still uses every idle cycle. It just steps aside when the CPU is short, and a pipeline waits in the queue for a few minutes instead of slowing down Plex. The empty &lt;code&gt;network&lt;/code&gt; gives each job a fresh network of its own: with a shared one, every job&apos;s PostgreSQL had the same name, and the tests sometimes connected to another job&apos;s database.&lt;/p&gt;
&lt;p&gt;Running the CI next to the services is not ideal, and it is one of the things we will fix sooner or later.&lt;/p&gt;
&lt;h2&gt;Next&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://devncode.it/homelab-monitoring-prometheus-loki-grafana/&quot;&gt;Part 4&lt;/a&gt; is about what happens after the deploy: the alerts that should tell me when something breaks, including the ones a deploy causes.&lt;/p&gt;
</content:encoded></item><item><title>Structuring an Ansible repo for a one-server homelab</title><link>https://devncode.it/ansible-homelab-repo-structure/</link><guid isPermaLink="true">https://devncode.it/ansible-homelab-repo-structure/</guid><description>One role per service for atomic deploys, every value in two files, resource classes for CPU and memory, and a precedence trap that overrode production.</description><pubDate>Sun, 11 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The server from &lt;a href=&quot;https://devncode.it/run-homelab-like-production/&quot;&gt;part 1&lt;/a&gt; runs about a hundred containers, and one Ansible repo describes all of them. I picked Ansible because I have used it for years and I have always been happy with it. This part is about the shape of that repo: where a service lives, where its values live, and how one bad loading order overrode production for months without anyone noticing.&lt;/p&gt;
&lt;h2&gt;One role per service&lt;/h2&gt;
&lt;p&gt;Every service is a role, and every role has its own tag in the playbook. That is the whole reason for the layout: a deploy can touch one service and nothing else. A role is small and always looks the same:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;roles/&amp;lt;service&amp;gt;/
  tasks/main.yml           create the directories, render the files, compose up
  templates/
    docker-compose.yml.j2  the container, with limits from the resource classes
    &amp;lt;config files&amp;gt;.j2      whatever the service reads at start
  handlers/main.yml        restart the container when a rendered file changes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The playbook runs the roles in order: first the base system (common, router, VPN, ZFS, Docker), then the services. A full deploy goes through all of them. A normal one does not. When I moved the temp directory of Plex into RAM, it was one variable, one line in a template and &lt;code&gt;make deploy-tags TAGS=plex&lt;/code&gt;, and only Plex restarted.&lt;/p&gt;
&lt;p&gt;Almost no role has a &lt;code&gt;defaults/&lt;/code&gt; directory, and none has &lt;code&gt;vars/&lt;/code&gt;. A role holds the logic, not the values.&lt;/p&gt;
&lt;h2&gt;Every value in two files&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;inventory/group_vars/all/common.yml&lt;/code&gt; has everything shared: datasets, ports, hostnames, resource limits. &lt;code&gt;inventory/production/group_vars/all/vars.yml&lt;/code&gt; has what belongs to the real server: addresses, interfaces, and references to the secrets, which are in an encrypted &lt;code&gt;vault.yml&lt;/code&gt; next to it.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;vault.yml.example&lt;/code&gt; lists the keys of the vault with fake values, so I can read what exists without decrypting anything. &lt;code&gt;make vault-check&lt;/code&gt; compares the two lists and fails when a key is missing from the example or left there after removal.&lt;/p&gt;
&lt;h2&gt;Resource classes instead of numbers&lt;/h2&gt;
&lt;p&gt;This server was born for Plex and the *arr stack, and nothing else. Everything that came after shares the same 4 cores and 32 GB, and the CPU is the tight part. Giving every service the right resources is critical, and Docker gives three knobs per container:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;cpu_shares&lt;/code&gt; is a weight, not a cap. It only matters when the CPU is busy, and Docker&apos;s default is 1024.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;mem_limit&lt;/code&gt; is a hard cap. A container that goes over it gets a process killed by the kernel, inside that container, and the rest of the server is not involved.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;oom_score_adj&lt;/code&gt;, from -1000 to 1000, decides who the kernel kills first when the whole host runs out of memory.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Three numbers for each of a hundred services is a lot of numbers to keep consistent. So the numbers live in a few named classes, and a service picks one:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;resource_class:
  critical:
    cpu_shares: 4096
    mem_limit: &quot;0&quot;
    oom_score_adj: -500
  high:
    cpu_shares: 768
    mem_limit: 768m
    oom_score_adj: -100
  high_light:
    cpu_shares: 768
    mem_limit: 384m
    oom_score_adj: -100
  medium:
    cpu_shares: 384
    mem_limit: 768m
    oom_score_adj: 0
  low_light:
    cpu_shares: 192
    mem_limit: 384m
    oom_score_adj: 100
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The name says the priority, the suffix says the memory: &lt;code&gt;high&lt;/code&gt; and &lt;code&gt;high_light&lt;/code&gt; get the same CPU weight and the same place in the kill order, and differ only in the cap. &lt;code&gt;critical&lt;/code&gt; has no memory cap, four times Docker&apos;s default weight, and is the last thing the kernel kills. Only two services are in it: Vaultwarden, and Plex, the reason the server exists. A few classes exist for one kind of workload, like the containers that drive a real Chrome: a single page of results costs about 400 MB, so they get 2 GB.&lt;/p&gt;
&lt;p&gt;The mapping is one line per service:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;container_resources:
  plex: &quot;{{ resource_class.critical }}&quot;
  traefik: &quot;{{ resource_class.high }}&quot;
  adguard: &quot;{{ resource_class.high_light }}&quot;
  sonarr: &quot;{{ resource_class.medium }}&quot;
  transmission: &quot;{{ resource_class.high }}&quot;
  vaultwarden: &quot;{{ resource_class.critical }}&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each compose template reads its three values from there, so no number is ever written in a role:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    cpu_shares: {{ container_resources.plex.cpu_shares }}
    mem_limit: {{ container_resources.plex.mem_limit }}
    oom_score_adj: {{ container_resources.plex.oom_score_adj }}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The classes change after incidents. A service that needs more moves to another class, and the comment next to its line says why. Traefik was &lt;code&gt;high_light&lt;/code&gt;, until one afternoon it went from 85 to 371 MB in under two minutes: the kernel killed it at its 384 MB cap, and every site behind the proxy went down with it. Now it is &lt;code&gt;high&lt;/code&gt;, with the same weight and twice the memory. Transmission was &lt;code&gt;medium&lt;/code&gt;, until two Plex transcodes at once left it so little CPU that 41% of the calls to its web interface took more than 5 seconds. Now it is &lt;code&gt;high&lt;/code&gt;, with the same memory and twice the weight. Both fixes were a one-word change.&lt;/p&gt;
&lt;h2&gt;The loading order that overrode production&lt;/h2&gt;
&lt;p&gt;For months the playbook loaded &lt;code&gt;common.yml&lt;/code&gt; with &lt;code&gt;vars_files&lt;/code&gt;. That is the wrong place for shared defaults. In Ansible&apos;s &lt;a href=&quot;https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_variables.html#understanding-variable-precedence&quot;&gt;variable precedence&lt;/a&gt;, play &lt;code&gt;vars_files&lt;/code&gt; rank above inventory &lt;code&gt;group_vars&lt;/code&gt;. So when a key was in both files, the shared default won over production.&lt;/p&gt;
&lt;p&gt;It happened with the DHCP reservations. &lt;code&gt;common.yml&lt;/code&gt; had an empty &lt;code&gt;router_dhcp_static_leases: []&lt;/code&gt; as a default, &lt;code&gt;vars.yml&lt;/code&gt; had the real list with the access point in it, and dnsmasq got the empty one. The access point had no reserved address, and I never noticed. It was not about that key either: every key present in both files lost to the default, including the ones nobody had added yet.&lt;/p&gt;
&lt;p&gt;Now &lt;code&gt;common.yml&lt;/code&gt; is part of the inventory. The environment&apos;s &lt;code&gt;group_vars/all/&lt;/code&gt; has a symlink to it, next to &lt;code&gt;vars.yml&lt;/code&gt;, and Ansible reads the files of a &lt;a href=&quot;https://docs.ansible.com/projects/ansible/latest/inventory_guide/intro_inventory.html&quot;&gt;group_vars directory&lt;/a&gt; in lexicographical order: &lt;code&gt;c&lt;/code&gt; before &lt;code&gt;v&lt;/code&gt;, shared before production.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;group_vars/all/
  common.yml              the shared file, the only copy
production/
  hosts.yml
  group_vars/all/
    common.yml -&amp;gt; ../../../group_vars/all/common.yml
    vars.yml              read after common.yml, so it wins
    vault.yml
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Achtung&lt;/strong&gt;
The order is alphabetical. Rename &lt;code&gt;vars.yml&lt;/code&gt; to something that sorts before &lt;code&gt;common.yml&lt;/code&gt;, and the shared defaults win again, without a warning.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Something this easy to break gets a test. &lt;code&gt;tests/test_var_precedence.sh&lt;/code&gt; has two halves. The first reads the repo: no &lt;code&gt;vars_files&lt;/code&gt; in the playbook, a symlink that resolves to the one shared file, &lt;code&gt;common.yml&lt;/code&gt; sorting before &lt;code&gt;vars.yml&lt;/code&gt;. The second asks Ansible for the values with &lt;code&gt;ansible -m debug -c local&lt;/code&gt;, which renders them without touching the server, and expects production to win: the access point is in the lease list, and every key that differs between the two files has the value from &lt;code&gt;vars.yml&lt;/code&gt;. CI has no vault, so there only the first half runs. The second runs on my machine.&lt;/p&gt;
&lt;h2&gt;Docs that point to the code&lt;/h2&gt;
&lt;p&gt;The last rule is about the &lt;code&gt;docs/&lt;/code&gt; folder. Docs explain why. They never list services, datasets, networks, databases, tags or versions: those live in &lt;code&gt;common.yml&lt;/code&gt; and &lt;code&gt;site.yml&lt;/code&gt;, and the docs link there. I made it a rule because static lists were impossible to keep up to date. When I applied it, some docs no longer matched the code at all: one still described HTTP-01 certificates, while Traefik was using the DNS-01 challenge with Route53.&lt;/p&gt;
&lt;p&gt;Lint is a rule too: yamllint and ansible-lint, with the &lt;code&gt;production&lt;/code&gt; profile, on every push, and the result must be zero warnings. Exceptions go in the linter config, where they are visible. It is worth it, but it is a detail next to the rest.&lt;/p&gt;
&lt;h2&gt;Next&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://devncode.it/homelab-deploy-forgejo-semaphore/&quot;&gt;Part 3&lt;/a&gt; follows one change from the commit to the running container: the CI, the Semaphore webhook, and the checks after a deploy.&lt;/p&gt;
</content:encoded></item><item><title>Running a one-server homelab like production</title><link>https://devncode.it/run-homelab-like-production/</link><guid isPermaLink="true">https://devncode.it/run-homelab-like-production/</guid><description>One Debian box is the router, the NAS and the media server for my family. Why it runs from an Ansible repo with CI, alerts and tested backups.</description><pubDate>Sat, 10 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Everything my family uses at home runs on one machine: an i5-6500T with 4 cores and 32 GB of RAM, Debian 13, a 250 GB SSD with the system and a ZFS pool, and two USB disks, 6 TB for media and 4 TB for backups. About a hundred containers run on it. It is also the router, so when it goes down, the house goes offline.&lt;/p&gt;
&lt;p&gt;This series is about how I keep that machine boring. This first part is the why, and a map of the pieces. The other parts go into each piece.&lt;/p&gt;
&lt;h2&gt;Kubernetes was too much&lt;/h2&gt;
&lt;p&gt;Before the current setup I had a Kubernetes cluster with Argo CD. Exploring GitOps was fun, but for us it was overkill: we have one node and no shared filesystem.&lt;/p&gt;
&lt;p&gt;In March 2026 I started again from an empty repo, with Ansible. Its README states the rule: the repo is the source of truth, and the server is disposable. Everything that matters lives on ZFS datasets that are backed up every night, and a fresh Debian install plus one playbook rebuilds the rest. There is a runbook for that rebuild in the repo.&lt;/p&gt;
&lt;h2&gt;Why the server became the router&lt;/h2&gt;
&lt;p&gt;Until April the router was a TP-Link AX18. A NAT router keeps a connection tracking table: one entry for every connection between a device inside and a host outside, so it knows where to send the replies. Every entry costs memory, and the AX18 has 256 MB of RAM for everything it does. When the table is full, new connections are dropped. With the devices of a whole family and a torrent client, ours was full, and the symptom was the upload: it went to almost zero.&lt;/p&gt;
&lt;p&gt;First I tried to make the problem smaller: I lowered Transmission&apos;s peer limit from 200 to 80, and started pinging three targets every 15 seconds, the gateway and two public DNS servers, so the next outage would show whether the router or the provider was at fault. Two days later I moved NAT, DHCP and the firewall to the server, and the AX18 became a Wi-Fi access point.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;AX18 doing NAT&lt;/th&gt;
&lt;th&gt;Server doing NAT&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Upload&lt;/td&gt;
&lt;td&gt;almost 0 Mbps&lt;/td&gt;
&lt;td&gt;887 Mbps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Download&lt;/td&gt;
&lt;td&gt;355 Mbps&lt;/td&gt;
&lt;td&gt;941 Mbps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Connection tracking&lt;/td&gt;
&lt;td&gt;256 MB of RAM for the whole router&lt;/td&gt;
&lt;td&gt;room for 262,144 entries, about 2,800 in use as I write&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Probably a good router would have been enough. But we like to make our lives complicated, and this way we got two things for one. The server now hands out the addresses on the network, and it gives itself as the DNS server, so every device goes through AdGuard and the ad and tracker filters live in one place.&lt;/p&gt;
&lt;p&gt;The price is that the server is the single point of failure for the whole family. It is not ideal. One day we will fix it.&lt;/p&gt;
&lt;h2&gt;How the pieces fit&lt;/h2&gt;
&lt;p&gt;The diagram is the whole series in one picture. The laptop and Semaphore change the server; Prometheus, Loki and restic watch it and copy it. Forgejo and Semaphore run on the same server, which is less circular than it looks: a deploy from the laptop needs neither of them.&lt;/p&gt;
&lt;p&gt;&amp;lt;figure style=&quot;margin:2rem 0&quot;&amp;gt;
&amp;lt;svg viewBox=&quot;0 0 440 520&quot; role=&quot;img&quot; aria-labelledby=&quot;hlp-title hlp-desc&quot; style=&quot;display:block;width:100%;max-width:440px;height:auto;margin:0 auto;font-family:var(--font-sans)&quot;&amp;gt;
&amp;lt;title id=&quot;hlp-title&quot;&amp;gt;How the homelab is built, deployed and watched&amp;lt;/title&amp;gt;
&amp;lt;desc id=&quot;hlp-desc&quot;&amp;gt;A laptop pushes to Forgejo, which lints and tests every push. A release triggers Semaphore. The laptop or Semaphore applies Ansible roles to the server. The server sends metrics and logs to Prometheus, Loki and Grafana, which alert on Telegram, and restic copies its data to S3 every night.&amp;lt;/desc&amp;gt;
&amp;lt;defs&amp;gt;&amp;lt;marker id=&quot;hlp-arrow&quot; viewBox=&quot;0 0 8 8&quot; refX=&quot;7&quot; refY=&quot;4&quot; markerWidth=&quot;7&quot; markerHeight=&quot;7&quot; orient=&quot;auto&quot;&amp;gt;&amp;lt;path d=&quot;M0,0 L8,4 L0,8 z&quot; style=&quot;fill:var(--muted)&quot;/&amp;gt;&amp;lt;/marker&amp;gt;&amp;lt;/defs&amp;gt;
&amp;lt;g style=&quot;fill:var(--code-bg);stroke:var(--rule);stroke-width:1&quot;&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;20&quot; width=&quot;190&quot; height=&quot;80&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;20&quot; width=&quot;190&quot; height=&quot;80&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;150&quot; width=&quot;190&quot; height=&quot;80&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;410&quot; width=&quot;190&quot; height=&quot;96&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;rect x=&quot;230&quot; y=&quot;410&quot; width=&quot;190&quot; height=&quot;96&quot; rx=&quot;6&quot;/&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;rect x=&quot;20&quot; y=&quot;280&quot; width=&quot;400&quot; height=&quot;80&quot; rx=&quot;6&quot; style=&quot;fill:var(--code-bg);stroke:var(--accent);stroke-width:1.5&quot;/&amp;gt;
&amp;lt;g style=&quot;stroke:var(--muted);stroke-width:1.5;fill:none&quot; marker-end=&quot;url(#hlp-arrow)&quot;&amp;gt;
&amp;lt;line x1=&quot;210&quot; y1=&quot;60&quot; x2=&quot;228&quot; y2=&quot;60&quot; marker-end=&quot;url(#hlp-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;100&quot; x2=&quot;325&quot; y2=&quot;148&quot; marker-end=&quot;url(#hlp-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;115&quot; y1=&quot;100&quot; x2=&quot;115&quot; y2=&quot;278&quot; marker-end=&quot;url(#hlp-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;230&quot; x2=&quot;325&quot; y2=&quot;278&quot; marker-end=&quot;url(#hlp-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;115&quot; y1=&quot;360&quot; x2=&quot;115&quot; y2=&quot;408&quot; marker-end=&quot;url(#hlp-arrow)&quot;/&amp;gt;
&amp;lt;line x1=&quot;325&quot; y1=&quot;360&quot; x2=&quot;325&quot; y2=&quot;408&quot; marker-end=&quot;url(#hlp-arrow)&quot;/&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--fg);font-size:15px;font-weight:600&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;46&quot;&amp;gt;Laptop&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;46&quot;&amp;gt;Forgejo&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;176&quot;&amp;gt;Semaphore&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;306&quot;&amp;gt;Server&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;436&quot;&amp;gt;Grafana&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;436&quot;&amp;gt;restic → S3&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g text-anchor=&quot;middle&quot; style=&quot;fill:var(--muted);font-size:13px&quot;&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;68&quot;&amp;gt;git push&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;88&quot;&amp;gt;make deploy-tags&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;68&quot;&amp;gt;git repos&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;88&quot;&amp;gt;Actions: lint, tests&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;198&quot;&amp;gt;webhook on release&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;218&quot;&amp;gt;runs one role&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;328&quot;&amp;gt;Debian 13 · ZFS · ~100 containers&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;220&quot; y=&quot;348&quot;&amp;gt;one Ansible role per service&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;458&quot;&amp;gt;Prometheus, Loki&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;478&quot;&amp;gt;a dashboard per service&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;115&quot; y=&quot;498&quot;&amp;gt;alerts on Telegram&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;458&quot;&amp;gt;every night&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;478&quot;&amp;gt;checked every week&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;325&quot; y=&quot;498&quot;&amp;gt;restored every month&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g style=&quot;fill:var(--muted);font-size:12px&quot;&amp;gt;
&amp;lt;text x=&quot;123&quot; y=&quot;194&quot;&amp;gt;deploy&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;333&quot; y=&quot;128&quot;&amp;gt;release&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;333&quot; y=&quot;258&quot;&amp;gt;apply&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;123&quot; y=&quot;390&quot;&amp;gt;metrics, logs&amp;lt;/text&amp;gt;
&amp;lt;text x=&quot;333&quot; y=&quot;390&quot;&amp;gt;data&amp;lt;/text&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;/svg&amp;gt;
&amp;lt;/figure&amp;gt;&lt;/p&gt;
&lt;h3&gt;One repo, one playbook&lt;/h3&gt;
&lt;p&gt;One Ansible role per service, all run in order by one playbook. Two variable files hold every setting: one shared, and one for production with the real addresses and the references to the vault, where the secrets are. In broad lines the repo looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;inventory/
  group_vars/all/common.yml     shared settings: datasets, limits, hostnames
  production/
    hosts.yml                   the one server
    group_vars/all/
      vars.yml                  production values, pointers into the vault
      vault.yml                 secrets, encrypted with ansible-vault
playbooks/
  site.yml                      one play, every role in order
roles/
  &amp;lt;service&amp;gt;/
    tasks/main.yml              directories, config files, compose up
    templates/                  docker-compose.yml.j2 and the config files
    handlers/main.yml           restart when the config changes
  grafana/files/dashboards/     one dashboard per service
scripts/
  deploy-verify.sh              checks after a deploy
docs/                           the why: architecture, runbooks
Makefile                        lint, test, deploy-check, deploy-tags
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The playbook starts by refusing to run on anything that is not Debian 13, then goes through the roles from the base system up:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  pre_tasks:
    - name: Verify Debian 13 (Trixie)
      ansible.builtin.assert:
        that:
          - ansible_facts[&apos;distribution&apos;] == &quot;Debian&quot;
          - ansible_facts[&apos;distribution_major_version&apos;] == &quot;13&quot;
        fail_msg: &quot;This playbook requires Debian 13 (Trixie)&quot;

  roles:
    - role: common
      tags: [common, security]

    - role: router
      tags: [router, network]
      when: router_enabled | default(false)

    - role: wireguard
      tags: [wireguard, vpn, network]
      when: wireguard_port is defined

    - role: zfs
      tags: [zfs, storage]

    - role: docker
      tags: [docker]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://devncode.it/ansible-homelab-repo-structure/&quot;&gt;Part 2&lt;/a&gt; is about how the repo is organized and why the docs never list services.&lt;/p&gt;
&lt;h3&gt;Deploy one role at a time&lt;/h3&gt;
&lt;p&gt;I don&apos;t change containers on the server by hand. A change is a commit, and a deploy usually touches one role, with a dry run first when the change is risky:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;deploy-check: galaxy ## Dry-run deployment on production
	uv run ansible-playbook $(PLAYBOOK) -i $(INVENTORY) --check --diff

deploy: galaxy ## Deploy to production
	uv run ansible-playbook $(PLAYBOOK) -i $(INVENTORY)

deploy-tags: galaxy ## Deploy specific tags to production (usage: make deploy-tags TAGS=router)
	uv run ansible-playbook $(PLAYBOOK) -i $(INVENTORY) --tags $(TAGS)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After the deploy, a script checks the container status, the HTTP answer over the real domain and the last minutes of logs. Every push runs yamllint, ansible-lint and the offline tests on Forgejo Actions, and lint has to finish with zero warnings. The apps I write myself have their own pipeline: a tagged release runs test, publish, release and deploy, and the last step calls a Semaphore webhook that applies the app&apos;s role. &lt;a href=&quot;https://devncode.it/homelab-deploy-forgejo-semaphore/&quot;&gt;Part 3&lt;/a&gt; is the deploy path, step by step.&lt;/p&gt;
&lt;h3&gt;Alerts with the threshold on the graph&lt;/h3&gt;
&lt;p&gt;Every service gets a Grafana dashboard, and its alert rules live in the repo with everything else. They arrive on Telegram. The rule is that a panel with an alert draws the alert&apos;s threshold as a line, so the number on the graph and the number that sends the message are the same number. &lt;a href=&quot;https://devncode.it/homelab-monitoring-prometheus-loki-grafana/&quot;&gt;Part 4&lt;/a&gt; is the whole monitoring: metrics, logs, dashboards and alerts.&lt;/p&gt;
&lt;h3&gt;Backups that get restored&lt;/h3&gt;
&lt;p&gt;Restic copies the container data to S3 every night and keeps 30 days. Once a week a job runs &lt;code&gt;restic check&lt;/code&gt; and reads the data back. Once a month a drill restores every database into a throwaway copy. I learned the hard way that a backup has to be tested: &lt;a href=&quot;https://devncode.it/time-machine-samba-docker/&quot;&gt;part 5&lt;/a&gt; is that story.&lt;/p&gt;
&lt;h2&gt;What the monitoring missed&lt;/h2&gt;
&lt;p&gt;Three examples from the last months:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The verification of the Time Machine backup bundle had not run for five months, and no alert said it. I found it by hand, and the alert on the age of the last verification came after (part 5).&lt;/li&gt;
&lt;li&gt;The ZFS ARC was allowed 97% of the RAM, next to all those containers. I found it while going through the memory of the server after an outage (&lt;a href=&quot;https://devncode.it/zfs-arc-max-homelab/&quot;&gt;part 6&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;One day the Docker daemon restarted. A minute before, the authentik worker had died: it had started before DNS was up and could not find its database. The &lt;code&gt;unless-stopped&lt;/code&gt; policy does not bring back a container that was already stopped when the daemon starts again, so the worker stayed down, and half of authentik with it. No alert fired.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of the three was caught by an alert the first time. Each one ended up in the repo: an alert for Time Machine, a cap in the ZFS role, and &lt;code&gt;restart: always&lt;/code&gt; for the critical containers.&lt;/p&gt;
&lt;h2&gt;What it costs, and the weak spot&lt;/h2&gt;
&lt;p&gt;Day to day, it is low effort. Most changes are one role and one &lt;code&gt;make deploy-tags&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The weak spot is the storage. Two USB disks are amateur stuff: they are hard to expand, and the backup disk is six years old. The next step is probably a real DAS.&lt;/p&gt;
&lt;p&gt;The rest of the series, in the order it makes sense to read it, is on the &lt;a href=&quot;https://devncode.it/series/homelab-like-production/&quot;&gt;series page&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item></channel></rss>