Some Bits: Nelson's log

187 posts about homelab

Updating Plex in Linux (NixOS)

Major Plex exploit this week shows out a bunch of older Plex servers that weren’t updated. Turns out Plex server does not auto-update itself in Linux. It does on Mac and Windows. But in Linux you’re expected to update it yourself through your OS.

I used to run Plex server on Debian. Updating there was as simple as an apt upgrade. But you’d still have to remember to run that, I’m not sure unattended-upgrades covered it.

I’m now running Plex server on NixOS. Entirely with Claude Code’s help managing Nix. We came up with several ways to update it, none entirely satisfactory:

  1. Install Plex from nixpkgs, either stable or unstable. You can run system.autoUpgrade and have NixOS update itself on a timer. This works but updates tend to be a little behind: nixpkgs is a few weeks behind Plex releases. The crucial security fixes did come out in a timely fashion.
  2. Install Plex with Nix yourself from a hand-rolled file that grabs a pinned Plex server .deb and installs it in NixOS. This is a little tricky because of Nix’ assumptions about paths, Claude ended up creating a bubblewrap environment for it. The problem is for new Plex releases you have to repin, run a Nix update yourself from your dev environment, rebuild and switch.
  3. Don’t install Plex with Nix. Instead make a generic NixOS container that manages everything except Plex’s own program files. Then have that container launch a script to download and install Plex in /var/lib in the NixOS container. Also an update script that downloads new versions and installs them on its own.

There’s a similar question with Plex’ config file, the Preferences.xml. Claude started wanting to manage that itself as part of the Nix config. But that means the Plex GUI for editing the config would be overwritten by new Nix pushes. The other option is just to keep it as a file outside of Nix on the server.

I started with option 2 (my Nix config doing the work). I quickly got irritated at how much work I had to do to push an update. So now I’m in option 3. I lose Nix management of Plex and its config file. But Claude’s own script can handle upgrades for me, it seems like a reasonable design. We’ll see in a few weeks.

Option 1 is probably the simplest and most reasonable. I went with 3 because I wanted updates ASAP.

rsync --append trap

I learned something from Claude Code today. rsync --append isn’t very safe. The common pattern of rsync --partial --append is suggested as a way to copy files and allow resume. That’s not a good idea to put in recurring sync jobs you run regularly over a long period of time.

The problem is --append won’t retransfer a file in many circumstances if the contents changed. And it only writes new data. It is append only and rsync’s man page warns it is “only applicable to update files that are known to be growing larger, that is, where any existing content on the receiving side is also known to be the same as the content on the sender”. If the file changes on the sending side, it can cause all sorts of corruption on the receiver.

I was using rsync --append to sync video between two machines once a week. But the source occasionally updated files in-place when I got better copies of the video. The destination wouldn’t replace the file when the source changed and so my destination slowly got out of sync.

Before 2008 and rsync 3.0, rsync did more checking with --append. So old advice may not have been wrong at the time.

In modern rsync there’s a --append-verify that will help but won’t catch the case where the updated file is smaller than the original. --append will still skip it in that case.

Claude Code advises me to not use --append at all, it’s the --partial that does the work of allowing resumes (for network copies). There’s also a --partial-dir which keeps partial downloads in an out-of-sight directory until they’re done.

If you’ve been running --append on a mirror, do an rsync -c to verify checksums and find damaged files.

Vault: my new file storage

After some 35 years of ad hoc carrying files around from place to place, I finally have all my important digital files in one well built storage system I’m calling “Vault”. More or less like a lot of people do with a NAS, but a little different.

Hardware

Vault is a Linux container running on Proxmox in SF. It stores files to three ZFS pools managed by Proxmox. One small volume for important small files on NVMe storage (two devices, mirrored). One large volume of large media files on spinning rust (again, a mirror). And one large volume of backups on spinning rust (single disk). There’s also offsite backups of everything but the video files to Backblaze B2.

Software

So far that’s pretty basic. The slightly unusual thing is what software runs on vault. Note this whole thing is LAN and Tailnet only, not on a public network. The setup was all built via AI but the big choices are mine.

  • Proxmox and ZFS for the hardware management. Tailscale for network access.
  • NixOS in a privileged LXC container for the vault operating system. Nix is my new thing for using AI to build servers. The declarative system seems a good match for coding agents.
  • No NFS or SMB. That’s the weirdest choice I made. I’ve never liked synchronous network filesystems, they are lies. It would be easy to add one of these but I don’t need it.
  • Syncthing. The most important volume I store is all my source code, about 15GB of my career over 35 years. I sync this to several different computers. I’ve been using Syncthing for years and it is a reliable workhorse. This is what I use instead of a network filesystem, particularly when working in Grass Valley.
  • sftp/sshfs. For needing to access a remote file outside of src. Purely for ad hoc use, this is very easy in the Linux Dolphin file manager. I could set up a FUSE mount too.
  • bind mounts and virtiofs. This is what allows a container on the SF Proxmox host to access the files in the Vault’s ZFS pools. Vault itself is working through bind mounts to the volumes. virtiofs is a relatively new option for the same thing for VMs. (I used to use NFS for that.)
  • Restic for backups. Both to a local disk and also offsite to B2.
  • File Browser for web access to files. Not sure I really need this, and the project just got shut down, but it’s there.
  • plocate for finding files. This is really not adequate: I have to ssh in and all it does is grep filenames. But it’s something. One big project I’m considering is some fancy full text indexing of all the contents and their metadata. That’s an endless project, I wonder if there’s something good off the shelf I can use.
  • ntfy.sh for notifications. What a great little service! I just use the public free tier, it’s enough for my needs and very easy to use

AI development

I bought the hard drives for this project in 2024. I even got halfway through building a Debian VM to manage everything, poorly, and then abandoned it because I couldn’t see a path forward to trusting this thing with my files.

I built the whole thing with Claude Code and Opus/High in 5 days.

Claude was active about 23 hours of that time. Me, maybe 10 hours? It used $205 in credits but all fit in the $20/mo subscription.

The process mostly went well. I had it come up with a design, then a work plan, then we stepped through tasks. I gave Claude more power than I have in previous projects and that was a good choice. But then I also had a lot of verification steps, including full backup tests outside Claude’s control. (I’m still trusting Claude somewhat: on my own I’m testing backup integrity and completeness but only spot checking identical files. Claude says it checked every single file.)

We made one major mistake. Part of the consolidation involved changing the UID for my files. I still have a VM that uses the old UID and so now it can’t write some files it used to be able to. (Unfortunately Proxmox’ UI for virtiofs doesn’t support any way to map UIDs.) It’s not a big deal, and I plan to shut that VM down entirely. Claude mostly was working to anticipate and avoid problems like this, as was I, but we both missed this one.

Overall the AI did a much better job than I would have. It got it done with no drama and with better testing and monitoring and backups than I’d ever manage on my own. I’m a total AI convert for this kind of project now.

Cleaning up my hosted services

I’ve got a shiny new dashboard and consistent access to all my home services! It’s very nice.

Since adopting Proxmox a couple of years ago I’ve grown to hosting a bunch of my own services. I didn’t really think about how I accessed them: I just threw them all on Tailscale and accessed them ad hoc. Each with their own URL on a random port, password, failing SSL, etc.

In this new setup I have a gateway that proxies requests to backend services. I have a single wildcard domain for them all. So linkding.private.example.com gets me to linkding instead of linkding.some-nonce.ts.net:9090. And SSL works. For some services, the gateway running at private.example.com could even handle authentication so I don’t have to use Linkding’s own password system. And in theory this system is safe to run on the public Internet, but in the last minute I chickened out.

Gateway: Reverse proxy

¾ of the value of my setup is running Caddy as a reverse proxy for *.private.example.com. I wish I’d done this a long time ago! Now all my requests go to one proxy web server with a wildcard domain. It’s much nicer than setting up tailscale on each service container. And Caddy makes SSL easy so I no longer have to click through a bunch of SSL errors.

Setting this up is pretty easy, mostly it’s just a bunch of config blocks like

        @linkding host linkding.private.example.com
        handle @linkding {
                reverse_proxy 192.168.0.34:9090
        }

A few of the services get persnickety about the hostname on the request matching their idea of their hostname, so you have to tell them to accept the proxy name as theirs.

Gateway: Authelia

The complicating factor on the gateway is I have Caddy set up to only proxy requests if I’m authenticated via Authelia. That works by setting up something like this in Caddy and including it in each service definition:

(authelia) {
        forward_auth 127.0.0.1:9091 {
                uri /api/authz/forward-auth
                copy_headers Remote-User Remote-Groups Remote-Name Remote-Email
        }
}

There’s a bunch of extra work to configure Authelia. For simple things a basic policy: two_factor rule is sufficient, Authelia will demand I log in before forwarding requests. For Linkding I had to add a special bypass rule for /api/ so that the Chrome extension worked.

I’m not sure Authelia was worth the trouble. Originally I did all this because I wanted to make this gateway host be on the public Internet, and so of course authentication is important. I think the config I have is secure to do that. But it’s complicated and I don’t really trust it, so at the last minute I put the gateway on my Tailnet instead of the public Internet. That’s fine for me.

The neat thing about this gateway approach is it works for multiple users. If I had many people accessing my backend services, possibly not from the tailnet, I’d commit to building trust.

The other nice thing Authelia can do is single sign-on. I log in to Authelia as Nelson, then it tells the backend services I’m Nelson and they trust that. Sometimes this works with a simple HTTP header, sometimes you need something more complex like OIDC.

I did set up proxied authentication for the linkding service. It was remarkably complicated, the key config is telling linkding LD_AUTH_PROXY_USERNAME_HEADER=HTTP_REMOTE_USER.

Every backend service has a different setup. And of course this means fully trusting Authelia’s authentication, it’s a little scary. I may do more of this in the future but for now I still have a bunch of passwords.

Homepage

The other part of this project was setting up Homepage, a simple website which serves as a lightweight dashboard + bookmarks for services. I like how it works, everything’s configured in one simple file and it’s pretty stateless. I’ll see how useful this is as a UI, I’m hoping it replaces my unwieldy list of bookmarks.

Sysadmin in the age of Claude

I never would have tried a project this complex without AI help. I used to love tinkering with this kind of stuff. But as I’ve gotten older and more retired I’ve gotten crankier about learning new things.

But using Claude is a marvel. I mostly did this with Opus/High and it was mostly right. I wanted to learn it as I went and I didn’t quite trust Claude, so I ran all the commands myself. Next time I might trust an agent to do the work for me.

Overall this project took about 6 hours over 3 days.

Proxmox secure boot: June apocalypse

The failed Secure Boot technology has a booby trap in it that might keep Linux boxes, including VMs, from successfully booting because some certificates start expiring June 24. The suggested fix is to enroll new security keys, which require a lot of BIOS fiddling. I was impressed Proxmox had a warning about this for your VMs and a tool for fixing it. Seems to work. It adds ms-cert=2023k,pre-enrolled-keys=1 to the disk options for the EFI partition.

Update: secure boot keys on PC hardware

I have some hardware I don’t have access to and I’m wondering if it will refuse to boot come June 27. Here’s some stuff you can do from a Linux CLI. RedHat also has decent docs on this.

mokutil --sb-state will tell you if secure boot is active at all. It looks like it’s disabled on both of my Linux servers. A little surprised at that, btw.

mokutil --db will show you the enrolled keys for secure boot. I don’t really know how to read all this, but you can find the problematic keys.

        Issuer: C=US, ST=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Corporation Third Party Marketplace Root
        Validity
            Not Before: Jun 27 21:22:45 2011 GMT
            Not After : Jun 27 21:32:45 2026 GMT

Apparently the good new key will say 2023, but I don’t have one to be sure.

Adding the new key is something you have to do in the BIOS. Installing a firmware update from the console is the surefire way. LVFS should also be able to do it, maybe as simple as fwupdmgr update. But that doesn’t seem to add a 2023 cert for me on my ASUS motherboard.

Looking in dmesg for things about X.509 certs may be instructive for what the Linux system is doing. That won’t tell you what the BIOS is doing though.

A fine rant

Secure Boot is a complete disaster. In theory it was supposed to protect against pernicious malware. In practice it’s been a complete sham since the beginning because all the implementations are deeply buggy. See here for some history on that. If BIOS malware were a real thing in practice we would have seen a lot more attacks against these buggy implementations using such things as CN=DO NOT TRUST that were trusted by every major PC manufacturer.

What Secure Boot did do was protect Microsoft’s monopoly. It continues to make installing other operating systems very difficult on PCs. About once a year I have to spend an hour+ dealing with some sort of secure boot fiasco in Linux. The most recent example: Nobara just doesn’t support it at all because they have no practical way to sign kernel packages in their build system.

So I’m disabling Secure Boot everywhere. Including in VM BIOS, what a farce. I had one old PC that caused problems if you disabled it though. If you turned off secure boot there was no way to use some other platform features, maybe the TPM? I haven’t run into that in awhile though.

Proxmox container for a Tailscale exit node

I want to set up a Tailscale exit node for me on the server with a good home Internet connection. This is a sort of poor-man’s VPN, routing all traffic through my home ISP connection. It’s pretty easy but I ran into a problem with IP forwarding.

First I set up a tiny Alpine container and used the Tailscale community script to set up Tailscale on it. You can install Tailscale by hand but this script handles the extra config needed to give an unprivileged LXC access to the tunnel device.

Then I set up Tailscale in the container to advertise as an exit node. The key thing there is sysctl configurations to enable IP forwarding inside the container OS. Very important! You also have to tell tailscale to advertise itself as an exit node.

Once I did this it worked. At least, I think it did. But it stopped working, maybe after a reboot?

To fix it, I also enabled IP forwarding via sysctl on the Proxmox server itself. I’m not 100% sure this is required or even a good idea. But when I enabled it, the exit node started working again. I’m a little confused about this but I think it’s OK.

Outgoing SMTP relay services

Fiddlesticks. I had my somebits.com email all set up right. DKIM and SPF were working, I had a DMARC policy of rejecting unsigned email for three weeks with no problems. And then I broke my setup by cancelling Google Workspace.

Now I’m back but sending email via SMTP2Go. Details below.

I broke it

Last year I set up somebits.com to be on Google Workspace for incoming and outgoing email. And then promptly forgot what I did. Last month I stopped using somebits.com for incoming email because it was not working right. Cloudflare’s email relaying seemed better. So I figured I could stop paying $8/mo for Google Workspace since I wasn’t receiving email.

I forgot about sending email. Without Workspace, there’s no way to DKIM sign outgoing emails I send through Gmail. Gmail will still send email from @somebits.com but it won’t even try to sign them. That’s sort of OK, at least once I turned off my p=reject DMARC policy. But I like the idea of DKIM signed emails.

The easy thing would have been to re-enable Google Workspace. But when you do that you get a notice about how things might not work right for 24 hours. Google’s stupid eventual consistency designs still biting me in the ass, 20 years later. Also I just don’t like Google Workspace, it’s a messy product and does way more than I want. Time for an alternative SMTP sender.

SMTP relay services

The trick is finding a reliable sending service that caters to small legitimate users. Clearly all the business is in helping spammers marketers deliver bulk email. Not me!

I asked several AIs what I should use. My main concerns are correctness of DKIM and SPF and a good reputation so I don’t get blocked along with a bunch of spam customers. Here’s a quick summary of what the AIs suggested:

  • SMTP2Go. Generous free tier of 1000 emails / month, supposedly forever. Good reputation, good service.
  • Brevo. Very generous free tier (9000 emails / month). But some question about reputation.
  • Postmark. The leader for correct + good reputation, in part because they segregate marketing email. But the free tier is only 100 messages a month. If I get to the point of needing to pay $15/mo to deliver email I’ll look at them again.
  • Forward Email. They came up as a relay for receiving mail too. The free tier doesn’t allow sending mail via the relay so I didn’t look further. OTOH $3/mo may cover me, worth a look again maybe.
  • MailerSend. Generous free tier (3000 emails/month). Didn’t look further.
  • Amazon SES. Not interested in the mire of AWS.
  • SendGrid / Twilio. Nah.
  • Mailgun. Seemed good but no real free plan.

I wanted to use Cloudflare since I already use them for receiving email. They did finally launch their email sending service in public beta. But near as I can tell they don’t have an SMTP relay suitable for pointing Gmail at to deliver mail. It’s not really their goal, the purpose of their service is more backend stuff.

Sorry for the half-ass evaluation, I was losing patience. I picked SMTP2Go based on what I saw.

SMTP2Go

So far so good with SMTP2Go. It’s pretty simple. You set up an account, tell them what domain you want to send mail as, then they give you three DNS records and you’re off to the races. One neat trick is the DNS records are all CNAMEs to their servers, no need to configure complex TXT records with nonces in them.

I like their dashboard UI. You can set up different users, manage passwords, etc. It’s all overkill for my small use case but easy enough to work with. I appreciate the rapid view into sent email with logs and reporting and the like.

One weird thing: smtp2go explicitly says you don’t need to set up an SPF record. Instead they are using something called VERP that involves a CNAME, see here for more detail. One of the test tools I tried complained about an SPF failure so I went ahead and added smtp2go as an authorized sender for my whole domain, which shut up that error.

Email receivers for testing

I keep tinkering with my email setup. It’s very helpful to have an email address you can send messages to that gets you some diagnostics. Here’s a few.

Technical tools

dmarctester aka learndmarc. A very cute interactive tool. A little cumbersome for quick testing but there’s a fast forward button. It shows results for SPF, DKIM, and DMARC. It does not show spam score nor the exact message it received.

dkimvalidator: very barebones but good for basics of SPF, DKIM, DMARC. Shows original message front and center. A little hard to read but then again quite complete. I’ll note this flagged an SPF error where others didn’t. I suspect this isn’t supporting the VERP that SMTP2Go uses or if there’s a real problem. (The problem went away when I added a supposedly unnecessary SPF entry.)

mxtoolbox has a responder on ping@tools.mxtoolbox.com. The email reply gives you basics (SPF, DKIM, DMARC) and you can click through for a nicely formatted detailed report. Not much marketing / reputation info. Does show you the exact message received.

Marketing tools

mail-tester.com. Nice mix of technical stuff (SPF/DKIM/DMARC) and content / marketing stuff. Shows your spamassassin score. Tells you if you’re on any major blocklists. Will show you original message. I like the way this tool looks.

aboutmy.email. Marketing-oriented tool. Does tell you about SPF and DKIM, also Yahoo/Google requirements (like an unsubscribe link)

Not useful

check-auth@verifier.port25.com: this tool was great but recently stopped working (April 2026).

restic cheatsheet notes for myself

I use Restic for backups. It’s great! But I forget how to use it, the usability for what I’m doing is not great. I’m using resticprofile as a CLI frontend. Last I looked backrest was a good option for a Web GUI: I should reconsider and switch.

Anyway, some notes on the current setup on my personal Linux box with all my important files. (This is the host tt.)

Configuration

Important stuff is in /usr/local/etc/restic, including passwords (also in 1Password) and profiles.toml

/ and /home/nelson are backed up locally to /mnt/backup/restic (another disk). /home/nelson is also backed up to BackBlaze emulating an S3 datastore in a bucket named “restic2”.

(there’s also backups for other hosts in Backblaze in other buckets and honestly I’ve forgotten what they are for! See Below for update)

Shell setup

alias rp='/usr/local/bin/resticprofile --config /usr/local/etc/restic/profiles.toml’

Look around

rp profiles
rp home.show
rp home.snapshots
rp home.mount /tmp/m

Check metadata integrity

rp home.check
rp root.check
rp bbhome.check

Check local home backups are working by verifying 5% of the data

rp home.check --read-data-subset=5%

Check backblaze backups with read (note: slow)

rp bbhome.check --read-data-subset=1%

Maintenance (slow!)

rp home.prune
rp root.prune
# rp bbhome.prune # may be expensive!

Somebits.com backups (2026-05-11)

My public server somebits.com backs up all of / to BackBlaze via Restic. The details are described in a 1Password note “Restic backup password for somebits.com” and contains a TOML file for resticprofile and the necessary passwords and keys. I tested it today (May 11 2026) and the backup seems to be working.

I also have rsnapshot backups of just /home configured. That doesn’t include /var/www or the important stuff in /etc.

DMARC p=reject

I’m further working to secure my new somebits.com email domain. Today I’m setting a strict p=reject policy for DMARC. If a message arrives claiming to be from @somebits.com and isn’t DKIM signed, the receiver should bounce it. Scary!

Why do this? Because I think all email I’m sending will be DKIM signed, so it’s harmless to my legitimate mail. And it will stop spammers from spoofing mail from my domain. I’m hoping this will also be seen as a positive sign that my domain is not a spam source. Or at least, prevent my domain from getting a bad reputation from people spoofing it. Let’s see.

Details

DMARC and DKIM have been around for awhile but almost no one enforces it strictly. If an email should be DKIM signed but isn’t, email receivers like Gmail will take that as a signal that maybe it’s spam. But they aren’t strict about it.

You can set a DMARC policy for a domain about what to do for unsigned email. A lot of folks run p=none, which means “don’t worry about the signature but send a report if it doesn’t match”. A monitoring setup, you can send error reports to nice consoles like PostMark’s or Cloudflare’s.

I’ve been doing that for a few weeks now and all my emails seem to be properly signed. They should be, I only ever send mail out from Gmail. I have seen some reports of failed signatures but they all look like spammers impersonating me. Today it was an email from China Mobile to mail.ru. Definitely not me.

A lot of folks advise testing the waters by setting p=quarantine first. That tells the receiver to just put the mail in a spam folder, not bounce it. But that means I get no feedback. My theory of jumping straight to p=reject is if anything goes wrong my mail will bounce and I’ll see it. At least, I hope so.

What might go wrong? The usual problem is a bunch of legacy systems are built around spoofing email. Various cron jobs, mailing list software, etc impersonating @somebits.com. But I haven’t done that for years because it’s unreliable. I send all my mail via Gmail’s servers where they are DKIM signed. So I should be good.

Another way to test is pct=25 or the like, to say “only reject 25% of the mail if it’s not DKIM signed”. I can see the value of this for a high volume domain so you don’t break all your customers. But for a personal domain it would just make things unreliable. I either want it 100% working or 100% failing, not for a quarter of my mail to randomly get dropped.

So now we run this way for a few weeks and see what happens. I’m liking Cloudflare’s DMARC reports, they are aggregated daily and presented in a nice dashboard.

Subdomains

Currently I have no setting for the subdomain policy sp=. The default behavior is to follow the p= policy, so now I have sp=reject as well. That means any email for subdomains like foobar.somebits.com will act the same as somebits.com. Which is just fine for my situation, I’m not even using subdomains.

SPF

BTW, all this DMARC and DKIM stuff is different from SPF. DKIM says “this email claiming to be from @somebits.com was signed by a valid somebits.com system”. There’s also SPF, which says “this email for @somebits.com arrived from an IP address belonging to a valid somebits.com system. I do have some SPF failures because various folks are legitimately forwarding email around who aren’t valid SPF senders for my domain. I had this problem for my inbound email and fixed it by using Cloudflare as my MX. They do ARC signatures right which works around the SPF problem.

It’s possible to set aspf=s to tell mail systems to strictly drop any email for the domain if there’s an SPF failure. I can’t imagine that works well in practice. I’m not doing it.

Bottom line: Cloudflare still reports SPF failures but it’s OK. They are often from legitimate activity. And systems are supposed to not drop my mail just because of an SPF failure.

Testing

Gemini helped me test what happens with email that’s not signed. It’s gotten a little tricky to forge email: all the legitimate mailing services don’t allow you!

LearnDMarc is a tool that will forge mail and show you what happens. It’s a little too scripted though, I’m not sure if what I was seeing is real.

swaks is a modern tool for forging mail, a replacement for the old days of just telnetting to port 25. That’s hard to run from a home ISP because they all filter outgoing port 25, but I have a cloud server that still can send email. So I tried sending an email to gmail from me at somebits.com:

 -> Date: Tue, 31 Mar 2026 19:13:45 +0000
 -> To: ******@gmail.com
 -> From: *****@somebits.com
 -> Subject: test Tue, 31 Mar 2026 19:13:45 +0000
 -> Message-Id: <20260331191345.1520151@localhost>
 -> X-Mailer: swaks v20240103.0 jetmore.org/john/code/swaks/
 ->
 -> This should be rejected by DMARC.
 ->
 ->
 -> .
<** 550-5.7.26 Unauthenticated email from somebits.com is not accepted due to
<** 550-5.7.26 domain's DMARC policy. Please contact the administrator of
<** 550-5.7.26 somebits.com domain if this was a legitimate mail. To learn about
<** 550-5.7.26 the DMARC initiative, go to
<** 550 5.7.26  https://support.google.com/mail/?p=DmarcRejection 46e09a7af769-7da0a433fadsi8755951a34.58 - gsmtp
 -> QUIT

Looks like it worked! An immediate rejection from Gmail’s receiving SMTP server. Great!

Email woes again, CloudFlare setup

A few months ago I gave up using monkey.org for my email and moved my email setup to my personal domain somebits.com. I was using Google Workspace as the MX entry for receiving mail for that domain; as of today I’m using CloudFlare. So far so good.

Google Workspace problems

The setup I was using was to pay for Google Workspace and have them receive all mail for my domain via an MX entry. Google Workspace was then told to forward all of it to my personal @gmail.com account. This worked pretty well but every once in awhile friends @yahoo.com or @hotmail.com would complain that a message bounced.

The problem turns out to be the way Google Workspace forwards email to Gmail. They don’t do it right! I’m not confident but I think they’re not doing SRS or ARC correctly. So Gmail receives this mail claiming to be from some random @yahoo.com person and to me@gmail.com, but the mail isn’t correctly signed and so Gmail rejects it as spam. It didn’t happen often, not as often as my old monkey.org setup, but it happened enough to annoy me. Google should be able to forward mail to itself reliably!

It’s possible I could have fixed this by not using Google Workspace to forward the whole domain and instead just to forward individually from my name @somebits.com to my personal Gmail. Some reports suggest ARC/SRS works better in this configuration. I didn’t try it.

CloudFlare Email

Instead I followed an AI’s advice and have switched to using CloudFlare as my MX provider, a feature they call “Email Routing”. (The other option was forwardemail.net). It’s simple but seems good. The free tier is all I need. You can have CloudFlare forward email to specific names @ your domain to specific destination email addresses. There’s also a Catch All forwarding option that’s off by default.

The key thing is CloudFlare seems to be doing ARC and SRS stuff correctly. Email I send to myself from yahoo mail arrives fully intact and properly signed as far as Gmail is concerned. Yay!

As part of this change I also made CloudFlare the nameserver of record for my domain instead of Porkbun. I’m not sure that’s 100% necessary but it makes things easier on CloudFlare. Also they are the best in the business at providing DNS so why not?

One gotcha: CloudFlare email routing doesn’t support subdomains, at least not easily. I wanted to test all this just for test.somebits.com at first but it was either all of somebits.com or nothing.

Another gotcha: CloudFlare rewrites the SPF record for your domain saying only CloudFlare is authorized to deliver email for your domain. This isn’t a total disaster, it’s a soft fail, but it means that Gmail can’t sign mail it sends for you. The solution is to hand edit the SPF record to include both Gmail and Cloudflare as authorized senders. The test address auth-results@verifier.port25.com was a big help in figuring this problem out.

(It’s a bit weird that CloudFlare injects itself in the SPF records because CloudFlare doesn’t yet offer a service that delivers email for you. Ie, no outgoing SMTP. You have to send your mail out via Gmail or someone else. The AI says that ClouldFlare still needs an SPF record so that the mail forwarding is allowed and properly signed. Anyway a hybrid SPF record seems to work fine.)

Update: Cloudflare is better

Cloudflare’s email forwarding is better. All my forwarded email used to show up in my Gmail with failing SPF. Now it shows as passing. I can no longer understand email headers, particularly all the signature stuff, but apparently the difference is Cloudflare is doing the Sender Rewriting Scheme (SRS) whereas Google Workspace does not. According to Gemini the crucial difference is the Return-Path header, which reflects the data sent on the MAIL FROM part of the SMTP exchange:

FeatureEmail 1 (Failed SPF)Email 2 (Passed SPF)
Return-Pathsomeone@hotmail.comSRS0=tzui=rb=hotmail.com=someone@somebits.com
SPF CheckChecked against hotmail.comChecked against somebits.com
ResultFail (Google isn’t a Hotmail server)Pass (Cloudflare is allowed for somebits.com)

I don’t really understand all this stuff. But Workspace seems to be just forging mail when it forwards it to Gmail, pretending to be sending on behalf of hotmail.com. Cloudflare is being more honest that the email is really from my domain somebits.com but still mentions the hotmail addresses. The actual From header is hotmail in either case, that’s the one I most care about since it’s what is displayed.

I still think Gmail should have special rules for accepting email from Google Workspace. But I can see why they don’t, both for technical reasons and for anti-trust reasons. Failing that, why isn’t Workspace doing SRS?

Upgrading Proxmox 8.4 to 9.1

I updated my main Proxmox server today from 8.4 to 9.1. The big change is an upgrade from Debian bookworm to trixie. And of course lots of Proxmox changes on top of that.

This server is the one doing important work. And to make things spicy, it’s a little customized: I have it running an NFS server on the PVE host itself, with a special loop subnet for communication between the Proxmox guest systems (including NFS). I also have Tailscale installed, Proxmox has no first class support for that.

The upgrade went fine. A little scary, as always, but no real problems. They have good docs on it and a nice pve8to9 tool for testing as you go. It’s a little bit of a manual process, I don’t love running sed commands via copy-and-paste and being told “just look at the config file changes and decide for yourself what to keep”. But at its core it’s basically just a regular Debian update and that process is well tested. I did make a rookie mistake of upgrading via ssh without a screen session but I got away with it. (The upgrade process is smart enough not to kill your active ssh session!)

Little hiccups I encountered:

  • I had to hand-edit one apt source to get tailscale on trixie instead of bookworm.
  • I got a very confusing message from the upgrade about /etc/initramfs/post-update.d/systemd-boot being changed and which version did I want to keep. This issue is not in the Wiki (it should be) but it is discussed here. I went with “N”, keeping the old Proxmox version which just got stubbed out with This hookfile has been disabled by proxmox-boot-tool. I’m guessing its contents don’t matter as Proxmox overrides Debian’s boot setup.
  • After the install pve8to9 told me I should remove the systemd-boot package to prevent future upgrade problems. This issue is well documented on the wiki and removing it was fine in my case.

The boot hiccups are scary. Booting in Linux is confusing, Proxmox is doing something even trickier with its own bootstrap and booting from ZFS. And if this screws up your whole system is broken in a hard-to-repair way. But I think the underlying tools are pretty robust. The pve8to9 script also seems to have enough checks and safeguards in place it works as a safety net. I think.

New email setup

Email is the most important Internet service I use. I’ve been using something like email since the mid-80s on BBSes. I had my first networked email in 1988, a very rickety UUCP setup to a local BBS. 1989 at college got me real email, first uunet!ogicse!reed!minar, then minar@reed.bitnet, and finally nelson@reed.edu and proper SMTP. I moved on to santafe.edu and then media.mit.edu along with monkey.org which was my personal email home for nearly 30 years.

Names

This week I’ve moved on from monkey.org. I’m now using somebits.com as my primary email domain. I’ve owned that domain for 20 or 25 years now but have only used it for my web stuff. Now it’s my email address, hopefully for the rest of my life.

I’m not in a hurry to change my email address everywhere. I’m still not fully trusting the somebits.com setup but it seems reliable so far! But it’s an enormous task to change every single Internet account over to a new login email. I’ll be receiving mail at monkey.org and gmail.com for yeas.

SMTP services

Currently I’m hosting somebits.com email on Google Workspace via the usual MX setup. They do a good job of accepting mail for my preferred mail user agent. They also do a good job of delivering email for me. All the DKIM and other antis-apm stuff a modern domain needs works fine on Google Workspace. And the company has a good reputation, so most sites will accept their mail.

Before this switch my monkey.org address was being handled by hostedemail.com, a TUCOWS service. It worked OK for many years but not perfectly. Some of my mail got bounced for not being properly DKIM signed, and some mail never got delivered. Part of my problems were I was just having hostedemail forward to Gmail and that was not 100% reliable.

Mail User Agent

I’ve used Gmail since 2004, when it launched. Before then I used Thunderbird on a self hosted SMTP and IMAP setup. And before then various Unix local mail delivery systems with an emacs mail reader, Berkeley mail, etc. I’m still using Gmail today as my primary email archive and all my mail is sent to or through it.

But this week I switched to Shortwave as a frontend to Gmail. It uses Gmail as the archive and mail services but has its own web app. The webapp is pretty Gmail-like but nicer in lots of little ways. And it’s married to a very good LLM and RAG system so I can do natural language queries about my email like “when is the potluck today?” or “what recipes did I share with my friend Jack?” I’ve written a bit about it already and have more to say. It’s very good but not perfect.

Future changes

This is enough change for awhile! But I still have a couple of other things I’d like to do.

I have old email archives in mbox format going back to 1990 or so. I never did get around to importing them into Gmail and would like to. Now that Shortwave can do a good job talking about those mails maybe it’s finally time.

I’d still like to write my own email search system. Shortwave is a good product, I don’t need to. But I think I could learn something tinkering with my own RAG system. Also maybe do some specialist things Shortwave doesn’t do, like analytics.

DMARC reports

I set up DMARC on my new domain with p=none; rua=mailto:dmarc-reports@example.com. This means “don’t enforce any mail restrictions, but send reports to this address”. Never seen a report before! I sent a few test emails recently and got my first set of reports.

Each of three mail handlers I sent mail to emailed me back a report for 24 hours. Some had no text at all, some had a summary of the contents (like “1 success 0 failures”). Attached in the mail is an XML report in some standardized format. It seems to contain stats aggregated by source_ip with info on what domain the mail claimed to be from and whether it delivered or not. You can also infer roughly where the mails or going from who is sending you reports, although “Gmail” could be any of a zillion people. Anyway overall it looked useful and not too privacy-invading. I imagine there are tools to ingest the XML and track stats. Update: a friend recommends Postmark which I think has a free level.

Every time I try to read more about all the modern spam measures in SMTP I find a bunch of sites catering to spammers. Er, “newsletters”, which I assume 95% of the time means marketing bullshit. It’s clear why they’re the audience with money to be worth writing docs for. But I can’t help the feeling something is wrong when we’ve built so much email infrastructure that is mostly used by and circumvented by the spam industry.

I find it hilarious that spamassassin has a rule that says “any mail signed with DKIM looks a little like spam”. That’s then offset by a bunch of DKIM specific rules that rate the mail less like spam if the signature is valid, matches SPF, etc. DKIM is a net positive in spamassassin. But not entirely!

<?xml version="1.0" encoding="UTF-8" ?>
<feedback>
  <version>1.0</version>
  <report_metadata>
    <org_name>google.com</org_name>
    <email>noreply-dmarc-support@google.com</email>
    <extra_contact_info>https://support.google.com/a/answer/2466580</extra_contact_info>
    <report_id>74417372361908878</report_id>
    <date_range>
      <begin>1756425600</begin>
      <end>1756511999</end>
    </date_range>
  </report_metadata>
  <policy_published>
    <domain>example.com</domain>
    <adkim>r</adkim>
    <aspf>r</aspf>
    <p>none</p>
    <sp>none</sp>
    <pct>100</pct>
    <np>none</np>
  </policy_published>
  <record>
    <row>
      <source_ip>209.85.220.41</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>pass</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>example.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>example.com</domain>
        <result>pass</result>
        <selector>google</selector>
      </dkim>
      <spf>
        <domain>example.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
</feedback>

New domain Google Workspace email setup

I’m setting up my domain somebits.com for my new email address. To do this I’m using Google Workspace to handle email. This turns out to be remarkably complex: Workspace is a quite elaborated product and designed to do a whole lot more than just forward email. I’m ignoring almost all of its features and only using it to forward all email sent to me at somebits.com on to my personal Gmail account (an @gmail.com address).

Receiving somebits.com email in personal account

There’s two ways to do this. You can forward email for an individual somebits.com simply in that user’s Gmail setup. Instead I’m using Workspace tools to forward mail for the whole domain, before it gets to the user’s Gmail. I’m doing a blanket default route (ie: all addresses in somebits.com). There’s way more complex routing rules.

This is the key configuration. In Admin / Apps / Gmail there’s an option for “Default routing”. Here you can tell it that for All Recipients, Change the envelope recipient to any email address you want. I used <my.address>@gmail.com. I also clicked “Bypass spam filter for this message” and “Perform this action on non-recognized and recognized addresses”. I believe this means every single email will go to my personal gmail account.

Sending somebits.com email from personal account

I also want to be be able to send email from somebits.com from my personal @gmail.com. This is just adding another account in to Gmail. It wants to know an SMTP server: I tell it smtp.gmail.com. It also wants a username and password for logging in to the SMTP server. That’s kinda dumb: this is Gmail using Gmail! But they don’t have a special auth path. So I created an app password for it.

Email logs

Workspace has a very useful email log (“Email log search”) for figuring out problems. Note when you load it it says 0 results: you have to click the search button for it to populate.

DKIM and DMARC and SPF

I’ve set up DKIM (to sign mail), SPF (to say who can send mail for my domain), and DMARC (to say what folks should do with improperly signed mail). The Workspace docs for this are pretty good. check-auth@verifier.port25.com is also a big help in testing things. DKIM and SPF seem like basic price of entry now and the main reason I’m using Google Workspaces at all is I can have Gmail in the loop, Gmail is highly trusted globally. DMARC seems more optional, I’ve set up p=none just out of curiosity what reports I’ll get.

Account juggling

I now have two logins: my personal gmail and my new account. Every time I use any Google product I need to be careful which account I’m using. Most Google products have a switcher now. Gmail isn’t so bad. I got tripped up and accidentally turned on Workspace for my personal Gmail account because I didn’t realize which user I was clicking a button as.

Email woes

For nearly 30 years I’ve been using nelson@monkey.org as my email address. The hosting details have changed over time but for nearly twenty years I’ve been forwarding everything into Gmail. Over the years this has gotten worse and worse as email has deteriorated as a medium.

monkey.org uses OpenSRS’ HostedEmail for both sending and receiving email. It seems fine if barebones.

Sending email

The big problem I solved today was that Gmail was sending email itself and just forging the monkey.org address. This used to work seamlessly but over the years a variety of not-very-effective spam fighting technologies have made this harder and harder. The big problem is Gmail cannot sign emails for DKIM as monkey.org and DKIM is increasingly becoming required to have your mail delivered.

Today I got to learn all about SPF and DKIM and DMARC. The autoresponder at check-auth@verifier.port25.com is very helpful for diagnosing problems, there’s also a lot of web based email verifier tools online.

About a month ago Yahoo (and sbcglobal, and pacbell..) stopped accepting email from me. Often mail would just disappear but I did get one helpful bounce.

550 5.7.9 This mail has been blocked because the sender is unauthenticated. Yahoo requires all senders to authenticate with either SPF or DKIM. Authentication results: DKIM = FAILURE - SPF monkey.org with ip 209.85.167.173 = FAILURE. See https://senders.yahooinc.com/smtp-error-codes/#authentication-failures for more information.

This report is bogus: that IP address (from Google) is valid in monkey.org’s SPF records. At least it is right now. But there is no DKIM signature in my email and that’s maybe really why Yahoo bounced it. (monkey.org has a DMARC policy of p=none, which should mean sites accept email without DKIM).

The solution for all this is to configure Gmail to use monkey.org’s SMTP server to send mail so that server can DKIM sign the mail. I hate adding this extra server in the path but there’s really no way around it. It seems to work fine once I figured out the configuration.

Ugh: now a new problem, I can’t send a Google Photos URL to a hotmail friend of mine, it gets bounced as spam, I think by hotmail. This never happened before when Gmail was directly delivering the mail but now that hostedemail is involved, I get marked as spam.

Receiving mail

I’m also having trouble receiving mail.

In my old setup, monkey.org forwarded my email directly to gmail as soon as it was received, I think inside the mailer daemon itself. This forwarded started failing occasionally, silently bouncing mail back without a clear explanation. Not consistently: simple text email from the same sender would mostly get through then one out of ten would bounce. Lots of spam gets through no problem.

We changed it so monkey.org now delivers mail into the OpenSRS HostedEmail webapp. I then configured the app to forward mail to gmail. This mostly works fine, although it is yet more steps to process each message. But some messages still don’t get to gmail. Now instead of bouncing they get left in my Inbox at HostedEmail. It seems about the same pattern as the ones that bounced. My guess is Gmail doesn’t like these messages for some reason and is refusing to accept the forward. At least I can find them in this other inbox.

I may yet configure Gmail to also fetch mail out of HostedEmail via POP3. That may be a way to retrieve the messages when the forwarding fails.

Change my email address?

Part of what’s made this complicated is I don’t control monkey.org. The other folks who use monkey mostly do not use Gmail. No complaint, they have been very generous and reliable, but I’m basically relying on the help of old friends. So once again I consider whether I should change my email address, probably to the domain I use for my blog. I can set that up to be hosted by Gmail pretty easily for $7/month. I think all the configuration is pretty simple, a few DNS records to set up just once.

We are a long long way from the days when you could send email just by telnetting to port 25 and typing. And yet somehow we still don’t have end-to-end encrypted email. Probably never will.

Update: giving up

Sending mail via hostedemail is causing enough new problems that I’m giving up. I’m setting up my blog’s domain for email 100% in Google Apps. Email used to be an open medium. It has now been wrecked by spammers and captured by a few companies.

ZFS on an external USB drive

I’m liking ZFS so much I decided to use it on my new media storage drive. A 14TB external USB drive with video and music files. The serious nerds who use ZFS will tell you that USB is unsuitable and there’s no point in using ZFS without reundancy. Phooey!

It works quite well. You plug the disk in, create a pool on it (with just the one disk), and you’re done. It automounts for you. You can create datasets to segregate data and they automount. (Be aware you can’t efficiently move files between datasets, that ends up being a byte by byte copy.) And as a bonus you get ZFS features like checksums, deduplication, snapshots, etc. It’s nice!

What happens if you unplug the disk? If you unplug while the disk is mounted (“imported”) it’s a total mess. Don’t do that. This is the problem with USB, it can be a bit flaky and act like it unplugs itself, but I think that’s mostly a problem of the bad old days. So far so good!

If the disk is unplugged and the system is rebooted, the directories won’t exist at all. This is different from ext4 or other fstab filesystems. For instance, say /jukebox is my USB disk. With ext4fs I have to do a mkdir /jukebox before mounting, so there’s a /jukebox present on the root filesystem. The mount replaces the directory. If the disk doesn’t mount you still have that /jukebox visible and other stuff might try to use it. Instead if you have a ZFS pool named “jukebox” it just automounts to /jukebox even if that name doesn’t exist at all in the root filesystem. And if it doesn’t mount, that means there’s no /jukebox at all. In my case I’m using these USB disks as bindmounts for LXC containers. Proxmox notices the directory doesn’t exist and refuses to even start the container. I like that failure mode.

Mostly the disk is plugged in though and ZFS seems to work pretty well with it.

(Elsewhere I have a deployed system with ZFS mirroring deployed on two USB disks in the same enclosure. This also seems to work reliably, after one USB hiccup scared me right at the start.)

PiKVM for a remote console

Following up on my efforts for a remote PC console, I gave PiKVM a try. Very impressive! A great first experience: once you find your way to the right docs it is great. This remote console option is a winner and I’m going to stick with it.

Skip down to the section about software if you’re curious what it’s like to use the thing. I spent a lot of time hacking up some hardware to run it so first notes on that.

Hardware

PiKVM runs an Raspberry Pis. The simple thing is to buy an assembled device from them. You get a CM4, video capture device, an ATX power controller, a power supply, and other stuff all in a nice case. I think the V4 Mini at about $300 is what I’d need. It’s not a bad price for the convenience. OTOH at that price you have a choice of other IP KVMs. I’m not sure if PiKVM is the best choice.

Update: I bought the PiKVM Mini v4. It’s a very nicely prepared product, well built and nicely packaged with plenty of cables. The Mini isn’t just cheaper than the Plus, it’s smaller too. Not a huge thing but I appreciated it. I should have just bought this to start, could have saved myself a fair amount of time.

I’m stubborn and wanted to build my own. They have a very nice guide on doing that, including what hardware to buy. I took their recommendations. $50-$100 depending on what parts you may have lying around already.

  • Raspberry Pi Zero 2 W. A tiny $15 computer, these things are very versatile. I had one lying around.
  • A HDMI-CSI bridge. A $30 HDMI capture device. It takes HDMI as the input. The output is an RPi Camera device (Camera Serial Interface).
  • A CSI ribbon cable. $9 for a set of cables, you only need one. This adapts the wider CSI output to a narrower CSI input on the RPi Zero.
  • A quality USB power supply for the RPi.
  • An ordinary Micro USB to USB A cable (maybe with some tape, see below)
  • Optional: an ATX power interface. This seemed complicated to build, I haven’t looked at it.

The drawback with the RPi Zero is both USB ports are busy doing things and it’s not really practical to have an ethernet adapter. I’m OK just using on-board WiFi but obviously that’s not ideal.

Also this camera interface is pretty hacky. They say it’s capable of 1080p@50 maximum, the product page says 1080p@30. Either way it can’t do the bog-standard 1080p@60 that everything expects these days and that could cause a problem. My Linux PC is happily putting out 720p for it and that works fine.

Physical challenges

The ribbon cable is very fiddly to install. this is not a normal consumer connector. I found this video helpful. Basically you have to unsnap something in the connector, stick in the cable, then snap it in again.

It’d be nice to have a case. The parts are all exposed circuit boards and a delicate ribbon cable. And the HDMI and USB cables are heavier than the computer, which ends up putting a lot of strain on that delicate ribbon cable connector.

No one seems to have a case that fits both boards at once but this 3d printed kludge looks plausible. There’s lots of pre-fab cases for the RPi Zero by itself, that might help.

A note on power

The RPI Zero 2 W has pretty squirrely power. The board has one USB 2.0 port just for power and one just for data. But the power lines of both USB ports are hardwired together. This means if you provide power to the power port you may be dumping that power down the data port into the PC you’re plugged in to. Not good! Alternately, if you only plug the data port into the PC then the RPi will more or less manage to power itself off the data port, which isn’t reliable.

For the problem of backfeeding power to the PC, the PiKVM docs suggest taping off the power leads on your USB cable plugged in to your PC. That’s probably a good idea but I haven’t bothered and so far haven’t fried anything. Here’s hoping my PC’s motherboard is robust. OTOH I ordered this USB power blocker: $6.50 for peace of mind.

What about powering the PiKVM just off the data port connected to the PC? It sorta works! In a previous experiment I measured the RPi Zero 2 W using 165 mA when idle at 570 mA at max load. The USB spec promises 500 mA of power from the USB port so it’s almost enough, and in practice probably is enough if you’re not at max load. PiKVM does work and is usable with just data port power. But then it failed on me once and I have no idea why, was it a brownout? Also it makes the PiKVM dependent on the PC’s power and USB ports which is probably not a great thing in a debugging tool. Independent power seems like a good idea.

One last power note: RPis have a WiFi power saving mode that can cause problems for long-running servers like PiKVM. It’s easy to turn off. PiKVM doesn’t by default. (They wisely don’t recommend using WiFi at all.)

Software: Installation and use

The docs are pretty great and easy to follow. Basically you flash an SD card with their OS. Then edit a text file in a FAT32 partition for initial setup options (like wifi password). Then boot and it’s all pretty automatic. From there it’s all a pretty standard Linux experience. Arch, btw.

But I’ll say this, the PiKVM web interface is great. It was very easy to get it up and going and see my PC’s screen and type at the PC. Super easy to do the basic thing. And the screen sharing UI has nice options like shortcuts for sending weird keystrokes (Ctrl-Alt-Del or Alt-PrScr-T).

One weird thing: the PiKVM filesystem is mounted readonly by default. You have to explicitly issue an rw command to switch to read-write, then ro to go back. In practice you almost never need to do this manually, maybe when you’re changing the root password or something.

I’ve noticed the video feed flakes out when the PiKVM system is busy installing upgrades or fetching system logs. (Even when it has a separate power supply). It may be the RPi Zero CPU is just not powerful enough to keep up. Shouldn’t matter in normal use.

Advanced capabilities

There’s lots of cool hacker extras beyond the basic IP KVM. Some things it can do:

  • Tailscale
  • Cellular backup network connection
  • Fancy HDMI and video options. They seem to care about providing a good video feed, not just an adequate one.
  • OCR for the video feed so you can get text of what’s on the screen.
  • Audio and microphone
  • ATX power control so you can reset or power off/on your PC
  • Serial and Ethernet over the USB link to the PC
  • GPIO access on the RPi for special-purpose hacking
  • VNC server
  • An HTTP API
  • Extra hardware for a KVM switch for four devices

It’s a remarkably impressive product.

I noticed my Linux box sees a bunch of USB devices when I plug in the PiKVM: keyboard, mouse, CDROM. And I guess ethernet and serial are also possible if I enabled them.

e1000e: Detected Hardware Unit Hang

The Linux driver e1000e for Intel ethernet adapters has had a persistent problem for years. It can get in a state where it hangs and reports “Detected Hardware Unit Hang”. Sometimes it recovers on its own but recently on my system it started breaking my networking until reset.

Update Nov 2026: Proxmox kernel 7.0.14-28 seems to include a patch very specific to this bug.

The usual advice for fixing it is to disable hardware acceleration features on the adapter. This has a performance impact but is probably small and avoids the problems with the driver and/or hardware. A simple one-off fix of ethtool -K eno1 tso off gso off was enough to help my system, that turns off acceleration for segmentation of packets. But doing that once won’t persist for reboot, for that I like this systemd unit file. Note that script turns off a whole lot of other acceleration features too which may or may not be a good idea. See also discussion here and here and a whole lot of other places.

It’s not clear what the real underlying bug is. Some folks blame bad hardware design. But Linux drivers have lots of code for working around hardware problems, not sure why it’s such a problem in e1000e. The fact that segmentation may be a particular problem doesn’t surprise me. Segmentation is stateful: either the kernel or the hardware has to store some data while it breaks it up into packets and that probably involves locking.

The other confusion is why this bug started happening to me recently. The problem started when I upgraded to Proxmox 8.4.1 with their kernel 6.8.12-9. This bug discussion has a comment noting that one patch to the kernel didn’t get included in that build, maybe that was the problem. Proxmox has since released a 6.8.12-10 which says cherry-pick "bnxt_en: Fix GSO type for HW GRO packets on 5750X chips". But that patch is for “5750X chips”, which I think is a Broadcom part. So maybe not relevant to e1000e at all?

My guess is Proxmox had patched this problem in some kernels but it’s come back. Would love to understand why the upstream Linux release doesn’t have a fix for this once and for all. Even if it’s to default a bunch of hardware acceleration features to off in the driver.

Linux serial console in 2025

I wanted remote access to my Linux PC and decided to try a very old fashioned idea, a serial console. Normally a Linux PC’s console is a keyboard and video device. But it can also just be a serial device. Either an old school DB9 connector on an ancient PC or some modern thing plugged in with a serial connection. Then you need a second device to act as a serial terminal.

In theory the serial device is simpler and is more likely to work even if the network isn’t working. In particular the Linux PC’s kernel is managing the serial console and so as long as Linux is operating, there’s a good chance that serial connection will be.

I tried using a Raspberry Pi Zero 2 W for the terminal, plugged in to my Linux PC via a USB cable.

I got this sort of working and then quit. I realized there’s few cases where a serial connection will really help. Ie: the Linux machine is up but its networking is down, however the whole LAN is still up. It happened to me this week! But I’m going to look for a full IP KVM solution so I can do things even if Linux is busted.

Update: this set of docs may be useful.

Serial connection: USB Gadget / On-the-Go

The first complication: who has a real serial port anymore? I haven’t seen a DB9 in years. It’s all USB ports. And you can’t just plug a USB cable in between two computers because they are both in host mode, not device mode.

There’s hardware hacks for true serial. Plenty of USB-to-Serial adapters out there that give you a DB9 (or an RJ45 with serial). Also RPi hardware has UARTs that you can use with the GPIO pins, hack up your own serial port. All that conversion seemed du mb to me, particularly since I’d need two adapters on either end.

The hack I’m using is OTG / Gadget mode on my RPi Zero 2 W. The micro USB port is an OTG port, you can plug that in directly with a cable to a PC’s USB A socket. The PC is a USB host, the OTG port is a USB device. This actually works! No special cable or adapter needed, just an ordinary USB cable between the two computers. (Mine was male Micro-B to male A.) However, it still takes a lot of doing to get it going.

Getting serial working manually

Here’s how I got a serial connection working manually in Linux.

On the RPi Zero 2 W: steps to enable OTG mode and use the USB as a serial port

  • enable dtoverlay=dwc2 in /boot/firmware/config.txt and reboot
  • modprobe dwc2
  • modprobe g_serial
  • verify there’s a new /dev/ttyGS0 on the RPi

On the Linux server (after the modprobe on the RPi)

  • lsusb and verify there’s something named “Linux-USB Serial Gadget”
  • Verify there’s a new /dev/ttyACM0
  • Run getty -L 9600 ttyACM0 vt100 to create a login prompt on the serial port

Back on the RPi, connect to the Linux server.

This all works! I can now connect from one machine to another via a serial interface.

Proper server setup

The next big step is getting the server to run that console all the time. The simple way is to add ttyACM0 to the list of things that systemd should run a getty on. But that doesn’t catch the kernel. What you really want is to modify the Linux kernel command line to treat this serial port as a second terminal, not just for getty but also for kernel errors, etc. I didn’t do this step.

Proper terminal setup: ConsolePi

Any old serial terminal would work and that screen hack I tried is actually not bad if you only have a single server to connect to. But there’s a fancy OS purpose-built for being a serial terminal with a lot of nice extra features: ConsolePi. The key component is ser2net, that’s a Linux service that proxies all serial ports to TCP network ports. Then ConsolePi wraps that up in a nice UI.

I tinkered with it a bit but didn’t get it working. Honestly I found the docs confusing and was running out of patience. The main snag I ran into is ser2net doesn’t seem to find devices named ttyGS* by default, or at least I couldn’t figure it out. I’m sure that’s hackable.

Update: Conserver may be worth a look as a different app for monitoring serial ports.

Remote console options for Linux on PCs

I want to be able to remotely access my PC Linux box even if Linux is down. Ie: just like you’d do with a keyboard and monitor plugged in locally, but via the Internet. There’s a zillion ways to do this but they are all fiddly and the simplest ways are expensive or unobtanium.

This post is a mess but discusses three remote options.

I left out one useful technology: power control. Some of these solutions let you power cycle the Linux PC, either via the BIOS or via a hardware control. Me, I’m just using a smart power switch.

Remote management

The Big Boy option is to buy server hardware that has remote management capabilities. Some bulletproof mini-OS in the BIOS that you can access over the network. I have a friend who swears by HPE Proliant MicroServers for this exact reason. This isn’t really a Linux console, it’s just a PC that’s better suited for remote server management.

IP KVM

A common hack is to emulate a keyboard, video card, and mouse. You get a magic device (the “IP KVM”) that has HDMI and USB inputs, plug those in via cables to the PC’s HDMI and USB output, and as far as the Linux PC knows it has a normal local display, keyboard, and mouse. Meanwhile the magic device is accepting the video feed and making it available via a network server somehow, also emulating a keyboard and mouse for the PC.

The nice thing about this solution is it’s really a PC level solution, Linux is unaware of it. You can even use it to access the machine’s BIOS.

So what’s the magic device?

There’s a bunch of enterprise-grade IP KVMs out there for $400 or more. The nicest ones are rackmounted. They were more expensive and capable than I wanted so I kept looking.

JetKVM looks very impressive: $70 for a slick device with a web interface. Unfortunately this is not really purchasable. It’s only for sale on Kickstarter, they are way oversold, and they aren’t taking orders for the US.

PiKVM is another magic device option and you see it mentioned frequently because it’s a bit more hacker friendly. But the simplest thing is to buy it for.. yes, about $400. You can also DIY it with your own RPi and an HDMI capture device. I’m about to try this with a $15 RPi Zero 2 W and a $30 HDMI interface that plugs in to the camera port with a $10 cable.

I’ve also run across NanoKVM, a tiny PiKVM based on the LicheeRV Nano hardware. Interestingly the CPU is RISC V. It looks to be entirely a Chinese product so may be a bit tricky to import and understand the code. I sure wish I could read Chinese. Update: SiPeed has a pre-order page in English for NanoKVM.

Update: GL-iNet has a Comet(GL-RM1) for $90

Serial console

Another choice is to go old school and use Linux’ serial console support. This won’t let you access the BIOS of the PC (probably) but it will let you get to Linux the moment the boot loader starts.

On the Linux server end you’ll want to enable a serial console. Eventually you want this serial device to be a console at boot time. For hacking around you can just run a getty on the serial console.

On the other side of the serial cable you need a device that accepts serial and has an Internet interface. ConsolePi is one device for this purpose. It seems quite capable but also difficult to understand.

I have some much more detailed notes on a serial console in another post.

Server outage postmortem

Some notes on a personal server outage. Highlights:

  • Smart power switches are great
  • Would love a remote console of some sort
  • Having any sort of remote shell other than the server would be nice
  • Remote Unifi is helpful
  • My Intel ethernet device / e1000e driver may have a bug
  • A second network interface?
  • I’d sure like a watchdog

I left San Francisco on the morning of Apr 18. At 2:38AM Apr 19 I got notified some of my services running on my personal Linux server there weren’t working. No problem, I thought! This is what Proxmox is for! Only I couldn’t reach the Proxmox hypervisor: the whole machine was down.

Long story short, today (Apr 22) I power-cycled the machine and it came back fine.

Smart power switch

My first thought on the 19th was to reboot the server. Then I went looking for the smart power switch I thought I’d set up and couldn’t find it. I have like 4 brands of switches and apps. And I forgot to check Emporia, the newest one. Mostly that’s my car charger but they have a nice set of smart power switches too. I finally found it this morning (while looking at a list of devices on my LAN), power cycled the machine, and the reboot worked. Yay!

Remote console

I’d sure love a remote console for this server. Something I can log into remotely. I’ve got another blog post coming on options for that, I think PiKVM might be my solution. Next time I buy a server I should buy something like an HPE Proliant with remote management.

Remote Unifi

My Ubiquiti router has remote management with a web interface. I’ve used this more than I thought I would. I used it on the 19th the moment I knew things were wrong. It let me confirm the house Internet was working and that the Proxmox host was no longer on my LAN.

Remote shell

Usually when things go wrong and I’m not home I log into a VM on my server and poke around with diagnostic tools. But with my server down I had no VM to log into. Kinda wish I had a second machine, a little RPi or something. I finally figured out you can get a remote ssh shell on the router via the Unifi console. The Linux environment you get there is very limited but at least I could run ping.

Second network

I should consider adding a second network device, a cheap WiFi adapter, just as a backup. Would be nice to bypass the ethernet switches too.

Watchdog

The root cause of the failure was the networking going down. It’d be nice if my Proxmox server had a watchdog to reboot itself. In this case the computer was fine, just not the network, so that’s a little trickier. In the past every time I’ve set up watchdogs it caused more problems than it solved. The real Proxmox solution is to cluster and use high availability, but I don’t really want to buy more computers.

Root cause / ethernet problem

So why’d it crash? I’m not certain, but here’s the big sign of trouble

Apr 19 09:06:59 sfpve kernel: e1000e 0000:00:1f.6 eno1: Detected Hardware Unit Hang:

That got logged once every two seconds once it started. tailscaled also started complaining it couldn’t connect to the network. Everything else more or less kept running fine, scheduled tasks and backups and stuff. Just no network.

Looking at my logs, this error message has been logged about 150 times in the past year and a half. But in previous times it’s been transitory, a few errors and then it recovers itself without a reboot. This last outage was the first time where it got stuck and didn’t reboot.

Looking online, this error is frequently asked about. I don’t have the stamina to read all the diagnoses of what might be wrong. I did ask some AIs though. The usual cargo cult advice is to do something like ethtool -K eno1 gso off tso off to disable various advanced ethernet device features like hardware supported checksums or segmentation. Also some thought that power management might be a problem. Kind of hate the idea of this. I thought Intel ethernet devices were well regarded and supported in Linux.

I updated Proxmox from 8.3.? to 8.4.1 a few days before this crash. If it happens again it might be a problem with this kernel (6.8.12-9-pve).

Updates

The server crashed again the same way last night at about the same time.

Apr 23 09:08:37 sfpve kernel: e1000e 0000:00:1f.6 eno1: Detected Hardware Unit Hang:

This is happening during the 2am busy cron job window, so it’s possible there’s system load involved. There’s a big backup job running of my primary VM which takes about 8 minutes. The backup does complete! And I’d hope it doesn’t generate network traffic. But who knows. FWIW I was able to run the backup job manually without causing a problem.

After that Apr 23 crash I turned off GSO and TSO and it hasn’t crashed the last two nights. Given the code I’ve read, I’m guessing segmentation is in fact the problem.

I’ve got a separate blog post just about this kernel problem.

Apr 29: got a crash late last night with GSO and TSO turned off. At 04:52:56 UTC (about 10pm local), so a few hours earlier than the previous crashes. So turning those features off helped but didn’t solve the problem. Going to try turning off many more options as in this unit file and see how I do. But still a one-off, I keep hoping Proxmox releases a fixed kernel.
/sbin/ethtool -K eno1 gso off gro off tso off tx off rx off rxvlan off txvlan off sg off

Hacking Proxmox boot process (ZFS)

I’m upgrading my main Proxmox home server from a single SSD with ZFS to two SSDs mirrored in ZFS. Some discussion here. The simple thing is just to reinstall Proxmox new but I’m going to try to do it in-place first. Either way requires careful backups.

The docs on changing a failed boot device are the in-place process I’m following. More or less. It boils down to “set up the new disk in ZFS, then run proxmox-boot-tool to make it bootable”. The blessing process is complicated. Booting with ZFS is always tricky. And Proxmox is rumored to have a special thing where it installs boot loaders on all mirror devices for redundancy. I want that with my new drive! This post is me learning about how it all works.

Summary: this worked very well and is simpler than imagined. Also Proxmox is remarkably well documented. Hurray!

How is Proxmox booting now?

A year ago Proxmox installed something that made it boot from ZFS. Works great. What’s it doing? The challenge is Proxmox has three different ways of booting and I’m not sure which mine is. These docs on using the boot tool are helpful. Some other useful docs here. I should just plug in a monitor and look at the boot process but no, I’m stubborn. The docs say proxmox-boot-tool status will show you the current boot method but the output is not illuminating.

System currently booted with uefi
4B96-7CDC is configured with: uefi (versions: 6.5.13-6-pve, 6.8.12-1-pve, 6.8.12-2-pve)

Yes, it’s UEFI, I knew that. But is that GRUB? Something else? Looking around for advice in docs and from Phind I got some other ideas to try, looking at the EFI boot options:

# efibootmgr -v
BootCurrent: 0002
Timeout: 1 seconds
BootOrder: 0002,0003,0001,0004,0005
Boot0001* UEFI:CD/DVD Drive BBS(129,,0x0)
Boot0002* Linux Boot Manager HD(2,GPT,55f108de-abfa-4dad-b478-641a6d640390,0x800,0x200000)/File(\EFI\SYSTEMD\SYSTEMD-BOOTX64.EFI)
Boot0003* UEFI OS HD(2,GPT,55f108de-abfa-4dad-b478-641a6d640390,0x800,0x200000)/File(\EFI\BOOT\BOOTX64.EFI)..BO
Boot0004* UEFI:Removable Device BBS(130,,0x0)
Boot0005* UEFI:Network Device BBS(131,,0x0)

So that says it’s “Linux Boot Manager”, which is systemd (why doesn’t it say so?). Other docs I read suggest ZFS systems boot from a whole Linux system installed in the ESP. That may involve systemd too. In any case it probably does not involve GRUB. I finally hooked up a monitor and rebooted and saw a menu but it didn’t quite look like GRUB. I did see a message go by about EFI Boot Stub.

Bottom line: I think I’m booting with Linux Boot Manager which involves systemd and a Linux kernel on the ESP partition. Not GRUB.

It’s possible to inspect the boot stuff. It’s on partition 2, the ESP partition in a VFAT filesystem. It has stuff in it like EFI/BOOT/BOOTX64.EFI, EFI/proxmox, and loader/entries.

Identifying the disks

/dev/nvme1n1 is my existing Proxmox boot drive, a zpool with just the one disk in it. I want to add /dev/nvme0n1 to the pool and make it a mirror. But there’s many ways to name a device on Linux and you want a stable name. (Fun fact: the drives on 0 and 1 have swapped between reboots without me changing the hardware.) What’s best?

zpool status -v rpool tells me the status of my existing one disk pool.

        NAME                               STATE     READ WRITE CKSUM
        rpool                              ONLINE       0     0     0
          nvme-eui.002538b22140b542-part3  ONLINE       0     0     0

What is that EUI string? That’s another name for /dev/nvme1n1p3, the “Extended Unique Identifier”. A 64 bit ID, different from the UUIDs, serial numbers, and other identifiers I’ve used before.

I first found this same name with this query: udevadm info --query=all --name=/dev/nvme1n1. But I don’t really know what that tool is. Simpler is ls -l /dev/disk/by-id/ | grep nvme, which shows that nvme-eui.002538b22140b542-part3 is (currently) a symlink to nvme1n1p3. That I understand. So I looked for what linked to nvme0n1 and found that nvme-eui.002538bc3140272b-part3 is the name for the new SSD’s partition 3.

Adding the ZFS mirror disk

OK, time to do surgery on my machine. I am more or less following this guide.

Step 1: clone the partition table to the new disk. sgdisk /dev/nvme1n1 -R /dev/nvme0n1. After doing this the new disk has the same layout as the old one. blkid will show the partitions. (Although confusingly blkid doesn’t show filesystem types: fdisk showed they were labelled as VFAT etc, just like the original disk.) However the UUIDs of each partition are the same too which is not good, we’ll change that soon.

Step 2: give partitions unique UUIDs. sgdisk -G /dev/nvme0n1. Partitions are the same but now they have new IDs.

Step 3: attach the new SSD to the pool. zpool attach rpool nvme-eui.002538b22140b542-part3 $nvme-eui.002538bc3140272b-part3. Why attach and not add? (Edit: add expands storage, attach mirrors it.) Not sure but that’s what Phind told me to do. This pauses a couple of seconds and then returns. zpool status -v rpool shows what’s going on. The ZFS docs suggest that “attach” is a special thing that only directly mirrors devices. I would have guessed zpool add would have been the command to use but that seems to be a more general purpose thing for other configurations with vdevs and maybe RAID-Z.

  pool: rpool
 state: ONLINE
status: One or more devices is currently being resilvered.  The pool will
        continue to function, possibly in a degraded state.
action: Wait for the resilver to complete.
  scan: resilver in progress since Sun Oct 27 19:49:41 2024
        114G / 114G scanned, 2.24G / 114G issued at 2.24G/s
        2.31G resilvered, 1.97% done, 00:00:49 to go
config:

        NAME                                 STATE     READ WRITE CKSUM
        rpool                                ONLINE       0     0     0
          mirror-0                           ONLINE       0     0     0
            nvme-eui.002538b22140b542-part3  ONLINE       0     0     0
            nvme-eui.002538bc3140272b-part3  ONLINE       0     0     0  (resilvering)

Just a bit later it reports resilvered 116G in 00:01:02 with 0 errors on Sun Oct 27 19:50:43 2024. Nice! These SSDs are fast.

At this point the ZFS stuff is all done. The system reboots fine. I did a zpool scrub for good measure and it reported no errors. I’m now getting most of the benefits of ZFS mirroring for data integrity. However there’s still only one boot device: if that fails, I’ll have to recover with some other boot media.

Installing boot stuff on the new disk

Proxmox has extra stuff for making boot more durable. proxmox-boot-tool manages it. See docs here.

Step 1: I verify that the new disk doesn’t have a boot ESP partition. Device names have changed on me after I rebooted, so /dev/nvme0n1p2 is the original bootable partition. /dev/nvme1n1p2 is the new one.

# old=/dev/nvme0n1p2
# new=/dev/nvme1n1p2
# mount $old m
# ls m
EFI  loader
# umount m
# mount $new m
mount: /tmp/m: wrong fs type, bad option, bad superblock on /dev/nvme1n1p2, missing codepage or helper program, or other error.
       dmesg(1) may have more information after failed mount system call.

Step 2: format the ESP on the new disk. proxmox-boot-tool format $new. After this there’s a brand new VFAT filesystem on the partition, it is empty.

Step 3: get Proxmox to install its boot process on the new disk as well as the old. proxmox-boot-tool init $new. This copies all the kernels, etc to the new disk and enrolls it so updates should be written to it. After running this both disks have nearly identical boot partitions.

Step 4 (option): refresh. proxmox-boot-tool refresh. Just a sort of verification thing, shouldn’t be necessary, but it writes the kernels again to all enrolled disks.

Rebooting

It works! On reboot it just loads like nothing’s changed.

In the BIOS I now see more EFI boot options. Linux Boot Manager is now on both disks, other entries are also doubled. The EFI boot menu is totally rewritten and has two extra entries.

# efibootmgr -v
BootCurrent: 0000
Timeout: 1 seconds
BootOrder: 0000,0002,0003,0004,0001,0005,0006
Boot0000* Linux Boot Manager    HD(2,GPT,63a5e06a-3206-4a55-957c-0878a2275a8c,0x800,0x200000)/File(\EFI\SYSTEMD\SYSTEMD-BOOTX64.EFI)
Boot0001* UEFI:CD/DVD Drive     BBS(129,,0x0)
Boot0002* Linux Boot Manager    HD(2,GPT,55f108de-abfa-4dad-b478-641a6d640390,0x800,0x200000)/File(\EFI\SYSTEMD\SYSTEMD-BOOTX64.EFI)
Boot0003* UEFI OS       HD(2,GPT,55f108de-abfa-4dad-b478-641a6d640390,0x800,0x200000)/File(\EFI\BOOT\BOOTX64.EFI)..BO
Boot0004* UEFI OS       HD(2,GPT,63a5e06a-3206-4a55-957c-0878a2275a8c,0x800,0x200000)/File(\EFI\BOOT\BOOTX64.EFI)..BO
Boot0005* UEFI:Removable Device BBS(130,,0x0)
Boot0006* UEFI:Network Device   BBS(131,,0x0)

The real question is what happens if the boot disk fails. Will the system still boot? In theory yes, if you have ZFS mirrors and Proxmox’ magic boot setup. I don’t want to pull the M.2 drive in my machine to test it so I don’t know if it works. There’s two genuine looking boot partitions both listed in the EFI boot menus so I think odds are good.

Things that cause hangs in Proxmox boot / shutdown

I love how Linux has (mostly) fast reboots, 10 seconds or less. So I’ve noticed some slow reboots, a minute or more, that are annoying. What’s happening?

One challenge: when you tell Proxmox to reboot it shuts down all the Proxmox PVE stuff like the Web GUI. That happens immediately. It also asks all the guests to also shut down (maybe at the same time) but that takes longer. Only now the UI is gone so you can’t see what’s happening. I only got some insight by staring at a console plugged in and then reviewing logs.

Another awkward thing: the “shut down all guests” task has no timeout from Proxmox. If one of your guests refuses to shut down I think Proxmox doesn’t reboot, just stays in a mostly-dead state. (Edit: maybe not, the docs mention a 180 second default timeout.) That makes sense in a high availability environment but is not great for my home single server. I don’t think this has ever bitten me but I have everything plugged in to an Internet power switch for just this eventuality.

Slow VM shutdown for a Linux guest

One thing I noticed is shutdowns sometimes take a minute+. The culprit is my big work VM takes forever to shut down Why? It NFS mounts a disk from an NFS server that’s running on the Proxmox host itself. So if the NFS server shuts down first, the client has a hard time unmounting it. (A weakness of NFS). The unmount does eventually time out after 90 seconds and the shutdown proceeds, but it’s a problem.

The root cause here is me running an NFS server on the PVE host: that’s not a great idea. But there’s a similar possible problem if the NFS server is in one guest, the client in another. Proxmox doesn’t do any sort of dependency inference itself although you can manually configure it. At least you can make a guest dependent on another guest, you can’t make it dependent on a rogue NFS server you installed on PVE itself.

I don’t have a fix for this now. I’m working on moving the NFS server to a guest, will revisit then.

Slow boot of Proxmox

Another problem I had started after I added a USB disk as storage, then unplugged it. On boot Proxmox waits to mount that disk again. It times out after 90 seconds. Fair enough but awkward.

Doubly awkward is it kept happening after I had removed the USB disk from the list of storage options. The disk is no longer referenced, why are we waiting? Turns out the mount job was left enabled. That may be a Proxmox bug? I manually disabled it with systemctl disable mnt-pve-extbackup.mount.

Vault: towards my own NAS

Working on rationalizing my file storage now that I’m in a Proxmox universe. The idea here is to put all my important stuff on a NAS VM running the following services:

  • NFSv4
  • Samba
  • Syncthing
  • Restic with BackRest

I’ve got a basic cut at it working (other than Samba) and it seems good. Some notes on what and why.

Contents

What am I storing on the NAS? Very little right now, but the plan is:

  • 14GB of source code. Most of this never changes and it’s mostly small files although some 1GB data blobs sneak in occasionally.
  • 7GB of Windows Documents. Random stuff here but it’s helpful to sync and backup.
  • < 1GB of files on mobile devices. I use Syncthing to get stuff off my Android devices.
  • 4TB of Media archives. NFS and SMB mounted locally. No Syncthing, no backups. Right I am manually rsyncing them occasionally to the second house. I may migrate this to backups (local only, Backblaze is expensive) and Syncthing.

Access over the Internet

The challenge here is I want my files accessible over the Internet, because I have two houses. My house with Starlink is 50ms away from the house with the server (and Sonic fiber). NFS and Samba are only good for LAN access. Those network file systems sorta work over the Internet but it’s slow and awful.

So instead I’m using Syncthing to maintain a working copy of files on my local machine. That makes my setup a lot like what Dropbox or other cloud drives is doing. I’ve done it for years with important stuff including all my source code and it’s worked fine. A key thing here: I am almost never modifying files in two places at once. Syncthing has a conflict resolution system for that but it’s a little primitive.

I’m using Tailscale for now to access the Syncthing server on the vault. That shouldn’t strictly be necessary.

Storage medium

Where are my files stored? On virtual disks that Proxmox provides. Those virtual disks are allocated on a ZFS pool that Proxmox maintains. That way the NAS VM doesn’t need to use ZFS directly, instead it just puts an ext4 filesystem on the virtual disks and it’s simple.

It’s a little weird that ZFS doesn’t see the individual files and the NAS is unaware of the ZFS pool status. But it turns out almost all the advantages of ZFS operate at the block level. Proxmox creates the virtual disk as a ZFS dataset, a block device, and ZFS will happily snapshot and compress and checksum and self-heal those blocks for me. There are a few filesystem-level ZFS features (like ACLs) but I don’t really care about them, so not having them in the NAS is no big loss.

The other option would be to pass through raw disk devices to the VM and let it run a ZFS pool itself. That’s more like what a TrueNAS setup does.

Still on the fence about what physical media I’ll use. So far I’m doing it on a single SSD in the Proxmox server. I think a pair of spinning disks with mirroring makes sense for the media archive but might be a little slow for the NFS clients accessing the source code.

I’m using Restic (with Backrest) for two sets of backups. One of everything to local disk, an extra disk in my Proxmox server. (See this pattern). One leaving out the media archives to Backblaze.

Product design

So far I’m at the “hack config files” stage of building this out. And that’s fine. Backrest and Syncthing already offer Web GUIs. I’d like to streamline the NFS and Samba configs so I don’t have to keep re-referencing the same disk volume over and over in several config files but eh, whatever. I could imagine making this into an actual product other people could use but it’d take a lot of configuration and testing. The VM might also make a good NixOS project.

Why not Cockpit for a GUI? It might actually be a good idea, I’ve never tried it.

Why not TrueNAS or OMV? Partly because I don’t like either very much. Also because neither supports Restic or Syncthing. You can install them in the VM but it’s kind of a kludge and really, I’m OK just managing NFS and Samba myself. TrueNAS can also manage a ZFS array which would be a different storage solution than what I’m doing.

As always with hacker projects there’s a lot niceties of monitoring and alerting I should be doing but haven’t set up yet. At least Proxmox ZFS will tell me if something catastrophic happens to the data.

Wrinkles

One problem with any NAS is managing file ownership. The POSIX file model is very clear for ownership and permissions. But SMB kind of screws that up. And so does Syncthing: it really wants to run as a single non-root user. (Although it has some support for multiple owners). For now I’m going to stick with POSIX files but they’re all just owned by me. That’s a good match for my data. OTOH I am allowing NFS clients to be root on the server, so maybe I can do more when Syncthing isn’t involved.

NFS still sucks for clients when the server fails. I’m mounting with noauto,x-systemd.automount,x-systemd.idle-timeout=60,soft,timeo=15,retrans=2 which first of all, lol, why aren’t the defaults adequate? And x-systemd really? But it seems to work; if the server is down the client will throw an error in under a minute.

Setup details.

The Vault VM is set up to use two vCPUs and 2GB of RAM. There’s a 4GB disk for the system volume (including 0.5GB of swap) and then as many user data volumes as I want.

I’m running Debian 12 on the VM with just the basics installed: nfs-kernel-server, samba, syncthing, backrest. The system seems to be using an actual 400MB of RAM, very little. I think the most RAM-hungry thing is Restic, it likes to do a lot of housekeeping when de-duping backups etc. It might make sense to give more RAM to the NAS just for it to cache files its serving.

Right now I’m mounting the datasets on virtual disks into /mnt/UUID, big ugly names. Then I have a second fstab entry to bind mount from /mnt/UUID to /export/friendlyname. Trying to reference the datasets everywhere else with the /export name.

Some specifics:

  • /etc/interfaces: modified to add 192.168.240.* subnet for sharing within Proxmox
  • /etc/fstab: edited to mount disks into /mnt and bind mount into /export
  • /etc/exports: individually names each /export filesystem so NFS will send them
  • /etc/default/nfs-kernel-server was modified to be NFSv4 only. Debian has some docs on this but they seem to be badly out of date.
  • Backrest config is mostly in ~root/.config/backrest, also the systemd unit file. The GUI manages that.
  • Syncthing runs as user nelson via systemd user (with loginctl linger enabled so it runs without me being logged in). The GUI manages configs, they are stored in /home/nelson/.local/state/syncthing

Setting up Gotify with Proxmox

Continuing my search for some sort of notifications infrastructure, I set up Gotify to use with Proxmox and other services like BackRest so I get messages in a central place from my servers when things go wrong. I don’t love Gotify but it’s what works with Proxmox so I’ll start there.

The goal here is to get https://example.com/gotify/ working both for the Web GUI and as an endpoint for Gotify clients including a message destination and the mobile app. I used to use Tailscale but it’s nice to have the Gotify server on a publicly accessible address. It looks designed to be secure for that.

Step 1: install Gotify as an LXC container in Proxmox with the tteck script. This ships with no config file but the defaults are reasonable (you configure passwords and stuff in the GUI). Note that means no SSL support. Gotify actually has reasonable SSL including Lets Encrypt integration but I didn’t use it.

Step 2: use Caddy as a reverse proxy to forward to Gotify. Not necessary but useful for my setup where I have a public Caddy server brokering access to other stuff. The Caddy config is a bit fiddly but is well documented here. Caddy has to strip the URL prefix so Gotify doesn’t see it.

Step 3: configure a new application in Gotify and make note of the token.

Step 4: in Proxmox go to Datacenter > Notifications and add a new target. Paste in your token. The URL will look something like https://example.com/gotify. Note the lack of trailing slash: if you leave it in both Proxmox and Gotify are dumb about it and you get a confusing error. Press “Test” to verify the messages get through.

While I’m here... looking for a good solution to get notifications in Gotify from emails. There’s a zillion SMTP-to-Gotify gateways out there that obviate the need to have actual working mail delivery. This one looked promising on last review, simple and updated recently. I haven’t tried it. It doesn’t seem to have any sort of authentication so a bit worried it’ll collect spam if you run it on a public address.

Update: a quick test shows smtp-gotify works fine for email. I built it as a Go program and then just ran the binary, configured via a few environment variables. The Dockerfile in the project helped figure it out. The simple way to use it is set it as you SMTP host to send mail to. Which I’ve forgotten how to do simply in random Linux machines, need to read up on it.

backrest GUI for restic

I’ve been using Restic for backups for most of a year now. It’s terrific. But Restic is a bit of a low level tool, using it requires some fiddly config files and setting up cron jobs, etc. There are a bunch of frontends to Restic that turn it more into a user product. I’ve been using resticprofile but don’t love it, it’s confusing and awkward.

Backrest is new bae. Turns out I want a web GUI for this kind of thing, who knew? It has a very nice and simple structure for configuring Restic. You create repositories, then you create plans. There’s good GUIs for configuring things like retention policies, cron schedules, etc. It runs persistently to provide the web GUI and takes care of launching restic as needed and making things happen.

Remarkable number of grace notes too. I love that every configuration screen has an option in the GUI to show it as a JSON file, making it easy to keep track of what’s actually happen. Also it has remarkably good live web updates. Not just showing you a job is running but specific status output updated once a second to see, say, how many files of the backup have been completed so far.

It’s just a really nicely developed product.

Using a simple USB disk for Proxmox backups

Trying a delicate thing here. I have a USB disk I want to write backups too. Mostly I want to back up precious data from a Proxmox guest system (an OpenMediaVault VM with user files, backups written to it with rsync and restic). I also want Proxmox to write backups of guest systems to it. There’s a bunch of ways to do this.

I decided to complicate it by having a constraint of simplicity. It’s important to me that the USB disk with the backups be as simple and ordinary as is realistic. That means no ZFS, no QEMU virtual disks, no weird partitioning. I want the USB disk to be as simple as possible so someone could plug it in to Linux box and get the files off it.

The solution I landed at was to use GPT partitions and ext4 filesystems. There’s a 1TB partition for Proxmox, it will connect it to storage as type “directory” and write backups to it. And there’s a 10TB partition for the OMV VM to write backups to with software running in the VM. It seems to work!

Preparing the disk partitions

This is all generic Linux stuff. I used gdisk on the PVE host to partition the disk. I just used fixed partitions: I didn’t use LVM or something to make the partitions more flexible. I also didn’t use any Proxmox tools to set up the storage because they all seemed complicated or unsuitable.

1TB Proxmox backup partition

This part’s also pretty generic Linux. I made a filesystem with mkfs.ext4 /dev/sdd1. Then I edited /etc/fstab on the PVE host to mount it:

UUID=6ad88c2a-3a59-4d8f-a887-344e69c6711d /mnt/12tb-backup-usb ext4 defaults,nofail,x-systemd.device-timeout=15s 0 2

I don’t love this part, I’d rather not customize Proxmox config files. But this seems unavoidable, Proxmox doesn’t have a managed GUI for “just mount this partition for me”. The fstab works fine, I’ve done something similar on another server for most of a year.

Once I mounted the new filesystem I used the Proxmox GUI to add a new Storage named “usbbackup” of type “Directory” and pointed it to /mnt/12tb-backup-usb. Now Proxmox’ backup systems will write backups to it. Yay!

10TB OMV partition

This part is trickier. Conceptually it’s not hard: I just pass through the disk partition to the VM for it to use. But it’s a little weird.

First thing is finding the partition. I don’t want to name it /dev/sdd2 on the Proxmox host because that could change. I finally figured out it has a more stable name in /dev/disk/by-partuuid/. Not /by-uuid/ which you normally use, that’s for filesystems and we don’t even have one yet, we want the partition.

There’s no way in the Proxmox GUI to pass through a partition to a VM guest. It’s got a great GUI for creating virtual disks or passing hardware devices. Fortunately there’s docs on how to do it with the command line. The command I used is:

qm set 101 -scsi2 /dev/disk/by
-partuuid/14db8691-9229-407f-bb55-a693c1a92f70,iothread=1,backup=0

Note I added options for iothread=1,backup=0. That matches the other virtual disks that Proxmox created for me, and I think those are good choices. (More efficient I/O and don’t include the disk in Proxmox backups.) Here’s what my virtual drives look like in the GUI afterwards. The other two disks are QEMU images Proxmox manages for me.

With this done the 10TB partition /dev/sdd2 that Proxmox has now looks like /dev/sdc in the OMV VM. Note there’s no partition number, as far as the VM knows that device is a whole disk and not just a single partition. But I don’t want to make a partition table in that /dev/sdc. I think you can nest GPT partitions but that complicates things.

So instead I just ran mkfs.ext4 /dev/sdc inside the VM to turn the whole (virtual) disk into a filesystem. Then it shows up in /dev/disk/by-uuid and OMV can also mount it and use it via the GUI. I probably could have used OMV to create the filesystem, for that matter.

As an extra test I also shut down the OMV VM and then mounted the partition temporarily on the Proxmox host. Just to verify I could read the files. A real test would be to take the drive to a different computer entirely but that would require me driving somewhere to touch it.

I love how flexible all these systems are. Also appreciate being able to mix my old school sysadmin knowledge with some modern virtual systems stuff. It’s all quite productive.

telegraf ping in unprivileged LXC containers

Quick hint for solution for pinging in native mode from telegraf in an LXC container:

setcap cap_net_raw+ep /usr/bin/telegraf

I use telegraf to run pings for monitoring networks. You can run it in a tiny Alpine LXC container in Proxmox. But there’s a permissions issue with unprivileged containers that results in status code 2 being logged to Influx and errors like these for native pings and exec pings:

Aug 18 22:32:00 influxdb telegraf[865]: 2024-08-18T22:32:00Z E! [inputs.ping] ping failed: permission changes required, enable CAP_NET_RAW capabilities (refer to the ping plugin's README.md for more info)

Aug 18 22:38:00 influxdb telegraf[896]: 2024-08-18T22:38:00Z E! [inputs.ping] Error in plugin: host "192.168.68.1": exit status 2 - /usr/bin/ping: socktype: SOCK_RAW
Aug 18 22:38:00 influxdb telegraf[896]: /usr/bin/ping: socket: Operation not permitted
Aug 18 22:38:00 influxdb telegraf[896]: /usr/bin/ping: => missing cap_net_raw+p capability or setuid?

What great error messages, whoever wrote that deserves a peer bonus. It’s almost enough to solve the problem! Turns out LXC containers are locked down and by default can’t manipulate raw packets. But ping needs to be able to do that. The solution is to give the binary doing the pinging the raw network capability:

setcap /usr/bin/telegraf cap_net_raw=ep

You can verify it took with getcap /usr/bin/telegraf. If you need exec pings you can make it work with setcap /usr/bin/ping cap_net_raw=ep

Here’s the weird thing. Root inside the container isn’t trusted. So why can root inside the container elevate the privileges of an executable in the container? Why does the hypervisor allow that?

The other weird thing: /usr/bin/ping in the container does not have this capability set in my Debian installs. But ping works anyway, you can ping from the container in a shell as root. However if telegraf tries to ping using that same binary, it doesn’t work.

I suspect the issue is telegraf is not running as root inside the container, it has its own user. Indeed, sudo -u telegraf ping 8.8.8.8 gives an error (unless you set the capability). I still don’t understand why root inside the container is trusted though. I must not understand what “untrusted ” really means in LXC.

Another USB failure (OWC enclosure)

Ugh, right after writing a big blog post about how I’d made a reliable USB storage array, it failed. I was making a backup with Restic from the RAID array to another USB disk and both disks in the RAID failed. The simple kernel reset didn’t work either. So ZFS suspended the pool and everything broke. A reboot took 10 minutes but it’s all back and I don’t think I lost any data. But ugh, now I don’t trust this hardware.

The problems start when a read command from UAS fails on drive sdc. 30 seconds later the kernel resets the device, at the same time there’s a read error from the other drive sdb. It’s at this point everything breaks. The reset doesn’t work and so the devices are both taken offline. That causes I/O errors that ZFS notices and it suspends the pool immediately.

Just after the pool is suspended both disks come back online with new device names (sdd and sde). But ZFS doesn’t just magically assume these are OK. 122 seconds later the kernel notices some tasks have been blocked and complain.

I don’t see any errors in journalctl in the VM guest that’s using this ZFS pool. Unfortunately the kernel logs didn’t persist after a reboot so I can’t check there. It looked like the backup process was still gamely trying to run, it wasn’t even in Device Wait, but I’m not sure.

I think I might have been able to recover from the command line with zpool clear or the like. But I figured rebooting Proxmox would be simpler. That took 10 minutes after I pressed the button on the Web GUI. There’s about 6 minutes of shutdown in the logs as it’s timing out on various things that are unhappy their disk went away. Then there’s an unexplained 4 minute gap from the last log line written during shutdown to a new log line for the kernel coming up again. Afterwards the reboot went smoothly, stuff was working again in 15 seconds or so.

Very frustrated. Particularly that in this case the kernel reset didn’t work: with previous USB errors things mostly recovered. It’s like the whole USB enclosure just failed. Which is actually quite a plausible explanation.

Update Sep 7: three weeks later I haven’t seen another error from these disks. Mostly just light use but I’ve taken two full backups, one with rsync and one with restic (the thing that triggered the error before). I’m running restic with a single CPU thread and read concurrency 1, so it doesn’t hit the disk as hard.

I don’t know what conclusion to draw from this. We’re going to keep using the disks in the USB setup for now. But if I ever set up another serious ZFS array I won’t use USB for it. Common wisdom it’s a bad idea and I’ve now had enough problems I respect it.

USB drives for Linux servers

A summary of what I’ve learned using USB drives to make a little NAS server with Linux.

The serious guides will tell you “don’t use USB for storage”. They’re probably right: USB adds an extra layer, the SATA/USB interface. And those chipsets seem pretty flaky, the last thing you want in a storage system. With most of the hardware I tested the Linux kernel would throw errors every 30 minutes or so and reset the device.

OTOH it mostly seems to work and not corrupt data. I finally found an enclosure that hasn’t thrown an error (yet).

Update: lol, not an hour after publishing this I got a failure from the enclosure I thought was good. A Restic backup (which is read intensive) triggered the failure. It didn’t even reset correctly, so the disks went offline and ZFS suspended the pool. ARGH!

If you have a SATA or Thunderbolt interface by all means use that instead. Related: Host Bus Adapters. But if USB is all you got, here’s some notes.

Drive types

I’m focusing here on spinning 3.5″ drives, Western Digital Red Plus. These drives are the best inexpensive option for storage that’s cheap and big. Sequential throughput is pretty good on these, at least 100MBytes/s. SSDs are great but are 3-4x the price for the size. 2.5″ spinning drives are also nice but max out at 5TB. Also they use SMR media which has weird performance and reliability issues. 3.5″ drives still come in CMR.

Enclosures

The enclosure takes a 3.5″ SATA disk and gives you an interface: USB, also maybe eSATA or Thunderbolt. Small enclosures are simple and take a single disk. Bigger enclosures allow you to plug in many drives with a single USB cable. They often include a hardware RAID chipset you probably won’t use (JBOD is preferred for ZFS). If you put it in JBOD mode Linux will see multiple separate hard rives on a single USB interface.

Enclosures provide power via a separate transformer (do not rely on bus power for 3.5″ drives.). I’ve heard that the quality of the power supply varies significantly and matters a lot: a power blip screws things up. I don’t know more about it. One nice thing about 2.5″ drives is they can be bus powered, simplifying things. If you don’t need big fast storage consider 2.5″.

Many enclosures don’t provide power again if there’s a power outage. They have a stupid pushbutton you have to physically press to turn it back on. Look instead of enclosures with rocker switches that come on automatically.

Enclosures also provide cooling. Cheap ones are just aluminum boxes with passive radiating. That seems OK for one disk but not many, I saw temperatures up to 55°C with two disks in a Yottamaster. The OWC enclosure I’m using has a small fan that makes a huge difference, max temperature like 36°C.

The big problem is finding a reliable enclosure. I spent a lot of time stress testing enclosures and found the older USB 3.0 ones from Yottamaster and SABRENT had kernel errors. A newer 3.1 enclosure from OWC seems more reliable, it is my preference now.

USB versions

USB 3.0 provides 5Gbps or 625MByte/s, much faster than a spinning disk. So any 3.0 interface is fine for a single disk in terms of throughput.

USB 3.1 and 3.2 can provide 10Gbps or 20Gbps. That shouldn’t matter for a single disk or really even two in an enclosure. OTOH I saw some evidence that two 5Gbps separate enclosures was twice as fast as a single 5Gbps enclosure with two disks, not sure what that means. I didn’t test with 10Gbps or 20Gbps links.

However, there’s a theory that newer chipsets are more reliable, that some of the bugs in older systems have been worked out. So I’m going to avoid USB 3.0 enclosures and favor those that offer USB 3.2, or at least 3.1. Even better is eSATA, Thunderbolt, or USB4. If you have an interface on your computer for those you should use them instead of USB.

Cables

USB cables matter! It’s very easy to use a crummy cable and only get 480Mbits/s instead of 5000. The quick advice is “look for a blue connector”. Use lsusb -t to verify the speed you’re getting. Be particularly wary of C-to-A cables, a lot of them are really for charging and are slow for data.

UAS vs usbstorage

usbstorage is the old Linux kernel module for USB disks. My older 2.5″ drives are using it. It seems fine.

uas is the new Linux kernel module for newer USB disks. UASP is basically SCSI and should perform better. Linux will use this module automatically if the drive supports it.

usbfs turns up on Proxmox if you pass through a USB device to a guest. I have no idea what it does, nothing seems mounted with it.

SMART

USB devices are supposed to support SMART but it’s kind of tricky. I need to do more research on this.

My old usbstorage drives work out of the box with SMART. With my newer UAS devices smartctl complains /dev/sdc: Unknown USB bridge with some enclosures. The quick hack is to run smartctl -d sat, which will probably work. There’s a more elaborate thing where you teach the SMART software about your drive type but I haven’t tried it.

Performance

Long story short how is USB performance? Pretty good, I think for sequential reads and writes I can get close to the spinning disk speeds. 100-150Mbytes/s, at least. Random access is slower of course and I saw some confusing results that depended on buffering. The final RAID mirror setup I have can do about 20MBytes/s read, 14MBytes/s write with an aggressively random access pattern. I don’t know whether USB is adding significant overhead or not.

FIO stress test of NAS options

This blog post is a very long record of my testing of a disk array. I’m building a cheap NAS with 2 USB disks (8GB, 5400RPM) in a ZFS mirror configuration plugged in to an N100 MiniPC with 5Gbit USB links. I’m trying several enclosures: a Yottamaster dual bay, two SABRENT single bays, and an OWC dual bay. My main goal here is to find a reliable enclosure. (Spoiler: it’s the OWC.)

I’m running everything on Proxmox. Most of my tests are with Proxmox managing a ZFS pool and creating a virtual disk it passes in to an OpenMediaVault VM (aka OMV). Then I CIFS/SMB mount the disk back on the Proxmox host for further testing. I also did a bit of testing with TrueNAS in a VM where Proxmox just passes the USB disks in as devices for TrueNAS to manage a pool on.

Conclusions

  • Two of three USB enclosures generate kernel errors. Under heavy load there will be a command failure followed by a USB reset about every 30 minutes. In all cases the system recovers and it looks like no data is lost.
  • The OWC enclosure generates no kernel errors. It is also the lowest temperatures.
  • Throughput is wildly variable, sometimes transfers stall. I assume it’s buffering.
  • Network filesystems buffer even if you set various modes telling them not to.
  • TrueNAS seems to have better throughput than OMV. I didn’t test carefully.
  • TrueNAS is unusable with the Yottamaster enclosure, too many errors. It sort of worked with the SABRENT. Didn’t try the OWC.
  • The Yottamaster enclosure is unsuitable. Doesn’t turn itself on after a power outage, also not adequate cooling.
  • The SABRENT enclosures are OK. I don’t love having two power supplies. There were a few more errors in my testing but maybe that was just bad luck.

Decisions

  • I’m going with the OWC enclosure.
  • I’m going to stick with Proxmox ZFS and OMV for the NAS. There’s evidence TrueNAS performs better but I’m nervous about its complexity. Also feeling burned after the bad first experience with the Yottamaster enclosure although that’s probably the USB device’s fault.

The test job

I’ve been enjoying learning fio, the disk throughput tool, mostly because it has very good docs. Which means not only can I read them but the AIs can too. Phind gets it wrong sometimes though so I’m mostly hand-crafting my own fio setups now.

I cooked up a job file (see below) which I’m using as a small stress test as I try different USB hardware and ZFS / virtualization / network file system configurations. My main goal here is to run it for a long time to see if the disks fail in some way, also to measure temperature. I’m less worried about the actual throughput although it’s interesting.

The job file defines a job against a 1GB file. Random reads and writes of blocks from 4k to 1M. Up to 16 in parallel (io_depth), direct I/O enabled. (Note direct=1 means O_DIRECT which doesn’t actually work over a network file system. Oops.) I’m running two jobs in parallel for 15 minutes.

In general I’m seeing throughput of about 28MB/s both read and write, maybe 130 IOPS. That’s whether native on the ZFS machine, through VM disk, or through SMB to the VM disk. (Presumably seek time is dominating.) Not very fast but this is a random access test on a spinning disk. (Sequential gets up to 250 MB/s).

Weirdly I’m seeing more like 100MB/s with an SMB network mount. I’ve chalked this up to me not understanding caching in network file systems. Details below.

Here’s my results from several hours of testing. fio was run on Proxmox natively (which owns the ZFS pool), then on a OpenMediaVault VM (OMV) which gets a virtual disk from Proxmox, then from the Proxmox host itself that has SMB mounted the share from OMV. I also did a few tests with a different configuration: TrueNAS managing the two USB disks directly as USB devices and exporting over SMB.

Measurements

Tests with various enclosures, then some extra scenarios with the OWC enclosure.

OWC results

The hardware is a Mercury Elite Pro Dual, USB 3.1 at 5GBit, UAS. This device can do RAID bit I have it in JBOD mode, “IND”. PITA to get the disks installed, the mechanical design is not great, but it seem sturdy and has a little fan. It also advertises USB 3.1 (5Gbit) and there’s a theory that newer USB revisions imply newer, better chipsets.

Smartctl requires -d sat to work.

Max temperature: 34°C, the fan really helps. The disks are pretty noisy, the enclosure does nothing to dampen the sound.

No errors from the kernel! Haven’t seen a single UAS error after several hours of testing, unlike the other enclosures.

Throughput

  1. Proxmox ZFS native run 1: 21.0MiB/s read, 13.0 write, 97 IOPS.
  2. Proxmox ZFS native run 2: 21.4 read, 13.6 write.
  3. OMV: read 24.9 write 13.6, 109 IOPS
  4. SMB client of OMV run 1: read 122 MiB/s, write 66.5 MiB/s, 552 IOPS.
  5. SMB client of OMV run 2: read 133 MiB/s, write 72 MiB/s

The ZFS native test seems pretty slow at 21/13, it’s the slowest of the three enclosures I tried. Although that’s not that much slower than the Yottamaster dual enclosure test at 28/18. hdparm -t (a simple sequential test of a single drive) shows 210MB/s, so it’s not totally broken.

Yottamaster results

Yottamaster PS200U3. One dual disk USB enclosure at 5Gbit USB 3.0, UAS.

smartctl works out of the box on Proxmox, needed -d sat in TrueNAS.

Max temperature: 52°C. Noisy too.

Kernel errors: while testing over about 90 minutes I got one driver reset of a read command.

Throughput

  • Proxmox ZFS native: read 28MiB/s, write 18MiB/s, 131 IOPS.
  • OMV run 1: read 27MiB/s, write 15MiB/s, 122 IOPS. (Had a reset!)
  • OMV run 2: read 28MiB/s, write 16MiB/s, 127 IOPS.
  • SMB client of OMV run 1: read 98MiB/s, write 53MiB/s, 443 IOPS.
  • SMB client of OMV run 2: read 104MiB/s, write 55.7MiB/s, 470 IOPS.

SABRENT results

Two single disk SABRENT EC-KSL3 USB enclosures at 5Gbit USB 3.0. UAS. I’ve been using a third one of these for a week+ with good luck.

smartctl requires -d sat in Proxmox

Temperatures: 41. Quietest of the three.

More errors, but throughput looks good. While testing got an ugly UAS reset in the VM fio run. From the first error it took 54 seconds before a reset came through. OTOH it didn’t seem to affect throughput. Only one disk got reset, don’t know what ZFS does about that. A second reset during the SMB mount test, again not hurting throughput. Weird.

I also got a new kind of error I’ve not seen before, maybe related to erasing blocks? This error doesn’t end up in the SMART log.

[Mon Aug 12 01:28:06 2024] sd 1:0:0:0: [sdd] tag#0 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK cmd_age=0s
[Mon Aug 12 01:28:06 2024] sd 1:0:0:0: [sdd] tag#0 Sense Key : Illegal Request [current]
[Mon Aug 12 01:28:06 2024] sd 1:0:0:0: [sdd] tag#0 Add. Sense: Invalid command operation code
[Mon Aug 12 01:28:06 2024] sd 1:0:0:0: [sdd] tag#0 CDB: Write same(16) 93 08 00 00 00 00 00 02 fe 90 00 00 09 70 00 00
[Mon Aug 12 01:28:06 2024] critical target error, dev sdd, sector 196240 op 0x3:(DISCARD) flags 0x800 phys_seg 1 prio class 0

All in all 3 kernel errors compared to just 1 with the Yottamaster for the same amount of testing. Feels bad man. The fio verify didn’t find any problems though. I ran a ZFS scrub and it didn’t find any problems.

Throughput

  • Proxmox ZFS native: read 58, write 37, 266 IOPS.
  • OMV run 1: read 60.3 write 33.5 , 270 IOPS. (Had a reset!)
  • OMV run 2: read 59.8 write 33.7 , 275 IOPS (No reset).
  • SMB client of OMV run 1: read 128 MiB/s, write 68.4 MiB/s, 578 IOPS.
  • SMB client of OMV run 2: read 145 MiB/s, write 75 MiB/s, 658 IOPS.
  • SMB client of OMV run 3: read 133 write 68. (Reset)

Note the Proxmox and OMV throughput is better, maybe 2x what I got with the dual bay enclosures. Is that as simple as it being because I’m using two USB ports and two 5Gbit connections? (The max throughput I’ve seen is about 200MB/s or 1.6Gbit, well under a single 5Gb wire, so it’s not as simple as max bandwidth.) OTOH I’ve gotten more errors and more variety of errors. But all the data seems to be correctly being read and written.

TrueNAS tests

In addition to testing enclosures I did a couple of tests with TrueNAS managing the ZFS pool using USB devices passed in from Proxmox. This failed catastrophically with the Yottamaster enclosure, far too many errors. These tests are with the SABRENT. I didn’t try the OWC with TrueNAS.

The main thing I was wondering was what sort of errors I’d see, if any. I saw only one error with three 15 minute runs on TrueNAS, about halfway through a VM test. Write(16) commands failed and it reset about 30 seconds later and seemed to carry on fine.

Throughput

  1. TrueNAS VM run 1: 122MiB/s read, 64 write, 550 IOPS
  2. TrueNAS VM run 2: 137 read, 72 write
  3. SMB client of TrueNAS VM: 138MiB/s read, 76 write, 630 IOPS

I’m less worried about throughput comparisons to OMV, I care most about stability. But compared to the Proxmox ZFS + OMV solution it seems both faster and with less jitter. That is not surprising but should be confirmed more.

SMB and buffering tests

I tried to understand more what was going on with the SMB clients being faster than local writes. It’s definitely related to O_DIRECT and other synchronous writes not being enabled on network filesystems. Most of my tests were with direct=1 in FIO but that doesn’t really mean anything on an SMB mount. Forcing sync writes slows the network tests way down.

I ran some 1 minute tests of different configs on the VM writing to its virtual disk. The FIO test set was 1GB which might fit in caches or might not. I noticed the second time I ran the same test it was much faster, which suggests warming up the caches is a big factor in a 1 minute test.

  1. direct=1, end_fsync=1 (like most tests): 15MiB/s read, 16 MiB/s write.
  2. direct=0, buffered=1, end_fsync=1: 15MiB/s read, 15 MiB/s write.
  3. fio defaults (buffered and no fsync, I think): 13MiB/s read, 13MiB write.
  4. sync=1, fsync=1: 3.2MiB/s read, 3.7MiB/s write.

I can’t make much sense of these local results: even with full buffering I can’t get to the 100MiB/s the disk is capable of. Maybe it’s a virtualization issue, or the client workload being on the disk. The VM has 4GB of RAM allocated which I think should be enough to cache a 1GB working set.

I also re-ran these tests on the SMB host. I ran the first one twice and took the second result.

  1. direct=1, end_fsync=1 (like most tests): 102MiB/s read, 64 MiB/s write.
  2. direct=0, buffered=1, end_fsync=1: 110MiB/s read, 72.9 MiB/s write.
  3. fio defaults (buffered and no fsync, I think): 160 read, 118 write.
  4. sync=1, fsync=1: 3.0 read, 3.3 write.

These results suggest that the network filesystems are caching even in most IO modes that say don’t. That’s fair, it’s a real world result for a network client. Forcing sync and fsync does slow it down as expected.

To be honest, I don’t really understand all of what’s going on here, I don’t know FIO or network filesystems well enough to fully sort this out. Given my main goal was stability testing, eh, I’m OK with my ignorance for now.

Application testing

I did a bunch of real world testing, writing via SMB to the OMV VM with the OWS enclosure.

  1. Linux rsync of a music library: 21MB/s.
  2. Linux dd writing 16GB from /dev/urandom: 70MB/s
  3. dd reading 16GB of random: 182MB/s
  4. dd writing 16GB from /dev/zero: 188MB/s
  5. dd reading 16GB of zeros: 718MB/s
  6. WSL (drvfs) reading 16GB of random: 42MB/s
  7. WSL (drvfs) writing 1GB of random: 39MB/s
  8. Windows explorer reading or writing 1GB of random: 112MB/s

The FIO job file

[stress]
name=stress
description=Nelson small stress test

runtime=900
numjobs=2
time_based=1

rw=randrw
verify=crc32c

bsrange=4k-1M
size=1G

ioengine=libaio
iodepth=16
direct=1
end_fsync=1

Example output (from an OMV VM run)

This run had a kernel reset in the first minute or two.

stress: (g=0): rw=randrw, bs=(R) 4096B-1024KiB, (W) 4096B-1024KiB, (T) 4096B-1024KiB, ioengine=libaio, iodepth=16
...
fio-3.33
Starting 2 processes
Jobs: 2 (f=2): [f(2)][100.0%][eta 00m:00s]
stress: (groupid=0, jobs=1): err= 0: pid=128236: Sun Aug 11 21:42:17 2024
  Description  : [Nelson small stress test]
  read: IOPS=42, BW=13.9MiB/s (14.6MB/s)(12.3GiB/904825msec)
    slat (usec): min=2, max=8473, avg=26.58, stdev=52.04
    clat (usec): min=30, max=8023.4k, avg=158853.13, stdev=208421.15
     lat (usec): min=42, max=8023.4k, avg=158879.70, stdev=208425.03
    clat percentiles (usec):
     |  1.00th=[     66],  5.00th=[    137], 10.00th=[    245],
     | 20.00th=[    742], 30.00th=[   1565], 40.00th=[   3621],
     | 50.00th=[  79168], 60.00th=[ 143655], 70.00th=[ 206570],
     | 80.00th=[ 316670], 90.00th=[ 480248], 95.00th=[ 583009],
     | 99.00th=[ 742392], 99.50th=[ 801113], 99.90th=[ 926942],
     | 99.95th=[1027605], 99.99th=[3439330]
   bw (  KiB/s): min=   24, max=258184, per=47.42%, avg=13000.64, stdev=16851.88, samples=985
   iops        : min=    0, max=  564, avg=38.20, stdev=39.37, samples=985
  write: IOPS=23, BW=8021KiB/s (8213kB/s)(6549MiB/836125msec); 0 zone resets
    slat (usec): min=7, max=3420.8k, avg=343.27, stdev=24216.95
    clat (usec): min=6, max=30381k, avg=292247.93, stdev=1846279.09
     lat (usec): min=58, max=30381k, avg=292591.21, stdev=1846416.62
    clat percentiles (usec):
     |  1.00th=[      70],  5.00th=[     101], 10.00th=[     131],
     | 20.00th=[     192], 30.00th=[     293], 40.00th=[     979],
     | 50.00th=[    5669], 60.00th=[   13173], 70.00th=[   72877],
     | 80.00th=[  183501], 90.00th=[  367002], 95.00th=[  526386],
     | 99.00th=[ 8791262], 99.50th=[17112761], 99.90th=[17112761],
     | 99.95th=[17112761], 99.99th=[17112761]
   bw (  KiB/s): min=    8, max=299704, per=87.37%, avg=13650.88, stdev=19572.55, samples=977
   iops        : min=    0, max=  646, avg=40.49, stdev=45.01, samples=977
  lat (usec)   : 10=0.01%, 50=0.22%, 100=3.47%, 250=12.13%, 500=8.42%
  lat (usec)   : 750=2.49%, 1000=2.13%
  lat (msec)   : 2=7.58%, 4=6.57%, 10=4.21%, 20=4.34%, 50=3.45%
  lat (msec)   : 100=4.07%, 250=19.25%, 500=13.82%, 750=6.52%, 1000=0.65%
  lat (msec)   : 2000=0.08%, >=2000=0.61%
  cpu          : usr=0.51%, sys=0.23%, ctx=44359, majf=0, minf=60
  IO depths    : 1=0.1%, 2=0.1%, 4=0.2%, 8=0.3%, 16=99.4%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.1%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=38221,19954,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=16
stress: (groupid=0, jobs=1): err= 0: pid=128237: Sun Aug 11 21:42:17 2024
  Description  : [Nelson small stress test]
  read: IOPS=36, BW=12.9MiB/s (13.5MB/s)(11.4GiB/904823msec)
    slat (usec): min=2, max=37758, avg=29.45, stdev=218.32
    clat (usec): min=3, max=5053.6k, avg=184087.63, stdev=201615.07
     lat (usec): min=41, max=5053.7k, avg=184117.07, stdev=201618.12
    clat percentiles (usec):
     |  1.00th=[     65],  5.00th=[    135], 10.00th=[    219],
     | 20.00th=[    490], 30.00th=[   1680], 40.00th=[  58983],
     | 50.00th=[ 137364], 60.00th=[ 187696], 70.00th=[ 256902],
     | 80.00th=[ 362808], 90.00th=[ 484443], 95.00th=[ 583009],
     | 99.00th=[ 725615], 99.50th=[ 775947], 99.90th=[ 926942],
     | 99.95th=[1002439], 99.99th=[1635779]
   bw (  KiB/s): min=   24, max=303480, per=48.60%, avg=13324.66, stdev=15923.38, samples=900
   iops        : min=    0, max=  636, avg=36.52, stdev=34.91, samples=900
  write: IOPS=21, BW=7829KiB/s (8017kB/s)(6208MiB/812003msec); 0 zone resets
    slat (usec): min=8, max=23051, avg=172.05, stdev=269.40
    clat (usec): min=4, max=26223k, avg=345496.71, stdev=1929292.62
     lat (usec): min=56, max=26223k, avg=345668.76, stdev=1929294.26
    clat percentiles (usec):
     |  1.00th=[      68],  5.00th=[     101], 10.00th=[     130],
     | 20.00th=[     192], 30.00th=[     269], 40.00th=[     400],
     | 50.00th=[    2409], 60.00th=[   11469], 70.00th=[   33162],
     | 80.00th=[  214959], 90.00th=[  438305], 95.00th=[  591397],
     | 99.00th=[ 9328133], 99.50th=[17112761], 99.90th=[17112761],
     | 99.95th=[17112761], 99.99th=[17112761]
   bw (  KiB/s): min=   16, max=360360, per=91.60%, avg=14312.77, stdev=19145.59, samples=884
   iops        : min=    0, max=  756, avg=39.49, stdev=41.87, samples=884
  lat (usec)   : 4=0.01%, 10=0.01%, 50=0.24%, 100=3.43%, 250=13.62%
  lat (usec)   : 500=11.35%, 750=3.48%, 1000=1.55%
  lat (msec)   : 2=3.97%, 4=2.64%, 10=2.95%, 20=4.05%, 50=3.18%
  lat (msec)   : 100=3.23%, 250=19.75%, 500=17.91%, 750=7.21%, 1000=0.56%
  lat (msec)   : 2000=0.06%, >=2000=0.80%
  cpu          : usr=0.62%, sys=0.19%, ctx=42436, majf=0, minf=58
  IO depths    : 1=0.1%, 2=0.1%, 4=0.2%, 8=0.4%, 16=99.3%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.1%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=33008,17566,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=16

Run status group 0 (all jobs):
   READ: bw=26.8MiB/s (28.1MB/s), 12.9MiB/s-13.9MiB/s (13.5MB/s-14.6MB/s), io=23.7GiB (25.4GB), run=904823-904825msec
  WRITE: bw=15.3MiB/s (16.0MB/s), 7829KiB/s-8021KiB/s (8017kB/s-8213kB/s), io=12.5GiB (13.4GB), run=812003-836125msec

Disk stats (read/write):
  sdb: ios=71241/37679, merge=0/79, ticks=12088873/12617701, in_queue=25410356, util=98.74%

Example output (fast OMV SMB)

stress: (g=0): rw=randrw, bs=(R) 4096B-1024KiB, (W) 4096B-1024KiB, (T) 4096B-1024KiB, ioengine=libaio, iodepth=16
...
fio-3.33
Starting 2 processes
Jobs: 2 (f=2): [F(2)][100.0%][eta 00m:00s]
stress: (groupid=0, jobs=1): err= 0: pid=2695937: Sun Aug 11 22:35:44 2024
  Description  : [Nelson small stress test]
  read: IOPS=145, BW=47.6MiB/s (49.9MB/s)(42.5GiB/913477msec)
    slat (usec): min=2, max=26353, avg=58.40, stdev=206.57
    clat (usec): min=104, max=2047.9k, avg=12816.66, stdev=61461.93
     lat (usec): min=117, max=2047.9k, avg=12875.05, stdev=61461.19
    clat percentiles (usec):
     |  1.00th=[    996],  5.00th=[   2147], 10.00th=[   2769],
     | 20.00th=[   3621], 30.00th=[   4424], 40.00th=[   5407],
     | 50.00th=[   6521], 60.00th=[   7701], 70.00th=[   9110],
     | 80.00th=[  10814], 90.00th=[  13698], 95.00th=[  17171],
     | 99.00th=[ 120062], 99.50th=[ 446694], 99.90th=[ 960496],
     | 99.95th=[1166017], 99.99th=[1484784]
   bw (  KiB/s): min=   33, max=571776, per=100.00%, avg=105476.19, stdev=139877.54, samples=369
   iops        : min=    0, max= 1773, avg=299.33, stdev=402.43, samples=369
  write: IOPS=78, BW=25.4MiB/s (26.7MB/s)(21.9GiB/882111msec); 0 zone resets
    slat (usec): min=8, max=19996, avg=422.84, stdev=490.09
    clat (usec): min=120, max=4478.9k, avg=20844.50, stdev=104407.14
     lat (usec): min=145, max=4479.4k, avg=21267.34, stdev=104398.63
    clat percentiles (usec):
     |  1.00th=[    570],  5.00th=[   2376], 10.00th=[   2966],
     | 20.00th=[   3884], 30.00th=[   4817], 40.00th=[   5997],
     | 50.00th=[   7177], 60.00th=[   8717], 70.00th=[  10552],
     | 80.00th=[  13435], 90.00th=[  22938], 95.00th=[  55837],
     | 99.00th=[ 270533], 99.50th=[ 505414], 99.90th=[1535116],
     | 99.95th=[1954546], 99.99th=[4076864]
   bw (  KiB/s): min=  116, max=588064, per=100.00%, avg=111529.76, stdev=145498.82, samples=361
   iops        : min=    0, max= 1835, avg=319.26, stdev=420.92, samples=361
  lat (usec)   : 250=0.15%, 500=0.39%, 750=0.33%, 1000=0.28%
  lat (msec)   : 2=2.62%, 4=19.68%, 10=49.18%, 20=21.19%, 50=3.53%
  lat (msec)   : 100=1.01%, 250=0.79%, 500=0.38%, 750=0.21%, 1000=0.13%
  lat (msec)   : 2000=0.13%, >=2000=0.02%
  cpu          : usr=1.78%, sys=1.96%, ctx=161455, majf=0, minf=61
  IO depths    : 1=0.1%, 2=0.1%, 4=0.2%, 8=0.3%, 16=99.4%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.1%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=132944,68929,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=16
stress: (groupid=0, jobs=1): err= 0: pid=2695938: Sun Aug 11 22:35:44 2024
  Description  : [Nelson small stress test]
  read: IOPS=144, BW=51.0MiB/s (53.5MB/s)(45.5GiB/913651msec)
    slat (usec): min=2, max=23315, avg=57.89, stdev=177.90
    clat (usec): min=101, max=1961.1k, avg=12840.81, stdev=60523.78
     lat (usec): min=124, max=1961.2k, avg=12898.70, stdev=60523.08
    clat percentiles (usec):
     |  1.00th=[   1057],  5.00th=[   2212], 10.00th=[   2966],
     | 20.00th=[   3949], 30.00th=[   4752], 40.00th=[   5669],
     | 50.00th=[   6587], 60.00th=[   7767], 70.00th=[   8979],
     | 80.00th=[  10814], 90.00th=[  13566], 95.00th=[  16909],
     | 99.00th=[ 113771], 99.50th=[ 480248], 99.90th=[ 926942],
     | 99.95th=[1098908], 99.99th=[1434452]
   bw (  KiB/s): min=   11, max=535318, per=100.00%, avg=116860.38, stdev=139385.70, samples=352
   iops        : min=    0, max= 1606, avg=310.24, stdev=377.85, samples=352
  write: IOPS=77, BW=27.3MiB/s (28.6MB/s)(23.6GiB/884188msec); 0 zone resets
    slat (usec): min=6, max=26990, avg=438.46, stdev=504.53
    clat (usec): min=132, max=2040.9k, avg=17837.66, stdev=67499.86
     lat (usec): min=162, max=2041.4k, avg=18276.12, stdev=67487.74
    clat percentiles (usec):
     |  1.00th=[    668],  5.00th=[   2704], 10.00th=[   3556],
     | 20.00th=[   4686], 30.00th=[   5669], 40.00th=[   6783],
     | 50.00th=[   7963], 60.00th=[   9241], 70.00th=[  10945],
     | 80.00th=[  13566], 90.00th=[  21365], 95.00th=[  46924],
     | 99.00th=[ 204473], 99.50th=[ 387974], 99.90th=[1019216],
     | 99.95th=[1434452], 99.99th=[1769997]
   bw (  KiB/s): min=   82, max=585474, per=100.00%, avg=126777.70, stdev=149747.38, samples=347
   iops        : min=    0, max= 1630, avg=335.09, stdev=397.89, samples=347
  lat (usec)   : 250=0.12%, 500=0.35%, 750=0.31%, 1000=0.27%
  lat (msec)   : 2=2.34%, 4=14.81%, 10=53.90%, 20=22.06%, 50=3.49%
  lat (msec)   : 100=0.93%, 250=0.67%, 500=0.31%, 750=0.21%, 1000=0.15%
  lat (msec)   : 2000=0.09%, >=2000=0.01%
  cpu          : usr=2.50%, sys=2.06%, ctx=165105, majf=0, minf=58
  IO depths    : 1=0.1%, 2=0.1%, 4=0.2%, 8=0.4%, 16=99.3%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.1%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=132204,68715,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=16

Run status group 0 (all jobs):
   READ: bw=98.6MiB/s (103MB/s), 47.6MiB/s-51.0MiB/s (49.9MB/s-53.5MB/s), io=88.0GiB (94.5GB), run=913477-913651msec
  WRITE: bw=52.7MiB/s (55.2MB/s), 25.4MiB/s-27.3MiB/s (26.7MB/s-28.6MB/s), io=45.5GiB (48.8GB), run=882111-884188msec

Accessing a Proxmox guest in ZFS from a rescue disk

Testing disaster recovery: what if my Proxmox server dies and I need to get data from a VM disk stored in it in ZFS? The simple thing is to boot Proxmox and use it to recover. But what if I don’t want to use Proxmox to get at my files? It’s possible, at least in theory, using generic ZFS and QEMU tools. I tried this and it seemed to work.

(An aside: I harshly unplugged my ZFS pool disks while Proxmox was running, then plugged them in later. Proxmox didn’t handle this very well, I ended up having to reboot the Proxmox server and then everything was back with no drama.)

Part 1: import the ZFS pool

The first step is to get the ZFS pool online in a rescue environment.

  1. Boot systemrescue-zfs on some computer.
  2. Plug the drives from your ZFS pool into the rescue machine
  3. Run lsblk to see that the drives are present.
  4. Run zpool import to see a list of pools. Your Proxmox pool should be there. Proxmox creates rpool on install, you may have others.
  5. Run zpool import -f poolname to import the pool.
  6. Run zfs list to see what the pool has in it

At this point any normal filesystems in Proxmox are mounted somewhere in the filesystem and you can cd to their directories, copy them as files, etc.

Part 2: access the QEMU virtual disks

I’m after data that’s in a guest virtual machine’s disk. And those aren’t stored in normal files. Instead they are stored in ZFS datasets with funny names like rpool/data/vm-100-disk-1. They are in QEMU disk image format. (I think raw, not qcow2, but I am not certain.)

There’s several options for what to do next. You could zfs send the data somewhere safe. In Proxmox you could access the virtual disks with the qm command line tool. There’s probably a way to use qemu-img dd to get your data. But here in systemrescue-zfs I’m going to mount it via a network block device.

I’m a little out of my depth here but I bashed my way into getting access like this

  1. cd /zvol. In here is filesystem access to the ZFS datasets (as symlinks to block devices)
  2. Find the virtual disk you want, say vm-100-disk-1
  3. qemu-img info vm-100-disk-1 to see if there’s a plausible disk image there.
  4. modprobe nbd max_part=8 to load a driver for network block devices
  5. qemu-nbd --connect=/dev/nbd0 vm-100-disk-1 to make the QEMU disk available as /dev/nbd0. Note this is the whole disk, not just one partition.
  6. fdisk /dev/nbd0 -l to see the partition table of the virtual disk
  7. mount /dev/nbd0p1 /mnt/hope to mount the partition 1 filesystem as /mnt/hope.
  8. cd /mnt/hope and there’s your stuff!

USB enclosures and Linux

I’m beginning to see why everyone says not to use USB enclosures with Linux. It’s a cursed product category. I’m finding it very hard to find a simple two bay JBOD enclosure that might work reliably. OTOH I’ve been using 2.5″ USB drives with a server successfully for a year+ now, this general concept should work. And I’ve been using a new drive in a SABRENT 3.5″ single disk enclosure successfully. But I’m having a hard time finding 3.5″ enclosures that take more than one disk.

Update 1: see at bottom

Update 2: see this video which talks favorably about newer USB 3.2 enclosures like the Mediasonic Probox.

Update 3: see this Reddit post I made.

Horror stories abound of buggy JMicron chipsets. It’s never quite clear if the reports are real, they’re mostly ranty Amazon reviews. But definitely bad vibes.

I know for sure there’s one big problem with the USB enclosure product category: power restoration. Most of these enclosures will not turn back on when power is restored until you press a button on them box. WTF? Why would you build hardware like that?

Also USB enclosures typically have a low power / idle mode when not used for awhile. I’m OK with it taking a few seconds for the disks to spin up (although it’d be nice to have control over that). But some of them seem to never come back online or start throwing errors.

None of these devices I’ve bought recently work out of the box with smartctl. They aren’t identified correctly. smartctl -d sat works around the problem, sort of. There’s also some way to register the device in a database to teach smartctl about it. This identification thing seems to be a problem with the UAS driver in particular, or maybe it’s the 2022 version of smartctl Debian is installing.

SABRENT EC-KSL3, it works?

I’ve had decent luck for a few days with a SABRENT EC-KSL3, a $30 single disk enclosure. I don’t love the physical toolless design but the interface seems to work with my Linux box running OMV. It’s fanless aluminum which I think is OK for a single disk.

The device has a physical rocker switch for power. I need to test it but I assume that means it will come back on when power is restored. I think it’s gone to sleep a few times but seems to come back every time. I saw a couple of resets from the kernel driver early in trying to use it but have gone most of a day now without a single reset. So good?

The chipset is some sort of JMicron, not sure which.

Yottamaster PS200U3: it doesn’t work?

Much worse first experience with a Yottamaster PS200U3, a $80 dual disk enclosure. The physical design is pretty nice, they even included decent tools and extra screws. No fan and it’s plastic inside, so some question about thermals.

It has pushbutton power you definitely have to press to get it to turn on after a power failure. (Confirmed with support.) But none of that matters because the device is just not working. Ugh!

The chipset is a JMicron JMS56x.

I set it up with TrueNAS and my ZFS array disappeared within a few minutes. At least, TrueNAS can’t find it. Looking at the kernel log I see a whole lot of errors from the UAS driver and attempts to reset followed by giving up on the device entirely.

Whatever the case the disks in this enclosure just do not work with TrueNAS scale. There could be other sources of errors: the disks themselves, or the virtualization in the middle, or maybe TrueNAS. But I’m inclined to blame the enclosure.

Here’s an example dmesg log for errors in TrueNAS for the USB disk. This gets triggered just trying to look at the Storage status page in the web UI. The first line shows a reset at 67 seconds, the rest of it is another problem starting at 300 seconds (errors) and then a rest at 330s. I think these things have a 5 minute idle timeout so that doesn’t even explain it.

[   67.520053] scsi host3: uas_eh_device_reset_handler success
[  300.078621] sd 3:0:0:1: [sdc] tag#6 uas_eh_abort_handler 0 uas-tag 4 inflight: IN
[  300.078642] sd 3:0:0:1: [sdc] tag#6 CDB: Read(16) 88 00 00 00 00 00 00 00 22 20 00 00 00 e0 00 00
[  330.798889] sd 3:0:0:1: [sdc] tag#4 uas_eh_abort_handler 0 uas-tag 3 inflight: IN
[  330.799100] sd 3:0:0:1: [sdc] tag#4 CDB: ATA command pass through(16) 85 08 0e 00 d5 00 01 00 06 00 4f 00 c2 00 b0 00
[  330.814733] scsi host3: uas_eh_device_reset_handler start
[  331.071192] usb 3-1: reset SuperSpeed USB device number 2 using xhci_hcd
[  331.096325] scsi host3: uas_eh_device_reset_handler success

On further testing I can reproduce the problem by trying to open the Storage Dashboard in TrueNAS, it happens even if I try again in just over a minute. My guess is TrueNAS is issuing some commands via UAS that the controller or disks really don’t like and it’s crashing the connection to the drive. Could be a Linux bug, could be a controller bug. I sure hope this problem is isolated to the Yottamaster.

Update

I’m beginning to suspect TrueNAS Scale is the issue. This exact same hardware is doing fine with a ZFS pool built inside Proxmox. I made a 4TB virtual disk and shared it into an OpenMediaVault VM and so far it’s working great. Was able to write a bunch of data and run fio tests with no problem, no errors from the kernel. Also smartctl works out of the box on Proxmox.

Maybe TrueNAS is doing more complex probing on the disk? The TrueNAS docs do say not to use it with USB, so maybe that’s why. I may still try TrueNAS with some different enclosures.

This Proxmox ZFS + OMV solution is not bad. It’s not ideal from a management perspective, I’d rather the NAS VM knew more about the real hardware. But Proxmox is pretty good at that too. And I/O performance as measured by fio is pretty good. Some numbers:

Sequential writes on PVE (direct): 727MiB/s, 186k IOPS. ?!
Sequential writes via NFS: 70.3 MiB/s, 18.0k IOPS.
Sequential writes via SMB: 70.2MiB/s, 18.0k IOPS.

Random writes on PVE: 26.3MiB/s, 6734 IOPS
Random writes via SMB: 18.6MiB/s, 4759 IOPS
Random writes via NFS: 29.1MiB/s, 7458 IOPS

Basically this tells me it’s fast enough. The actual physical disks are probably about 100-150 MiB/s depending on where on the spindle you’re writing. So ZFS is costing us something, and then the network overhead is more, but it’s all reasonably fast for low end hardware.

Clearly that 727MiB/s number is bogus, I guess ZFS write caching. Weird because I have --end_fsync=1. If I add --fsync=10000 it backs off to about 73MiB/s, more plausible.

OpenMediaVault, exFAT, writeable

OpenMediaVault, the NAS, now officially supports exFAT. It’s still a lousy choice for a Unix filesystem.

I had it working with read/write access. But then the write access stopped working. Judging by searches I’m not the first one this has happened to.

I got it working again by manually editing /etc/openmediavault/config.xml and changing the options for the fstab mount to defaults,nofail,fmask=000,dmask=000. Then I ran omv-salt deploy run fstab to regenerate /etc/fstab and rebooted. Now the Unix directory in /srv has everything with permissions 777 (whee!) and SMB users can write. Total mockery of POSIX file permissions but eh, it’s exFAT.

Some other advice from the old days was to use exfat-fuse instead of exfat. I think that’s from when the Linux kernel only could read exFAT, not write it.

The main advice is “don’t use exFAT”. Which fair enough. But it’s nice to pop a USB drive in from a Windows machine or Mac and have it on the NAS.

Proxmox notifications: gotify, email

Proxmox sends emails for important notifications, there’s nice docs. But email sucks in 2024, I have no idea how to get mail like this delivered. The only other option Proxmox supports is Gotify. I wish it had some generic HTTP post or something simple, looks like the Proxmox devs are adding webhook endpoints. ntfy.sh seems popularly requested but can be supported in a webhook. See also apprise and UnifiedPush.

Gotify

Gotify is a little self-hosted server that receives notifications and does things with them. It has very nice docs. Gonna tinker by installing it in an LXC in Proxmox. This server should really be hosted elsewhere, ideally a cloud service, but those seem to start at $9/mo so let’s just hack in a container for now.

Installing was easy with the tteck script. I added tailscale and had to manually wangle the LXC config to allow access to the tunnel device, per usual. With that gotify’s web server was available. The default login is admin/admin.

AFAICT tteck doesn’t install any config script. There’s a systemd unit to start it and the software is in /opt/gotify. I think /etc/gotify/config.yml would be a reasonable place for a config. It actually seems OK with no config file? It must have reasonable defaults, like sqlite3.

Getting Gotify up and running with Proxmox isn’t too hard. You create an application, take the token, then set up a notification destination in Proxmox. I also told Proxmox’s notification matcher to deliver to gotify. Test messages post immediately and are visible in the webapp. The Android app works but I don’t like the design: I want something else connected to Gotify and just delivering push messages to my phone.

I could also use some other delivery options. Deliver to RSS in particular. There’s a bunch of plugins and contrib stuff. No Atom or RSS! There’s a Slack plugin but it’s 5 years old and doesn’t work with modern Slack tokens.

Lots of interesting plugins for receiving notifications too. A zillion RSS receivers. Support for webhooks, yay. Also an SMTP gateway. Also appreciate this reverse proxy so I could use a public IP instead of Tailscale.

I dunno, I’m left thinking the core Gotify message router is pretty good but usability and features are not. The default message view is very limited (no time filtering, doesn’t even show the application). The Android and other delivery options look limited. I’ll keep using Gotify for now because it’s all Proxmox supports but once PVE adds webhooks or something I should re-evaluate.

Email

The default configuration has you specify an Internet email address that root mail should be forwarded to. But they don’t do anything to actually help you get email delivered. The default config will gamely just try to SMTP deliver the mail but of course no modern mail system relays mail from strangers. The mail just disappears into a postfix queue until it times out.

How about local delivery? I first tried making root’s forwarding address root, the empty string, root@localhost, or other variants. None worked: either invalid or a mailer loop. I then fixed it by removing ~root/.forward. Now postfix will write to /var/mail/root. Not ideal but at least it’s not disappearing.

Another local option is to create a second user account on the PVE host (like “nelson”) and forward root’s mail to it. But I’m trying to avoid that.

Remote delivery should be possible, in the past at least it was possible to get Gmail to relay mail for you if you were authenticated enough. But every time I look at doing that it gets harder. Screw it.

Migrating Proxmox to a new install

After my Proxmox disk failed I managed to clone the disk before it died entirely and boot from it. But that’s temporary hardware, now I want to set up Proxmox again on a new permanent disk, a 256GB 970 EVO I had lying around.

I’ve decided to go for a full rebuild, installing PVE and configuring it as if new. Then restoring all my guests from a backup. There’s a simpler path where you just restore /var/lib/pve-cluster/config.db /etc/hosts /etc/hostname but I kind of want to redo the setup. I did this before in January for a different server. This post is my boring careful notes here on exactly what I did.

Backing up old host

First thing is to back up everything on the old host disk while the old host is still working. I stopped all the guests and did a full backup of every single one. This is the precious data, what I’ll be restoring.

Second is to back up /etc and /var/lib/pve-cluster/. Note that /etc/pve is special and backed by a live-mounted database in pve-cluster. I’m backing up the stuff in /etc/pve as if they were normal files (for future diffing) and taking a backup of the database with sqlite3 config.db ".backup 'config.db.backup'.

After shutdown I’m going to unplug the old host disk for safekeeping, if things go badly I can use it to restore. Note it’s awkward to read the files on it because after you install a new Proxmox you end up with two ZFS pools named rpool that both want to mount to /. zpool import -d -R should help with that but I found it tricky. Instead I’ve backed up the files I want to read to the backup disk.

Installing new Proxmox PVE server

Do the regular Proxmox install from USB. There’s very few options there, I love how simple the Proxmox installer is. But this is what I did:

  1. ZFS RAID0 as the filesystem, with the one internal SSD
  2. United States, UTC timezone, US English keyboard
  3. Password and email as nelson@monkey.org even if I never have set up outgoing mail
  4. Hostname gvpve. Verify IP address is correct (thank you DHCP).

Improving Proxmox install

These are my generic customizations to any new Proxmox install

  1. Add my ssh key to ~root/.ssh/authorized_keys. Don’t disturb the key for root PVE made!
  2. Run the tteck helper script “Proxmox VE Post Install” and accept all defaults. This does a few things to make a new install nicer.
    • enable no-subscription repositories
    • disable the nag message
    • disable the high availability services (pve-ha-lrm, pve-ha-crm, corosync)
    • software update to Proxmox (takes a few minutes)
  3. Reboot
  4. Install some useful software. apt install joe sudo avahi-daemon
  5. Install tailscale. Start with tailscale up --accept-dns=false. Disable key expiry in Tailscale console.

Restoring my guests

Proxmox can do all this automatically if you have a cluster, this task just becomes a migration. (Automatic, if you have HA configured.) But it’s nice to do it manually as a recovery exercise.

  1. Plug in the USB disks for backups and USB media and verify with lsblk
  2. Restore /etc/fstab mounts for these disks (look at backup file from old server).
  3. Mount /mnt/backup and /mnt/usb-media
  4. Under Datacenter > Storage, add my Proxmox backup volume
    id: backup, type: Directory, Content: VZDump backup file, Path: /mnt/backup
  5. Remove “backup” as a content for the storage named “local”
  6. Under Datacenter > PVE > Backup, locate the files for the backups I took just before shutting down old host
  7. Restore each one manually (a lot of clicking!). Re-type the guest IDs instead of taking newly assigned ones. Probably unnecessary.
  8. Reboot to start all the relevant guests.

The restores all went pretty well, Proxmox backs up the configuration of the guest as well as the guest’s disk images. For some reason the config for a TrueNAS VM changed, it added back the ISO for the install media. This could actually break the guest although it’s easy to fix. The vmgenid also changed on every VM.

Finishing up

  1. Add my Influx DB as a system metrics server
  2. Create a new backup job on Proxmox
    All guests, 9am, keep 6 monthly / 4 weekly / 7 daily
  3. Test a manual backup. MISTAKE. The daily retention policy means this manual backup erased the reference backup from earlier today. I’d already used those to restore all my systems, so it’s probably no big deal, but definitely not the right thing to do.

I tried diffing the old server’s /etc/pve (on backup disk) to the new one. Didn’t learn anything really. Lots of differences but most of them are what you’d expect, new security keys. Also missing config files because I looked before I restored the guest hosts. I did spot the config change for the TrueNAS VM though, still puzzled by that.

Proxmox split disk idea

A setup I did not pursue, but seemed an interesting idea.

Proxmox by default installs itself to a disk and takes over the whole disk. You can set it up with ext4 (LVM) or zfs and use that disk usefully for guest disk images, ISOs, backups, etc. But the whole thing belongs to Proxmox.

What if instead you install Proxmox to a small partition, it only needs 16GB. And then allocate the rest as a ZFS pool? That seems like a clean separation. It also means you can use ext4 for Proxmox which might make recovery simpler.

I went down this road, following notes similar to this guy. I told Proxmox to install to 32GB ext4. It creates a partition #3 with LVM. Inside is 3.8GB for swap, 13.6GB for root, and two 11.6GB marked “pve-data”. The rest of the disk is then unused.

So I used fdisk to add a partition of type bf01 (zfs). The next step would be creating a zpool on it, then telling Proxmox to use that as storage for things. But I realized in the end I’d just be replicating more or less what Proxmox does by default with a ZFS install, only with non-standard names and setup for questionable benefit. So I stopped.

There’s something vexing about systems having very capable but unreliable SSDs as their install drives. I want to use that storage better!

Some ZFS exploring, disk recovery

My BOSGAME N100’s boot SSD failed. So I learned some ZFS to recover the files. I don’t think too much important is on this disk. Proxmox has been faithfully backing up system images to another drive and I have no reason to doubt them. But I’d like to rescue the Proxmox system itself, particularly since I don’t remember what all I customized on it (and don’t have a backup).

Summary

This post is more scattered than usual and unlikely to be interesting. This is what I learned:

  • You can boot off a dd clone of the Proxmox ZFS boot disk and it will work fine.
  • My disk failed with random access reads but I could use dd to clone it still. Weird.
  • You can recover the files on a ZFS pool with a system rescue disk. The key command is zfs import which brings the pool online in a new operating system.
  • zpool list and zpool status give you basic info. zdb is useful if you can’t get a pool online
  • Cheap SSDs are not to be trusted.

Lots of details

The big help here was the SystemRescue-ZFS fork. That’s the venerable Linux SystemRescueCD modernized and with ZFS installed for you.

ZFS docs are confusing. There were a bunch written really well by Sun and/or Oracle in the early days. But that was over a decade ago. OpenZFS has good man pages but I’m missing an overall gestalt of understanding the system. And ZFS is complicated, it’s a comprehensive implementation of a lot of data storage concepts.

Claude was a big help for me exploring ZFS. So was this StackOverflow post which has some recovery commands to try. And this recovery book was mildly helpful but is mostly about how to recover from partial failures where your pool still exists. My whole pool is gone because I’m using ZFS on a single disk, shame on me. These Proxmox docs for ZFS are also helpful.

One ZFS concept I’ve learned: ZFS doesn’t really have fsck. It’s constantly fixing itself (hopefully), there’s no big check-the-thing-offline. (scrub is the closest it gets.) A second concept I’m only getting now: ZFS has a notion of “imported” pools, where the ZFS system becomes aware of some storage. It’s a little like mounting a filesystem but it is not just mounting into Unix namespace, it’s also enabling all the access to the pool, datasets, filesystems, etc.

Another key concept: Proxmox creates a ZFS pool called rpool for its system boot disk. That’s what’s not working for me.

Using SystemRescue

SystemRescue is great, and the ZFS fork is perfect for me. Try setfont -d if the console font is too small. Remember that Linux lets you have multiple console windows: Try Ctrl-Alt-F2 to switch to window 2. Even better set a root password and then systemctl stop iptables.service so you can ssh in from a humane terminal emulator.

Cloning the bad disk

I suspected hardware failure so first thing I did once I had the rescue system booted was dd if=/dev/sda of=/dev/sdc bs=1M to do a block by block clone of the disk. This worked with no hitches, suggesting maybe the disk is not entirely gone. I unplugged the backup, that may be crucial since ZFS might be confused by having two copies of the same pool.

Exploring the problem disk with SystemRescue

I booted SystemRescue and first thing I tried was zpool status. It says no pools available. Same thing with zpool list. Um, is that bad? (I’d briefly tried Proxmox rescue too and it said the same thing). So I asked some AIs to go deeper and got to the ZFS debugger. zdb -lu /dev/sda3 does find some ZFS labels and stuff that I need. So the data is there and at least a little ZFS-shaped.

Asking more AIs I learned that you have to “import” a pool: presumably this SystemRescue ZFS system has never heard of this ZFS pool and so didn’t import it. Sure enough zfs import finds my missing rpool. It doesn’t want to import it by default because it wasn’t cleanly exported by some previous system. But I can zfs import -f rpool to force it. Which I have done and it takes an alarmingly long time to respond! What’s it doing? After a couple of minutes it gives up and says cannot import 'rpool': one or more devices is currently unavailable. That’s bad right?

Yes, it’s bad. journalctl has the news. The kernel module ata2, the driver for the SSD, is reporting errors. A lot of them, but the bad ones are failed command: READ FPDMA QUEUED, hard resetting link, COMRESET failed, and eventually ata2: reset failed, giving up. At which point zio and sd 1:0:0:0 start complaining about read errors. Also I have to reboot now, /dev/sda is no longer a working device.

This sure seems like a hardware failure to me! I wonder why the dd worked though? Maybe it’s just random access reads that fail? Or maybe zpool import was trying to write and it’s the writes that are failing? But those errors were triggered by reads... I tried again with zpool import -o readonly... and got the same errors. I think this disk is cooked.

Exploring the cloned image

I took a gamble and tried to import the backup cloned disk image disk. It worked immediately! zpool import -o readonly -d /dev/sdc3 -f rpool. Note I’m using the -d option to specify what device to import from because I think I have two different disk devices with an rpool on them (one of which is offline.) Also that readonly turns out to be a lie.

I think zpool import tries to mount all the filesystems where they were last time. But there was some error about rpool/ROOT/pve-1 not mounting, I assume because it wanted to mount to /. So nothing mounted. I can manually mount other filesystems with zfs mount but I really need pve-1 and it really wants to mount to /.

In theory zpool import -R /tmp/restore should mount everything under /tmp/restore. But I kept getting confusing errors. I finally got the thing mounted by doing zfs set mountpoint=/tmp/rr rpool/ROOT/pve-1. Which mounted it under /tmp/restore/tmp/rr, not what I wanted, but close enough. (Note this edit was permanent, written to the disk, despite the pool being imported readonly. I had to undo it later.)

Anyway all this hackery later and I have access to my files! They are mounted and I can make a backup of my Proxmox boot disk.

Backing up Proxmox PVE itself

One annoying thing about Proxmox is it has no system for backing up Proxmox itself. Everyone says “don’t customize it, just run guests and back those up” and mostly that works but still, it’d sure be nice to have a backup for situations like this.

Here’s a five-year-old gist backup script. The discussion there is more valuable than the script. It backs up a bunch of stuff in /etc one by one. Me, I just took all of /etc.

The Proxmox docs for Recovery are also useful. They suggest backing up /var/lib/pve-cluster/config.db /etc/hosts /etc/hostname.

Big gotcha here: a lot of configs are in /etc/pve. But those aren’t normal files stored in ZFS. Instead that’s a FUSE filesystem Proxmox runs (keyword pmxcfs) so in my non-running system here /etc/pve is empty and my tar got nothing. Those files are backed by a sqlite database in /var/lib/pve-cluster/, as the docs above discuss. With the system offline you can just copy those files. With it online and live something like sqlite3 config.db ".backup 'config.db.backup'" is safer.

Setting up a replacement Proxmox

Now that I have a backup of my files I’ve got several options to bring something back online.

  1. Try jiggling the SSD a bit, maybe it’s just a loose connection? This problem started after I opened the case, maybe I disturbed it. Nope, no such luck.
  2. Try booting off the clone I made. That might Just Work, actually. Probably should make a second clone first. Yep, this worked!
  3. Reinstall Proxmox on clean disk, then follow those recovery notes to do a quick restore. But I have to re-apply whatever other customizations I did myself, too. And manually restore all the guest hosts.
  4. Reinstall Proxmox and just configure it again. May not be much more work than #3.

No matter what I do I should replace that SSD, I’m never going to trust it. Was a cheap one anyway.

New Install

Option 2 worked so I have a working server again. I ran zpool scrub just to be safe and it found no errors.

But I’d like to install cleanly on a new SSD. So I ordered a 1TB WD_BLACK 1TB SN850X based on these reviews. I used to be a Samsung partisan but they really screwed up with the 980s and 990s. There’s an argument that you should just use a tiny scratch drive to install Proxmox on, or maybe a fancy enterprise-grade SSD instead. Eh, I’ll go with this. (No one makes high quality 512GB SSDs anymore!)

I will probably go with option 3 on this new install. Reinstall Proxmox, but then clone the config by copying a few files around. If I’m patient I should do option 4 and change the way some things work on my system. This was the first Proxmox install I did and I could do a cleaner job the fourth time around.

Bonus: Exploring a healthy Proxmox install disk

Before I worked on the bad disk I took a look at what a good disk looks like in ZFS. Here’s some things I learned from a working Proxmox system with no problems. Proxmox is installed to a single 2TB SSD with default ZFS options.

The physical disk is /dev/nvme0n1. Proxmox created three GPT partitions. fdisk tells me nvme0n1p1 is about 1M big and is labelled “BIOS boot”. p1 is 1GB big and is “EFI System”. The rest of the disk is in partition 3 labelled “Solaris /usr & Apple ZFS”. lsblk -o +PARTTYPE will show the GUIDs for the types and that partition 3 is 6a898cc3-1dd2-11b2-99a6-080020736631. Which honest-to-goodness has two meanings in this reference table. (Neither of which are “OpenZFS” or “Linux ZFS”, lol.)

lsblk also shows the SSD partitions and a couple of USB drives I have. And a bunch of /dev/zd* devices, which I gather are device names for ZFS snapshots or datasets or something. Presumably I shouldn’t mess with them.

zpool status shows that I have one pool named rpool, that’s what Proxmox created. It has one device in it, nvme-eui.002538b22140b542-part3, which corresponds to my SSD partition. zpool list shows me a basic status of rpool, how much disk space is free and the like.

zfs list shows me a whole bunch of datasets in ZFS, I think this is the top list of every thing in this pool. Most of these are under rpool/data and are either filesystems (for containers) or disk images (for VMs). But there’s also a few extras that I think are related to the PVE host: rpool/ROOT/pve-1 is the important one, also rpool/var-lib-vz. rpool/ROOT and rpool itself exist but seem pretty empty, mostly there to hold the subdirectory rpool/ROOT/pve-1.

zfs list -t snapshot shows snapshots, just snapshots and not the primary datasets.

mount | grep rpool shows me a bunch of ZFS things mounted in various places. rpool/ROOT/pve-1 is mounted on /, that’s my root filesystem. Most other things are mounted under /rpool and include a bunch of subvolumes for containers filesystems.

zfs get all rpool/ROOT/pve-1 gives me a very deep list of properties for the root filesystem. Not much of interest here but it’s exhaustive.

zdb -l /dev/nvme0n1p3 is a low-level ZFS debugger, it shows the labels on the disk device. I have a single one, “LABEL 0”, with the name rpool, a hostname that matches my PVE host’s name, and a bunch of stuff I don’t understand. Mostly looking at this because it was helpful with the broken disk since zpool wasn’t even showing it.

Some NAS hardware estimates

I’m trying to get an idea of what building a 10TB NAS would cost if you’re on a budget. Options range from plugging in a single USB drive into an existing N100 miniPC running TrueNAS up to a dedicated Synology device.

I’m not an expert on this stuff: comments welcome!

I’m targeting a working set of roughly 10 TB of data. I’m thinking spinning hard drives (HDDs) make more sense. I like SSDs but the speed is mostly irrelevant in a NAS on gigabit ethernet. Maybe SSDs are more durable, but they are 2-3x more expensive. For RAID options I’m considering setups where one disk can fail and we still can operate.

Summary

We can get 10TB usable storage for anywhere from $200 to $1500 depending on how we do it.

Disks: 10TB usable can be done for $210 with a single disk (no recovery). Or RAID recovery with either 4x4TB or 2x10TB. Both RAID options are about $400 for spinning disks. $1300 to go with SSDs.

USB enclosure: about $200 for a four bay enclosure. Not needed if we just do one or two drives on the N100.

Separate PC appliance instead of the N100: about $250-$600, lets us avoid USB, also maybe a simpler commercial solution.

Update: I ordered two 8TB WD Red Plus drives and a Yottamaster PS200U3 two disk enclosure. Basically the cheapest plausible mirrored setup. Total price $400 plus tax (plus the computer to plug them in to). The 10TB WD Red Plus disks are sort of weird. 12TB are OK but noisier and higher power, so starting smaller. Early indications are the Yottamaster is not reliable, having a lot of trouble with USB errors in TrueNAS Scale.

N100 with TrueNAS and spinning disks

Variants of what I’ve set up already, a homebrew inexpensive system. The experts will tell you USB is not suitable for real NAS systems. But I think it could be OK.

10TB Cheapest: a single 10TB 3.5″ HDD on USB to the N100. 10TB is $210.

10TB RAID1 (mirror): two 10TB HDDs on the N100. $420.

10TB RAIDZ1: four 4TB HDDs ($400) in a USB enclosure ($200) connected to N100. $600

N100 with TrueNAS and SSDs

An SSD option. The disks are 3x the cost of HDDs.

10TB RAIDZ1: four 4TB SATA 2.5″ SSDs ($1300) in a USB enclosure ($200) connected to N100. $1500

Synology appliance (no N100)

A third party commercial alternative to building our own NAS on the N100. Not as capable as TrueNAS but easier to understand and support. No USB involved.

10TB RAID1: two 10TB drives ($420) in a DS223 ($250). $670

10TB RAID5: four 4TB drives ($440) in a DS423 ($400). $840

Build our own appliance

To avoid USB we build a little mini-PC with SATA disks in it. This is a rough guess only.

10TB RAID5. four 4TB drives ($400) and a cheap custom mini PC ($500?) $900ish

Extra costs: Local versioned backup drive

I think this is easy, just a local disk to copy stuff to.

16TB: 3.5″ external HDD on USB to the N100. $280

Extra costs: electricity

50 watts works out to 438kWh a year or about $200/year.

SanDisk Extreme Pro: data loss, smartctl

SMART

I have a recently purchased 4TB SanDisk Extreme Pro 55AF, an SSD. (Note SanDisk is a Western Digital brand.) smartctl doesn’t recognize it. I found a workaround for it which is to pass -d sntasmedia to smartctl. Doing that gives plausible output but some stuff looks a bit off (like power on hours). See full SMART output below.

Getting OpenMediaVault to pass this flag is not possible or at least not easy. There’s a remarkably detailed response here which says they want smartmontools to update its database instead. There’s also a suggested workaround which is to add an entry to /etc/smart_drivedb.h but the format for that seems daunting, I didn’t pursue it (yet).

Bad drive?

Unfortunately while researching this SMART problem I learned SanDisk Extreme Pro has been implicated in some serious data loss problems. See here, here, or here for reports. SanDisk has said it’s a firmware issue and put out an update, their tool here says we don’t need an update for this drive (if I have the right serial number). OTOH Tom’s Hardware is saying it’s a hardware flaw. That’s very troubling and knowing all this now I’ll think twice before buying any SanDisk or WD external USBs. Not sure what to do with this disk.

I have seen one problem with this drive, btw. When using hdparm -t to test throughput it reads for 3 seconds. It tests fine, like 800 MB/s. But if I test a second time it tests super badly, like 60 kilobytes/sec, and there’s an error in dmesg saying it had to reset the drive interface. Then the drive seems to work fine again (until I test throughput again.)

Jul 23 17:50:32 nchsomv (udev-worker)[7715]: sdb: Spawned process 'serial_id /dev/sdb' [7754] is taking longer than 59s to complete
Jul 23 17:50:32 nchsomv systemd-udevd[295]: sdb: Worker [7715] processing SEQNUM=2565 is taking a long time
Jul 23 17:50:32 nchsomv kernel: sd 3:0:0:0: [sdb] tag#11 uas_eh_abort_handler 0 uas-tag 2 inflight: IN
Jul 23 17:50:32 nchsomv kernel: sd 3:0:0:0: [sdb] tag#11 CDB: ATA command pass through(16) 85 08 0e 00 00 00 01 00 00 00 00 00 00 00 ec 00
Jul 23 17:50:33 nchsomv kernel: scsi host3: uas_eh_device_reset_handler start
Jul 23 17:50:33 nchsomv kernel: usb 2-1: reset high-speed USB device number 2 using xhci_hcd
Jul 23 17:50:33 nchsomv kernel: scsi host3: uas_eh_device_reset_handler success
Jul 23 17:50:33 nchsomv kernel: program smartctl is using a deprecated SCSI ioctl, please convert it to SG_IO

I’ve only seen this error with a synthetic test, and that via a KVM pass-through USB device. So I just kind of shrugged it off. FWIW we’ve successfully written 1.7TB of data to the disk and read 3.2TB off of it, so it’s not failing all the time. Sure don’t care for this uncertainty though.

Update: I’ve also seen this error now just reading files from the mounted disk (tar cf - . | pv > /dev/null). It’s possible this was related to the disk waking up from a sleep mode. The earlier hdparm failures were very unlikely to be sleep related. Then I was able to read 2.5TB or more off the disk, both streaming (at 400MB a second) and two parallel random access threads. Without a single error.

SMART output

# smartctl -a -d sntasmedia /dev/sdb
smartctl 7.3 2022-02-28 r5338 [x86_64-linux-6.1.0-23-amd64] (local build)
Copyright (C) 2002-22, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Model Number:                       WD_BLACK SN850XE 4000GB
Serial Number:                      240632803712
Firmware Version:                   624131EX
PCI Vendor/Subsystem ID:            0x15b7
IEEE OUI Identifier:                0x001b44
Total NVM Capacity:                 4,000,787,030,016 [4.00 TB]
Unallocated NVM Capacity:           0
Controller ID:                      8224
NVMe Version:                       1.4
Number of Namespaces:               1
Namespace 1 Size/Capacity:          4,000,787,030,016 [4.00 TB]
Namespace 1 Formatted LBA Size:     512
Namespace 1 IEEE EUI-64:            001b44 8b47193cd2
Local Time is:                      Mon Jul 29 21:55:46 2024 UTC
Firmware Updates (0x14):            2 Slots, no Reset required
Optional Admin Commands (0x0017):   Security Format Frmw_DL Self_Test
Optional NVM Commands (0x00df):     Comp Wr_Unc DS_Mngmt Wr_Zero Sav/Sel_Feat Timestmp Verify
Log Page Attributes (0x1e):         Cmd_Eff_Lg Ext_Get_Lg Telmtry_Lg Pers_Ev_Lg
Maximum Data Transfer Size:         128 Pages
Warning  Comp. Temp. Threshold:     91 Celsius
Critical Comp. Temp. Threshold:     94 Celsius
Namespace 1 Features (0x02):        NA_Fields

Supported Power States
St Op     Max   Active     Idle   RL RT WL WT  Ent_Lat  Ex_Lat
 0 +     9.00W    9.00W       -    0  0  0  0        0       0
 1 +     6.00W    6.00W       -    0  0  0  0        0       0
 2 +     4.50W    4.50W       -    0  0  0  0        0       0
 3 -   0.0250W       -        -    3  3  3  3     3100   11900
 4 -   0.0050W       -        -    4  4  4  4     3900   45700

Supported LBA Sizes (NSID 0x1)
Id Fmt  Data  Metadt  Rel_Perf
 0 +     512       0         2
 1 -    4096       0         1

=== START OF SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

SMART/Health Information (NVMe Log 0x02)
Critical Warning:                   0x00
Temperature:                        34 Celsius
Available Spare:                    100%
Available Spare Threshold:          10%
Percentage Used:                    0%
Data Units Read:                    6,286,318 [3.21 TB]
Data Units Written:                 3,285,119 [1.68 TB]
Host Read Commands:                 62,684,905
Host Write Commands:                33,660,622
Controller Busy Time:               94
Power Cycles:                       803
Power On Hours:                     33
Unsafe Shutdowns:                   8
Media and Data Integrity Errors:    0
Error Information Log Entries:      0
Warning  Comp. Temperature Time:    0
Critical Comp. Temperature Time:    0

Warning: NVMe Get Log truncated to 0x200 bytes, 0x200 bytes zero filled
Error Information (NVMe Log 0x01, 16 of 256 entries)
No Errors Logged

Debian 12 slow login in Proxmox

On my Proxmox 8.1.10 server if I create a privileged Debian 12 container, logins work but hang for 25 seconds before getting a shell prompt. There’s a good discussion of the problem in this forum post.

The clue was this error in journalctl:
Jul 28 16:43:23 transcode dbus-daemon[98]: [system] Failed to activate service 'org.freedesktop.login1': timed out (service_start_timeout=25000ms)

Looking more closely there’s a bunch of errors in systemd-login saying it can’t start. Kind of amazed I ever get a shell.

Unfortunately the recommended fix of setting ProtectControlGroups=no in the systemd-login definition did not work for me. Tried it, still broken.

The other ideas discussed are an unprivileged container (can’t do) or a nested priviliged container (can’t do). There’s also a mention that Ubuntu has a special patch for systemd preventing this error. I think that’s my next step, try Ubuntu instead of Debian.

Sometimes this computer stuff sucks.

Towards a Proxmox NAS

After trying out OpenMediaVault and TrueNAS I’m still left wanting a good NAS for Proxmox. It seems odd to me that the Proxmox folks don’t have their own product. They’ve got most of the pieces already, and a similar product in Proxmox Backup Service. They also bet heavily on Ceph but that’s a high performance distributed storage system, not a simple SMB or NFS server.

Update: HexOS might be worth keeping an eye on. It’s TrueNAS with usability stuff on top for ordinary users.

Now I’m wondering if I should just roll my own NAS services in a container or VM. I’m kind of doing that already, it works fine. I’m not going to make a fancy GUI for it, I’ve been editing /etc/exports and /etc/samba/mb.conf for 20+ years, why stop now? Although Cockpit and the file-sharing plugin might work?

The key thing here is Proxmox can manage ZFS itself. It seems strange to pass through disk hardware devices to a VM to have a separate kernel manage the disks when Proxmox can do it. So here’s the idea:

  1. Create a ZFS pool in Proxmox for NAS data.
  2. Create datasets for network file shares in Proxmox.
  3. Do not make filesystems or mount the network file shares in Proxmox itself
  4. Install Debian in a VM, maybe with Cockpit as a GUI.
  5. Pass the network file share datasets in as VirtIO-SCSI single disks to the VM.
  6. Configure samba and NFS in the VM to share the disks
  7. Bonus: disks can be shared on a private Proxmox-only bridged network for other guests to access them.
  8. Optional: install syncthing in the VM
  9. Optional: enable Restic backups of the file shares in the VM

The part I’m not entirely clear about is the “VirtIO-SCSI” part. I like the idea that ZFS is in Proxmox. What I don’t know is how good performance is virtualizing it t his way. And you don’t have ZFS-level features available in the VM like snapshots and stuff, you would want to use simple ext4fs or something. (ZFS-in-ZFS is possible but can quickly cause problems.) That’s not ideal, ZFS snapshots (for instance) are great for backups. OTOH you can use Proxmox own backup software for the datasets.

Another option would be to create and mount the filesystems in Proxmox and then pass them to all the guests with virtiofs. You wouldn’t even need SMB or NFS if you aren’t sharing data outside Proxmox! But virtiofs isn’t fully baked yet, Proxmox kinda supports it but not fully.

I’m also not clear if a VM is necessary; you might be able to do this all in a container. In that case you’d make the filesystems and mount them in proxmox, then pass them through with a bindmount.

I think there’s a potential product here, a new NAS operating system. Designed to be used as a VM inside Proxmox with Proxmox managing the storage. Just a small thing to publish network shares. Building a real product is a lot of work though, particularly if you want a GUI.

But maybe I’ll make this VM for myself just as a hack. Honestly I’ve done most of the pieces in different ways already, the difference here is being more systematic with managing the storage in Proxmox. I bet in two hours I could have NFS and Samba fully set up and going.

I wonder if this would be a good NixOS project?

TrueNAS Scale first impressions

After having mixed reactions to OpenMediaVault I thought I’d give TrueNAS Scale a try as a small Network Attached Storage system to run under Proxmox. This is a first time user and a very small test, nothing serious, but I learned something. I set up a single user accessing a single SSD via SMB and NFS.

TrueNAS is a bit confusing as a product. It’s a commercialized evolution of FreeNAS by iX Systems. It is still free and open source. TrueNAS Core was the original product and runs on FreeBSD. It’s being deprecated in favor of TrueNAS Scale running on Linux. So I’m only looking at Scale. Scale used to use Kubernetes to manage services but is migrating towards Docker instead. That’s created some drama with TrueCharts, a third party company that published a lot of popular TrueNAS Scale applications for installation. That’s over now but presumably the Docker ecosystem will substitute.

Compared to OMV, TrueNAS makes a very good first impression as a serious, professional product. It also feels like overkill for a home setup but maybe that’s OK. The docs are quite good, succinct and thorough. I’m having a bit of trouble because the TrueNAS Core docs seem more complete but are just a little out of sync with how Scale works. Scale has its own docs but they seem a little less organized. Still the docs are great. And community support is good, lots of nice answers on Reddit and TrueNAS’ own forum.

The initial setup experience seems faster than it was in OMV, despite TrueNAS having more complex features. Maybe that’s just because I’ve learned more about NAS setups in general, or maybe it’s because TrueNAS is nicely designed.

Fancy features

There’s some interesting advanced features for share types. Like early on you can designate a filesystem as case-insensitive if you’re only using it for SMB. There’s presets for multiprotocol SMB/NFS shares, for write-once-read-many SMB setups, etc. I don’t know if I need (or trust) these but it could be quite useful if they work well.

TrueNAS has elaborate support for creating virtual machines with KVM. It also has containers, and Docker, and Core made good use of BSD jails. I don’t need any of that stuff, that’s what Proxmox is for.

TrueNAS gives you access to ZFS snapshots. And it has cloud backup support. The latter looks more like a “replicate to cloud” feature but in combination with snapshots that could get you versioning. I didn’t explore this but it looks promising.

TrueNAS also has an app store and a bunch of installable apps. Some seem useful to have tightly bound in your NAS: SyncThing or Nextcloud are great. Others I’d rather run in separate Proxmox guests, like Plex or a Minecraft server. Also with the TrueCharts drama the world of community contributed apps is a bit in flux, but I bet that’ll work out. Moving to Docker is a good choice.

Complexity vs. low-spec systems

TrueNAS really wants to be a system for enterprise bullet proof storage. It’s very good at that, if you want to spend $2000+ on a storage array I’m sure it’s your software. But I’m sitting here with a $200 mini PC and a $100 USB drive. Is TrueNAS for me? Sorta, it will work, but it will nag you.

TrueNAS is all-in on ZFS. And it really, really doesn’t want you to lose your data. It really wants at least 2 storage disks and would be very happy to use 8 or more. It is possible to set up TrueNAS using a single disk (technically “striped mode”, but with just 1 disk). But the software complains and warns you at every opportunity that what you’re doing is not safe. Which, fair enough, but for my little home use case really it’s what I want.

On the flip side if you want to have 2 disks and mirror them or have 8 disks and some fancy RAIDz2 setup with a separate log device, TrueNAS totally is the product for you. Which, honestly, is probably a good idea for a real storage array.

There’s a similar nag if you try to use TrueNAS to share a USB drive. It complains “‘SSD’ is consuming USB devices ‘sdb’ which is not recommended.” Again, there’s good reasons for that but it ignores the reality of how good USB has gotten and the value in using consumer hardware for small projects. AFAICT it just complains once and you can ignore it.

I don’t know. Overall TrueNAS still feels like overkill to me. OTOH it’s not that hard to set up and you can run it for a small storage array. So maybe it’s worth it, just ignore the extra complexity you’re not using?

OpenMediaVault first use thoughts

I’m looking for a good NAS system to run inside Proxmox. Proxmox is great at managing disks but doesn’t have anything for SMB/CIFS, NFS, etc. There’s lots of ways to add a NAS as a guest system in Proxmox. TrueNAS is very popular but is complicated and overkill. So I gave OpenMediaVault a try.

OMV is good but not great. My biggest issue is it’s not very professional, particularly when it comes to docs. Also system design. But it is a solid complete product and has a lot of plugins. There’s an active user community but often the advice you find in forum threads is pretty amateurish.

Basic setup is straightforward but has a lot of steps. I found this guide useful. Basically you install OMV. Then to add a share you add a new drive (not the system drive), create a file system, then create shared folders in it. Then you make users (or allow guest access). Then you configure SMB or NFS or whatever to serve the share. By default the system supports NFS, Rsync, SMB/CIFS, and ssh. It all works pretty well and it’s nice having a complete product in a web GUI.

Where things get creaky is extending it. Take backups. There’s no built-in backup system for data drives (a bit of a surprise!) There’s several plugins: rsnapshot, timeshift, borgbackup, ... There’s also a “USB backup” that I can’t find any real docs for. But the description says “Automatically synchronise a shared folder to an USB/eSATA/SAS/SD device” and that leaves me wondering if they’ve confused synchronization for backups.

Another example of sloppiness: the flashmemory plugin, an OMV extra, that replaces directories like /var/log with a folder2ram filesystem so you don’t wear out a flash drive with write amplification. Nice idea! It works fine. But if you look closely it looks like it never automatically syncs the logs to disk, so when you reboot you lose them. Maybe? I tried testing it and got inconclusive results.

I’m also disappointed OMV doesn’t support ZFS. There is support for a plugin, and maybe that works great, but having it not in the core makes me nervous. (The outdated “not for public” docs don’t reassure!) Proxmox supports ZFS great, so one option is to have Proxmox manage the disk pool and pass through virtual disks to OMV instead of hardware devices.

I’m using ext4fs in OMV for now. It also supports btrfs, that’s it’s fancy filesystem, but that’s not the one I’d choose.

OTOH there’s a lot of plugins for OMV and it’s all easy to get working! Some curious omissions: there’s support for S3 and OneDrive for instance, but no generic rclone support which would support so much more. On the good side someone literally started working on a Restic backup plugin today. Does it work? Can I trust it? Probably not!

It’s all just a bit more fast and loose than I want for a store of precious user data.

So now I think I need to try TrueNAS again. I tried it briefly and it felt like overkill. But OMV feels like underkill, so... TrueNAS is really confusing right now though. Their old TruNAS Core FreeBSD product is being phased out with TrueNAS Scale (Debian) taking over. OK, fine. But somehow it has Kubernetes inside it? Also TrueCharts has historically been a big part of the ecosystem with their add-on apps but there’s crazy 🤡 drama there. The whole thing still feels like overkill, particularly when it comes to them having their own hypervisor features.

I just want a nice little web UI wrapper for SMB, NFS, SFTP, and Restic.

I pushed Claude to suggest some less well known products. It came up with Rockstor, XigmaNAS (NAS4Free), EasyNAS, and Openfiler. Also Unraid (not open source but not very expensive) or Nextcloud (does a bunch of other things I don’t need).

Maybe I give up and just run a Debian VM with old fashioned text file configs like we’ve been doing for decades.

OpenMediaVault setup notes

Setting up a little NAS with OpenMediaVault. First time user, my notes on what I did. This guide helped.

VM configuration

  • Make a Proxmox VM with 4GB RAM, 8GB of disk, and 2 CPUs. Legacy DOS BIOS.
  • Add a USB passthrough by device ID for an external disk that’s plugged into the machine
  • Enable qemu-guest-agent (note qemu-ga won’t start and gives a confusing error in the VM without this.)

OMV Installer

Basic Debian installer, mostly just take defaults.

OMV Configuration

Configuration mostly done via OMV’s web UI. Note at first it’s only available via http:, not https:. Default login is admin / openmediavault

  • Apply system updates
  • Change time zone to UTC
  • Change the admin login password
  • ssh: add myself to ~root/.ssh/authorized_keys
  • ssh: Install Tailscale
  • Reboot OMV from the web console

That’s a basic setup. After reboot....

And configuring the storage disk, mostly steps in the Web GUI

  • Storage > Disks: Wipe the disk in the Web UI: I aborted this when it started doing dd if=/dev/zero. But it did something with GPT to the partition table first, so probably a good idea.
  • Storage > Smart: Set up SMART for the external hard drive on USB
  • SSH: apt install hdparm so I can test disk speed (39 MB/s for a slow external drive.)
  • Storage > File Systems: Created an ext4 filesystem on the USB disk. This took a very long time!
  • Storage > File Systems: Mounted the filesystem. It ended up under /srv
  • Storage > Shared Folders: create a shared folder named “test”. Admin and Users are read/write, Others are no access
  • Users: Create a user “nelson” with a password
  • Services > SMB/CIFS > Settings: Enable service, set Workgroup
  • Services > SMB/CIFS > Shares: add the test shared folder I created

And using the disk from a client:

  • On Windows, open \\192.168.3.37\ and type in credentials (after a long pause)
  • On Linux, see the share with smbclient -L //192.168.3.37/
  • On Linux, mount the share
    apt install cifs-utils
    sudo mount -t cifs //server_ip/share_name /mnt/smb_share -o username=your_username,password=your_password
  • The name \\omv\ also works using the hostname omv. Also omv.local resolves as a hostname, Avahi is running.

Beelink N100 boot when power restored

I got a Beelink N100 for a little server. By default if the power is cut, it doesn’t boot again when it comes back on. Annoying for a server!

To enable it, go to the BIOS settings. Under Chipset > PCH-IO Configuration -> State after G3, set that to “S0 state”. There’s screenshots for all this in this Reddit post.

Sure is obscure huh? Why AMI doesn’t have a simple to understand top level setting for this, I don’t know. FWIW PCH is the Platform Controller Hub, the chip (or part of CPU) that controls various parts of a PC system.

PCH defines various power states like “full on” and “soft off”. G3 is “Mechanical OFF”, the name for there being no electricity at all. By default my Beelink goes to S5, which is “Soft Off”. So I’m telling it to go to S0 “Full On” instead after a G3 event.

Setting up a new Proxmox server

Some notes on setting up a new Proxmox server for the non-profit I’m helping. There’s almost nothing to do, got to be the simplest install ever. Still a few steps:

Hardware tasks.

  1. Enable BIOS to boot on power restoration
  2. Quick run of memtest from Proxmox boot ISO
  3. Quick run of s-tui from Linux to heat test

Basic Proxmox setup

  1. make a USB installer
  2. boot it and use the graphical install
  3. installer options:
    choose ZFS Raid0 for the simple filesystem on the SSD
    choose UTC timezone
    type a simple to remember root passwrd
  4. after reboot, open web console and set root password to a strong password from 1Password

Root shell customizations

Make as few changes as possible on the PVE itself. But a few are useful, log in with ssh as root.

  1. Add an SSH key to ~root/.ssh/authorized_keys
  2. Run the tteck post install script and accept all its defaults
  3. Run the tteck microcode installer, I picked 3.20240514.1~deb12u1
  4. Install Tailscale
  5. Run pveam update to update the list of templates for containers

GUI customizations

  1. node > System > DNS: update search domain and DNS servers
  2. node > local > CT Templates: pick templates for containers

Proxmox / KVM cpu types

When you create a VM in Proxmox it gives you a bunch of options for what CPU to emulate. The right choice is probably “Host” if you’re not using Proxmox’ machine migration features.

I’ve always chosen the default, x86-64-v2-AES QEMU, without knowing why. There’s a zillion options for various small differences in Intel and AMD CPUs, also QEMU virtual processors. Turns out the right setting for me is “Host”. That means no particular emulation, just pass through whatever the hardware has.

It should be more performant but I’m not sure how much. I doubt the emulated CPUs are doing a full interpreter environment, but OTOH they talk about emulating microcode so it has to be at least somewhat complicated. This blog post has some measurements showing Host is 3-10% faster than KVM64.

This is all well documented, see “CPU Type”. The important parts:

Usually you should select for your VM a processor type which closely matches the CPU of the host system, as it means that the host CPU features (also called CPU flags ) will be available in your VMs. If you want an exact match, you can set the CPU type to host in which case the VM will have exactly the same CPU flags as your host system.

Why isn’t this the default? Because it makes migration awkward.

This has a downside though. If you want to do a live migration of VMs between different hosts, your VM might end up on a new system with a different CPU type or a different microcode version. If the CPU flags passed to the guest are missing, the QEMU process will stop. To remedy this QEMU has also its own virtual CPU types, that Proxmox VE uses by default. ... If you don’t care about live migration or have a homogeneous cluster where all nodes have the same CPU and same microcode version, set the CPU type to host, as in theory this will give your guests maximum performance.

With the QEMU CPU, /proc/cpuinfo in the VM shows “QEMU Virtual CPU version 2.5+”. With the CPU type set to “Host” it shows whatever the actual hardware has (ie, “Intel(R) N100”).

I’ve apparently been running one VM as Host for months now with absolutely no problems. I converted the other one from QEMU to Host.

NFS still a tar pit in 2024

I was dorking around with a new NFS server and ran mount testserver:/test /tmp/test on my main computer. Then I turned off the testserver VM and forgot about it. Classic mistake, one I’ve been making occasionally for over 30 years.

The NFS disk in /tmp/test was still mounted on my client machine. And because I supplied no options to the mount command, it was a hard mount by default. Which means anything that accesses /tmp/test will get stuck in device wait, very hard to interrupt. I first noticed this because my restic backups were failing. It tried to back up /tmp/test and got stuck and the backup failed. (Why am I backing up /tmp? Lol.)

The usual fix is to supply some options to the NFS mount so it’s interruptible or has a timeout. Some options to know of: soft, timeo, retrans, intr. My fstab mounts things with this cargo cult set of options: x-systemd.automount,x-systemd.requires=network-online.target,x-systemd.device-timeout=10s. No idea where I got that, not sure it even actually works. Reading docs now I think that 10s timeout is for the initial mount only. ANd why does systemd need to be involved with its own bizarro thing? Who knows.

I also don’t understand why NFS doesn’t have some basic keepalive / server liveness test in its client. Maybe because NFS was originally connectionless and sort of loosey-goosey? I thought NFSv4 made all that much better. Maybe there’s some way to configure it. But the default options on Linux in 2024 are a tar trap.

I tried a bunch of things to unwedge my client. umount -f, which fails. lsof to see what processes had it open preventing the umount, which hangs forever. I finally gave up and just rebooted the NFS client. Awesome.

The underlying problem is network resources are not local resources. Software likes to assume that commands to a hard drive will either succeed or fail, not just hang indefinitely. But with a network filesystem they absolutely can hang. Even with a local one: modern hard drives are complex devices.

First impression of NixOS

I thought I’d give NixOS a spin after chatting with Jeff N. I had a great experience, I went from zero knowledge to a working web server in under two hours. And that includes lots of time writing this blog post, reading Mastodon, etc. And it was fun too!

I got this done mostly by asking Claude to tell me what to do: who has patience to read docs? It’s fun to learn something new this way. Also using this Wiki page and this baby steps tutorial. Julia’s notes are good too.

Update: I did this all as a Proxmox VM. There’s also notes on installing NixOS in a Proxmox LXC container.

Some basic concepts

I’m still trying to work my head around what Nix does. My impression is it’s similar to a Dockerfile or a puppet/ansible script, it’s a config file that creates a working Linux environment for stuff to run in. The difference is Nix has fancy design so everything’s managed, rollbacks are possible, etc.

NixOS is not Nix. Nix is the package manager, NixOS is an operating system built using the Nix package manager. Nix is like apt, NixOS is like Ubuntu.

The master configuration for NixOS and all the things running in it (like a web server) is in /etc/nixos/configuration.nix and has its own syntax. Almost the whole system is configured here. Nix folks have written little shims to take configuration directives from this file and write them into whatever weirdo format the ancient Unix utility might expect. (I hear the sendmail.cf generator is sentient but no one can understand what it’s saying.) You edit configuration.nix, check it into git, etc. You use nixos-rebuild switch to tell the system to implement the changes.

I’m looking at NixOS for a whole system image but there’s also a way to use Nix for your personal user environment that’s broadly similar.

There’s an effort to make bit-for-bit reproducible builds for NixOS which has nice affordances for security. But that’s not the only reason to use NixOS, more a happy side effect.

Install experience

First attempt for an install was with the minimal NixOS ISO (still 1GB!). But they aren’t kidding about minimal, this thing has you running fdisk yourself and leaves you with an unconfigured system. The graphical installer (3.5GBish) partitions a disk and gives you a basic working system when it’s done, so that’s easier.

After the default install the system reboots. 2.7GB is consumed on the hard drive and there’s 89 packages (not counting documentation packages). There’s about 10 processes running other than the kernel and all its threads. They all run out of /nix/store. They include

  • systemd running journald, udevd, oomd, timesyncd, logind
  • dbus-daemon
  • nsncd: a shim for name service (this one?)
  • Networkmanager

That’s a remarkably small system.

/bin and /usr/bin are nearly empty. There’s about 10 directories in my $PATH but much of what I’d expect to find is in /run/current-system/sw/. All the binaries there are symlinks into /nix/store. They’ve been dynamically linked with libraries like libc referencing paths in /nix/store.

NixOS installs a fairly complete Linux environment, at least it has less, bash, rsync, ssh. No sshd, python, or vim though. So why 2.7GB? As near as I can tell there’s a lot of stuff in /nix/store that’s not in my current environment, like a whole install of python3.11. Those binaries seem to work if I run them directly but I’m guessing I’m supposed to configure the NixOS system to officially use them if I want them.

The /nix/store can apparently get very large but there’s ways to manage it. I’m not sure if there’s an easy way to say “prune everything off the disk I don’t actually use” to get the install size down to 100MB or so.

Installing some packages in NixOS

First up, add an ssh server so I can log in easily. That’s as simple as editing configuration.nix to uncomment the line services.openssh.enable = true and then running nixos-rebuild switch to make it happen. The switch takes about 6 seconds. Various docs reference having to configure the firewall or enable password login, I didn’t have to do either with the NixOS GUI install’s defaults. (There’s some magic that allows ssh through the firewall if you enable it.)

I tried a rollback to remove ssh again. Easy as running nixos-rebuild switch --rollback. Apparently nix is keeping a history of what it’s done that it can undo. The rollback kills the sshd so I can’t log in anymore. My active sshd was still running, so I guess it doesn’t kill everything. (That implies many things about just how much state Nix will alter. Files, not memory, is my guess.)

Adding other shell utilities just requires listing them in environment.systemPackages. (Or maybe in a user environment, don’t understand that yet.) Whitespace delimited list. I did “joe git zip unzip” for now. And another rebuild switch and now I have those binaries available.

Final project was a hello world web server. I had Claude do this part for me.

  # Enable Caddy web server
  services.caddy = {
    enable = true;
    configFile = pkgs.writeText "Caddyfile" ''
      :80 {
        root * /var/www
        file_server
      }
    '';
  };

  # Create a simple HTML file
  system.activationScripts.createWebRoot = ''
    mkdir -p /var/www
    echo "<html><body><h1>Hello World from NixOS!</h1></body></html>" > /var/www/index.html
  '';

  # Allow HTTP traffic
  networking.firewall.allowedTCPPorts = [ 80 ];

That all just worked, thanks Claude! The firewall change was necessary: without it Caddy was running but unreachable outside this machine. iptables -L confirms that there is a firewall running (the default for NixOS), the chain nixos-fw seems most relevant. It’s letting in only ssh and http and ICMP ping.

Things to learn about

  • Updating packages from network
  • Scripting creating a new NixOS system from the environment file
  • Per-user Nix config vs system-wide
  • Nix state tracking, how rollbacks work
  • Logging
  • Recommendations for running actual production services in NixOS
  • Pruning disk usage
  • The ecosystem of Nix packages
  • nix-shell
  • WTF a flake is

Thoughts

This experiment was a good experience. Over the years I’ve tried a bunch of ways to automate setting up Linux system environments and gotten very frustrated every time. NixOS I had up and running in an hour and I feel like I could use this for real.

What would I use it for? Not sure, need to think more. I’ve been considering rolling my own NAS, a setup with NFS and Samba and syncthing and restic. I was just going to hand configure it but maybe NixOS would be a nice way to do that in a more managed way. As a VM in Proxmox I guess? Or maybe just an LXC container. Or just as a Nix thing in a general purpose VM, not sure if Nix gives me the separation I’d otherwise use Proxmox for.

I’ve run into some usability warts. nix search does not work as the config file suggests, you have to do some complicated set of flags for “experimental features” (this is apparently fixable but is a bad experience for a newbie!) The configuration that the NixOS installer created throws various warnings when you build with it. But stuff mostly seems to work.

The NixOS docs seem pretty good. I haven’t read them much but Claude has and that works great for queries. When I’ve looked stuff up myself there’s clear explanations for what I’m trying to learn.

I love learning new stuff like this. Claude was a big help.

ssh firedrill: patches, fail2ban

Major new ssh vulnerability including a remote root exploit of SSH servers. So far the exploit has only been demonstrated on 32 bit systems and that takes several hours of hammering a race condition. But it’s likely to get worse over time.

The easy fix is to install an update; here’s how to do that in Ubuntu. The openssh release notes are also helpful. They released version 9.8 to fix it. Ubuntu backported that fix to older versions. Unfortunately I have a system stuck at Ubuntu 23.04 which is not getting updates anymore. So I need a temporary workaround.

I went with installing fail2ban. I do not like that system, it’s a gross hack with way too many config options that can completely break your system. But I got it done. The ubuntu fail2ban by default doesn’t ban anything (I think). You copy jail.conf to jail.local and then edit the sshd section to enable it. There’s a bunch of outdated guides, I ended up using the Claude AI to figure it out.

Anyway, end of the day fail2ban scans your ssh log files and creates IP table rules to block aggressive clients. Not a full fix but should make a race condition exploit a lot harder. You can see what fail2ban is doing in the moment with fail2ban-client status sshd or use iptable -L to see the rules it’s creating and removing. Lol, just realized I log in with CGNAT. So some other Starlink user on the same IP address as me could conceivably block me from logging in. Oops.

Another option mentioned in the release is to set sshd’s LoginGraceTime to 0. That means “no limit”, so clients never get dropped if they hang during login. But that now opens you to a DDOS, I think by default sshd allows 100 simultaneous logins and if someone’s trying to exploit the race condition they’d quickly fill all those slots. Not positive.

The last thing I did was look at my bash history to see what hosts I ssh into to make sure they are all updated. Unfortunately you can’t read known_hosts anymore to see where you’ve logged in since the hostnames are hashed. Again Claude AI to the rescue, here’s what it recommended:

history | grep ssh | awk '{for(i=1;i<=NF;i++) if($i~/^[^-].@./) print $i}' | cut -d'@' -f2 | sort -u

I should probably disable ssh entirely on my public interfaces and require tailscale to log in. But despite a year+ of reliability I still don’t fully trust tailscale, what happens if it breaks for some reason and I can’t log in?

Simple monitoring for small projects

Just set up some long-overdue monitoring for small projects like my blog and linkblog.

updown.io makes HTTP requests to your server and alerts you if they fail or do not contain expected contents.

healthchecks.io alerts you if an HTTP URL on their server is not pinged in a configurable amount of time. It’s intended for cron jobs; if your job doesn’t load the URL in time you get a warning.

Both are free for initial usage, enough for at least a year of a small project (or more). And low cost beyond that. They’re both professionally made and have been around awhile. I’m impressed with how many integrations they have. Email notification is the default but there’s Slack, SMS, etc as well.

shout-out also to scrutineer.tech which runs a simple RSS feed warning you about upcoming SSL certificate expiration.

Proxmox production container for linkblog

Starting to containerize some stuff that I originally migrated to a VM. My linkblog, for a start. I need a generic Linux environment that’s fairly beefy; libc, not musl. Ideally I’d bake all this into a reusable container but I’m rolling it by hand for now. Here’s my notes.

Container creation

  • Create a unprivileged container with hostname “blogs”
  • Add root password, my SSH key
  • Use the Ubuntu 22.04 (or latest) template. Ubuntu so I can get deadsnakes for Python versions. I’d like latest Ubuntu but can’t because Playwright (the screenshot library I need for the app) only supports LTS releases.
  • 16GB of disk, 4 CPU cores, 16GB of RAM, 1GB of swap. Or more, these are all soft limits so it may be better to set these higher
  • Default networking but enable DHCP instead of static.
  • Consider adding access to vmbr1 for the NFS server.
  • Edit the container options to make it start on boot

Linux configuration

  • Start the container, launch a console, log in as root with password
  • apt update; apt upgrade
  • apt install joe sudo curl avahi-daemon git zip unzip rsync webp sqlite3
  • locale-gen en_US.UTF-8
  • Install tailscale
    curl -fsSL https://tailscale.com/install.sh | sh
  • Shut down container
  • On the Proxmox hypervisor server, modify /etc/pve/lxc/???.conf to give access to tailscale in the container
  • Start the container
  • Log in on console again
  • tailscale up, approve the URL to join the machine. Consider disabling tailscale key expiry in the web console.
  • Use ordinary ssh client to log in as root@ ts.net tailnet name.

(not sure avahi-daemon is working here, I can’t use the .local DNS name I am expecting. I tend to use Tailscale to connect to things anyway.)

Linkblog configuration

Specific to my application, but some generic notes here also about creating a prod environment for anything.

User setup

  • As root, make a user for the project.
    adduser linkblog; adduser linkblog sudo;
  • Log in as linkblog@ with password
  • ssh linkblog@localhost, to create the ~/.ssh directory.
  • create ~linkblog/.ssh/authorized_keys

Linux configuration

  • sudo apt install python-is-python3 python3.10-pip
  • Install Node18 from nodesource

App configuration

  • mkdir ~/prod
  • cd ~/prod
  • rsync -a nelson@sf.somebits.com:~nelson/somebits/linkblog/prod/ .
  • rm -r venv
  • python3 -m venv venv; source venv/bin/activate; python3 -m pip install -U setuptools pip wheel
  • pip install -r requirements.txt
  • sudo venv/bin/playwright install-deps
  • shot-scraper install

Testing and running for real

  • ./update.sh -f
  • cd site-generated; /usr/bin/python3 -m http.server 9191
  • Test HTML load in web browser
  • Push site manually and accept ssh host key.
    ./update.sh -f -p
  • Install crontab entry to run update.sh for user linkblog

Feed2toot for @somebitslinks@tech.lgbt

Separate cron job to update a Mastodon account from the RSS feed. Does not depend on any of the linkblog code, just the RSS feed.

  • As user linkblog...
  • mkdir ~/mastodon; cd ~/mastodon
  • python3 -m venv venv; source venv/bin/activate; python3 -m pip install -U setuptools pip wheel
  • pip install feed2toot
  • copy over the install from the old system. This gets credentials, config, and state.
    rsync -av --exclude=venv nelson@example.com:~/src/mastodon/linkblog-toot/ .
  • run a quick test, should show posting nothing if there are no new stories
    feed2toot -n --debug -c feed2toot.ini
  • Install crontab entry to run go.sh for user linkblog

TODO

  • Package linkblog as a proper Python package so deployment is better
  • Write linkblog code to manage crontab (or at least emit the line)
  • Write linkblog code to run test server

Intel QuickSync GPU transcoding in Proxmox

Notes on video hacking, efficiently transcoding H.264 to H.265 video. I’m updating my old to65 function to work in my new Proxmox environment. The key idea here is to use jellyfin’s build of ffmpeg with Intel QuickSync codecs to transcode video faster. The challenge is making getting a Proxmox guest OS that can use that. Both to set up the container and also to make sure it has the permissions necessary.

The expedient solution I set up was to use a tteck script to install jellyfin. That’s a whole server environment and is overkill but it installs the /usr/lib/jellyfin-ffmpeg/ffmpeg I need. It also sets up the container to access the Intel GPU. The main thing it does is make the container privileged: not ideal (nor necessary) but sure smooths things over. There’s also some entries in /etc/pve/lxc/104.conf for mapping the necessary devices, particularly /dev/dri/renderD128.

Anyway installing with that script is really all I needed. With that my i5-12600K server is transcoding a 1080p video at about 4x speed. Using 40% of one CPU core and intel_gpu_top shows me the Render engine is pegged at 100% (encoding?) with the Video engine also at 20% (decoding?). That’s more or less what I remember doing on the old native hardware, no surprise.

tteck also has a tdarr package. I should try that again; last time I did I couldn’t figure out tdarr’s UI. It’s perfect for what I need but I was scared it’d aggressively transcode all my video files, I really want to only transcode a few things.

Let’s Encrypt / certbot in 2024

I was an early adopter for Let’s Encrypt, back in 2016, then renewed in 2019. Over time I’ve accumulated a lot of cruft in my main web server related to it. To the certbot team’s credit it’s worked all this time with minimal intervention. I was adding a new virtual host domain name and needed to update the certificate, so I looked at it for the first time in a few years.

I was running certbot 1.10 or something; certbot 2.9 is current. So I used apt to remove the certbot packages I’d installed long ago from a PPA. And followed the new instructions to install from snap. This installs an executable in /snap/bin/certbot. It also installs a systemd timer to renew certificates that you can see with systemctl show snap.certbot.renew.timer.

I think I still have some old cruft lying around. /etc/letsencrypt was never purged so the new Snap picked that up, which is a missed blessing. I also have a /etc/cron.d/certbot which will renew, but only if systemd isn’t installed. So I’m just leaving that assuming it’s harmless.

Anyway, certbot reinstalled it’s time to reconfigure certificates. This is as simple as running certbot and accepting the defaults. It generates a single SSL certificate to be used for all the domain names it finds in your Apache configs. It creates Apache2 site config files named *-le-ssl.conf to reference the SSL certificate. Certbot also prompted me to switch from RSA to ECDSA keys. Sure, why not.

Renewal can be tested with certbot renew --dry-run. It seems to process all the files it finds in /etc/letsencrypt/renewal. I have an old one left behind from December for windhistory.com, which I think is no longer used so I removed it. My new one it has chosen to name for logsoflag.com, probably a name it picked years ago. It seems to be used for all my domains.

Another mild naming nuisance: the SSL certificate has Common Name (CN) feditrends.com. That’s one of my 9 domain names. Apparently certbot just picks the first name in an alphabetical list when making a cert for multiple domain names. You can override it but it’s a nuisance, so I’m just going to ignore it.

It all seems to work and honestly took less time to run than to verify what it was doing and write up these notes. I’ve made a reminder on my calendar to check in May a few days before expiration that the renewal worked automatically.

Small Linux distributions

Quick notes for further research on small Linux distributions that are none-the-less useful. See also this list of resources.

Components

MUSL is an alternative to GNU libc that is very small. It is a mature product that is actively maintained and used.

Of historical interest: dietlibc and uClibc. I think both are no longer being developed. See also this comparison of library features.

busybox is a set of userspace command line tools built into a small binary. It’s a mature product, widely used.

toybox is a rewrite of busybox with a non-GPL license. It presents itself as a reinvention / improvement as well and looks usable and under development. It’s about 740kb binary (compare 1110kb busybox) but has less implemented in it.

OpenRC, s6, runit are alternative init systems to replace systemd.

Linux distros

Alpine Linux is a MUSL and Busybox distribution. Very mature product and an enormous package database, it’s quite productive. The VM ISO image is 60MB.

glaucus is MUSL + Toybox. Just had their first ISO release recently, it’s 528MB (or 210MB compressed).

OS/1337 is a new project for a MUSL + Toybox Linux distro witih very ambitious binary size goals. No release, not clear if the developer’s enthusiasm will be matched by working code, but it’s got some well articulated ideas.

See projects using MUSL for a list of other Linux distros based on the small libc.

Wikipedia has a roundup of other small Linux distros. Worth splitting the CLI vs GUI distros, also those targeted at small RAM vs not.

What I haven’t found is a good list of really small glibc based Linux distros. busybox for instance still works with glibc, see these Docker images. When I looked at this in December I noticed that the locales and SSL were two major sources of space usage; those can easily be optimized.

Further afield

Beyond Linux from Scratch is a learning exercise, building a working Linux system from sources. Maybe a bit of overlap with Arch in being interesting for a source for ideas of a highly customizable Linux distribution. A stated goal of toybox is to allow building BLFS.

Unikernels are the idea of replacing a generic Linux operating system with a kernel specialized to run a single service as a single user. There’s a bunch of them, OSv is one I’ve read about a few times. NanoVMs are another cut at them; there’s some Proxmox support.

Distroless is one approach to building containers (for Docker) without shipping a Linux distribution inside the container. Makes particular sense for GoLang / Node / Java systems where you basically never interact with the user space tools.

Backing up Proxmox itself

Proxmox has great systems for backing up your guest OSes, VMs and containers. Including their configurations. But it has no affordance for backing up Proxmox itself. Mostly you don’t do much configuration on Proxmox but you do some, it’d be nice to be able to recover it. I finally found some docs on migration and restore hidden in the 7 -> 8 upgrade docs. A summary:

Backup: “all files in /etc”. Specifically named: files in /etc/pve, as well as /etc/passwd, /etc/network/interfaces, /etc/resolv.conf

Restore: /etc/pve/storage.cfg. Firewall configs /etc/pve/firewall and /etc/pve/nodes/<node>/host.fw 

It’s nice they tried but these instructions aren’t complete. At least in my reinstall I also had to pay special attention to jobs.cfg which configured the backup schedule. Also /etc/fstab.

And while I try not to put too much into Proxmox itself I at least need to install Tailscale for access. And an NFS server for one machine (although I may yet move that to a container). Those are outside the scope of the product so backing them up really is my problem.

Proxmox moving to a new server

I migrated my first Proxmox system to a new server. It went very well. Basically you just back up all the containers and VMs, restore them, and Bob’s your uncle. Took under an hour, more because I did a test run installing to an external USB disk first. Really I’m migrating to the same server, I just wanted to switch from btrfs to zfs.

Proxmox backups include not only the guest OS image but also Proxmox’ own configuration. The restore is smart enough to adjust the config to, say, handle that the virtual disk image now lives in ZFS. The only place anything failed is that my VM had a virtual CDROM mounted; the restore still referenced the image via BTRFS. Then again the CDROM didn’t even exist in the new zfs server, I no longer needed it. No big deal: the error message was clear and I could easily edit the config to remove it.

The other hassle was restoring Proxmox itself. There’s no way to back up a Proxmox server, just its guests! I think they’re idea is you’re using a cluster with several servers and so if one fails you just add a new host and have it learn what to do. Still seems like they should have a backup option.

For a small home user it’s good discipline to do as very little on the Proxmox server itself as you can. I made a checklist of things to set up on the new one, here’s a quick list:

  • update repositories and upgrade
  • configure /etc/fstab to mount my disks
  • configure backup disk as new storage type
  • set up guest backup schedule in the GUI (again)
  • add a system metrics server
  • apt install joe sudo avahi-daemon
  • install a user nelson for convenience but try not to use it
  • install tailscale and remember --accept-dns=false

I tried a couple of things to verify the new Proxmox was configured the same as the old without a lot of success. I was hoping that comparing /etc/pve would tell me more, that’s where Proxmox keeps its configs. But mostly it was stuff you’d expect to be different: crypto keys, details related to file system storage. Hard to find meaning in the noise. I was glad to find jobs.cfg though with a record of my backup configuration. (Note that /etc/pve is actually a pmxcfs FUSE filesystem for clusters; the actual truth lies elsewhere.)

Really pleased at how all this was. Virtualization is great! Next time will probably take half an hour at most and most of that time is waiting for disk images to copy around.

ssh attacks

I knew botnets testing ssh passwords was a thing but I didn’t realize it was this bad. Here’s one minute for my home server which I need to be able to ssh into.

Jan 11 01:14:00 tt sshd[294770]: Failed password for root from 98.97.59.56 port 27496 ssh2

Jan 11 01:14:09 tt sshd[294773]: Invalid user ftp from 212.70.149.150 port 62358
Jan 11 01:14:13 tt sshd[294773]: Failed password for invalid user ftp from 212.70.149.150 port 62358 ssh2
Jan 11 01:14:22 tt sshd[294789]: Failed password for root from 43.159.32.231 port 44228 ssh2
Jan 11 01:14:40 tt sshd[294795]: Failed password for root from 127.0.0.1 port 44192 ssh2
Jan 11 01:14:46 tt sshd[294816]: Failed password for root from 35.194.181.153 port 54910 ssh2
Jan 11 01:14:49 tt sshd[294818]: Failed password for root from 165.22.51.149 port 35608 ssh2
Jan 11 01:14:52 tt sshd[294838]: Failed password for root from 180.101.88.236 port 13566 ssh2
Jan 11 01:14:54 tt sshd[294838]: Failed password for root from 180.101.88.236 port 13566 ssh2
Jan 11 01:14:57 tt sshd[294838]: Failed password for root from 180.101.88.236 port 13566 ssh2

There are 97,354 of these attempts in five days, or a rate of once every 5 seconds.

The simple protection is to disable root login in sshd. I’d rather not deal with the requests. Some folks run ssh on an unusual port; that’ll at least cut down the traffic. fail2ban is also a popular solution but I’ve never liked how it works. Scanning logfiles? Really? And what if it blocks my legitimate logins somehow?

Here’s the top 20 users other than root being probed. Passwords really are a terrible form of authentication.

    796 admin

601 user
505 ubuntu
389 debian
238 test
147 oracle
92 ftpuser
88 postgres
72 deploy
67 git
66 mysql
59 hadoop
51 guest
47 student
47 es
47 centos
46 dev
44 test1
43 www
42 pi

Proxmox disk wear

Does Proxmox 8.1 wear out my disks? Maybe. A fairly idle Proxmox server is writing 40GB a day and I think most of that is wasteful. My SSD will last 10+ years at that rate but maybe I can make it better. So I looked more closely and in the end concluded most of the write activity is related to the guest operating systems I’m running, not Proxmox itself. Proxmox alone is writing about 50KB/second of data.

Wear is a concern with consumer SSDs; even a high end Samsung 980 Pro is rated for only 600 TB of writes for a 1TB drive. (Enterprise SSDs are 3x that or more.) It should be enough for an ordinary home server not doing a whole lot but a misbehaving system could make things bad. There’s several kinds of misbehavior with different solutions.

The Proxmox subreddit is full of posts like this or this with people noting high wear on their SSDs. The discussions are muddled. Someone says “it’s a problem!” and several people immediately respond “not a problem for me”. Inevitably someone says “buy an expensive enterprise SSD you fool”. Out of that noise I’ve found some pattern: Proxmox can write a lot of data.

Measuring disk writes

How do you measure the problem? The easy way is to use the Proxmox GUI to look at “Disks” for the host; the last column is “Wearout”. That’s current state of use and comes from SMART data. (Or should; my cheap N100 server doesn’t have the info.) Take a look, you may be surprised! I haven’t run Proxmox long enough to really know, my old Ubuntu server was running for a year+ without Proxmox and is only at 1%.

You can also get more insight by setting up system metrics on Proxmox. That has it export data to an Influx database when you can then visualize with Grafana.

More hands-on, you can measure write load with various Linux IO tools. Good old iostat is one way, ZFS has its own version of that:

$ zpool iostat

capacity operations bandwidth
pool alloc free read write read write
---------- ----- ----- ----- ----- ----- -----
rpool 72.4G 1.74T 28 21 1.91M 727K

That tells me the ZFS pool on my SSD has averaged 727KB a second since the last reboot. Watching zpool iostat 60 for minute-by-minute reports it’s averaging about 500KB a second on both Proxmox hosts I have. That’s about 40GB a day or 16TB a year. That still gives me decades before the device wears out. But it seems pretty wasteful, what’s doing all that writing?

Another tool is iotop or pidstat -d which show per-process IO stats. fatrace is also interesting, it gives you a log of file access.

Guest system write load

A simple explanation for the writes is the VMs or Containers running as guests on Proxmox may be writing to (virtual) disk, doing real work or writing logs. That’s got nothing much to do with Proxmox.

Proxmox has a nice tool for understanding disk I/O in guests; a graph right there in the GUI.

On my BTRFS machine the graph above tells me the Ubuntu VM guest is writing about 200KB/s. Another graph shows only one of the three containers has sustained writes, it says about 15KB/s. FWIW if I stop just the containers the iostat on the hypervisor goes from 500KB/s to 350KB/s, suggesting the three containers are writing 150KB/s between them. If I then also shut down the VM it saves another 300KB/s. The numbers don’t quite add up but I’m willing to believe that most of the disk writes are things the guest systems are doing. The Proxmox host itself is only writing 50–100KB/s, a small enough number I can ignore it.

On the ZFS machine where I measured 500KB/s writes, the VM itself says it was writing about 100KB/s. That still leaves 80% of the write load coming from the Proxmox hypervisor and maybe a mystery. Or maybe not, like I said the numbers don’t always add up.

Write amplification

A systems problem, write amplification is when writing (say) 1GB of application data results in a lot more than 1GB of write operations on the disk. Pathological systems can have 100x write amplification, a real problem. There’s various possible causes for this, I don’t really understand it.

On a simple test using iostat and dd I verified that writing 100MB of data from /dev/urandom in a VM resulted in about 100MB actually being written to the ZFS pool. Careful how you test; if something’s compressing the actual write might be less than the application data.

I think write amplification is a particular concern with ZFS depending on what RAID configuration you choose. Particularly if you run ZFS in a guest on a virtual disk backed by a physical ZFS pool. The VM itself can also be relevant, see zoned-storage for instance in QEMU. One drawback of virtualization is you’re so far removed from the hardware that things can get out of hand quickly.

Proxmox itself

On to the real question, does Proxmox itself write too much to disk? I’ve got a measurement that it’s only 50–100KB/s. Still, why that much? The Internet is full of advice on how to make Proxmox write less; this guide is particularly good.

The suggestion I was hoping would work is stopping services related to clusters if you only have a single node. The usual suggestion is to stop four: pve-ha-crm, pve-ha-lrm, pvesr.timer, and corosync. Of those only the two pve-ha services were even running. Stopping them didn’t really change the write load.

Another suggestion is to install log2ram and use that for /var/log instead of the real disk. Which could be a nice solution but you lose your logs in case of a hard system crash. Along those lines I’ve used tmpfs before for temporary directories. It helps as long as no one is expecting /tmp to be big.

Another recommendation is to change the vm.swappiness property; apparently Proxmox preemptively starts swapping things to disk when RAM is just 60% full. I don’t have any swap configured so that’s not going to change anything. Memory thrashing to swap could very quickly overwhelm an SSD.

File access details on Proxmox

I tried using iotop, pidstat -d, and fatrace to better understand what was going on. iotop is hard to read or possibly useless because ZFS or BTRFS themselves dominate the reports. pidstat -d is similar to iotop but different packaging. fatrace is a neat tool, and new to me. It shows which files are being written over the whole system. Sadly not how much are being written. Also it can’t show writes to a ZFS volume like my VM is stored on, since those aren’t files.

Shutting down all guests I’m left with proxmox itself. I’m still at 50KB/s or so, it’s hard to be sure exactly. fatrace tells me disk writes go to the following places:

  • pmxcfs: /var/lib/pve-cluster/config.db-wal. This is the PVE High Availability stuff I talked about turning off earlier. Even with those two services turned off there’s still some writes there.
  • pvescheduler: /var/lib/pve-manager/pve-replication-state.lck. Something related to a replication feature I’m not using. There are instructions on how to turn this off but they don’t seem to apply to modern versions.
  • pvestatd: /var/log/pve/tasks/.active.lock. Presumably an important part of PVE’s task scheduler.
  • pvestatd: /var/lib/rrdcached/journal/rrd.journal... Guessing this is the database for the nice graphs in the UI.
  • tailscaled: /var/lib/tailscale/tailscaled.log?.txt. Tailscale writes data briefly to its own log before pushing it to journalctl and removing it. This discussion has some notes about moving or disabling it. It seems to be about 30 writes a minute, 100 bytes at a time.

So that’s that. Most of my writes are coming from guests. Proxmox could be a little more efficienct, so could tailscaled, but what it’s doing now is not awful. And the amount of writes isn’t significant enough to worry about my disk lifespan.

QEMU virtual disks: clearing unused blocks

How do I get Proxmox VM backups to back up actual data and not disk blocks that were written once but no longer used?

Update: the answer for me was to enable the “Discard” option in the hardware options for the VM disk. That’s documented here in the Proxmox manual and for some unknown reason the default is off. After enabling this, trim in the guest OS propagates up to the storage; running fstrim -va in the guest resulted in the ZFS volume in the hypervisor dropping from 167G used to 64G used. This works with VirtIO block devices although next time I set up a VM I’ll still prefer using VirtIO SCSI. (On the other machine which I created with a Clonezilla clone it dropped from 69G to 24G. I wonder if Clonezilla cloned all the blocks even when they weren’t being used.)

Update 2: I also had to add the discard option in fstab for my ext4 filesystem. It’s not the default. I think it may be the default for btrfs and other file systems, not positive.

I ran into a funny problem today. The Proxmox backups of my main Linux VM were taking a tidy 56GB, about as much data (compressed) as there actually is on the 2TB virtual disk. Then I accidentally created a 100GB file (all of Wikipedia in ZIM format). I removed it, df shows its gone. But now a VM backup is taking 156GB. Presumably it’s backing up all the unreferenced blocks that were deleted but still have data on them. I suspect the QEMU clones I started with weren’t copying unused blocks.

You can see how much space ZFS has reserved for a virtual disk like this

root@sfpve:/home/nelson# zfs get used rpool/data/vm-100-disk-1
NAME PROPERTY VALUE SOURCE
rpool/data/vm-100-disk-1 used 167G -

I want that 167GB to be more like 67GB.

I tried using trimfs in the VM guest but it didn’t do much. It’s not clear the trim command ever makes it to the hypervisor host OS. Anyway, fwiw: /: 35 GiB (37617963008 bytes) trimmed. Right after a reboot I ran it again and got /: 139.2 GiB (149456355328 bytes) trimmed, but the second time it was back to 35 GiB. I have no idea what any of this means.

The Proxmox docs have details on how to make trim work in VMs get through to the host OS. They require the virtual disc be of type virtio-scsi and unfortunately I created the VM with a virtio-block. Apparently the SCSI storage type is the more modern and capable one. Also note this wiki page is 4 years old and I can’t quite tell if it’s really relevant now.

virt-sparsify is a QEMU tool for removing unused blocks from an unmounted virtual disk image, see here for more details. This looks perfect for what I need. But it’s not installed by default and installing it includes bringing in all of X11 in Debian, so I’m reticent. Also it requires operating on a file and Proxmox stores VM disks in block storage as a ZFS volume.

That same old Proxmox wiki page also has another solution; just use qemu-img convert to copy the virtual disk and you’re done. The qemu tools seem to be filesystem aware and smart about avoiding unreferenced blocks, I suspect I benefitted from that when I first created the VM disk by cloning my physical disk. But again this requires operating on files and Proxmox has them the disk image as a volume.

This discussion has some notes on using qm disk instead of qemu-img to operate on disk images; it’s able to work with volumes as well as files and presumably is just calling qemu-img to do the real work. I think it’d be as simple as using import to create a new disk that’s a clone of the existing one.

My fear with any of these methods is that they might change the block IDs or device names on my Linux guest and then it won’t boot. Updating /etc/fstab is easy enough but updating Grub is harder. (See my notes here, section “Fix the block IDs”).

The current state is not awful; backups are taking 3x as long and 3x the space as they should, but they all still work. But the problem will only keep getting worse. I think I’ll let it go for now but if I come back to this, ideas to try:

  • Switch to virtio-scsi for the VM and enable the trim command. See if that fixes it.
  • Make a qm disk import clone of the VM disk image and see if the new one is smaller. I can test that entirely with zfs get.
  • Clone the VM disk image to a file and use qemu-img or virt-sparsify to fix it.

Proxmox and data management

Still loving Proxmox but I’ve run into one product limitation: it doesn’t really have a good way of sharing filesystems across guest operating systems. If you want a disk managed by Proxmox to be available in a VM, or to share files between VMs, you pretty m uch have to use a network filesystem like NFS or CIFS (Samba). And Proxmox doesn’t run those itself servers. It seems like a gap in the product.

Proxmox has a fantastic system for managing storage for itself. You have your choice of filesystems but it really wants you to use ZFS. And it uses ZFS great. You can hand Proxmox a bunch of disks and it’ll set up ZFS, create ZFS datasets for container filesystems and volumes for VM disks, etc. It’s very nice.

But if you want to make, say, your home directory as a filesystem and share it to several VMs you’re on your own. There’s a bunch of ways to do this. What I’m doing now is I just make it a normal filesystem (or ZFS dataset) in Proxmox. Then I export them with an NFS server on the Proxmox hypervisor server and NFS mount the filesystem in VM guests. With all the overhead and (virtual) network awfulness NFS implies. Container guests have it easier than VMs, they can access the filesystem more or less directly with a bind mount.

The bummer here is I have to install and manage the NFS server manually on Proxmox. It’s easy enough to set up an NFS server as a Debian package but now I’m outside the Proxmox product, it has zero support for it. Same goes if I chose to use Samba for CIFS instead. For that matter Proxmox GUI doesn’t know about bindmounts for containers either although it’s easy enough from the Proxmox CLI, they even document it.

There’s fancier possible setups. One interesting possibility is to install TrueNAS in a guest VM in Proxmox. And use that as the NFS server with its management GUI. But then how does TrueNAS access the disks? The simple way would be to make a big virtual disk for the TrueNAS VM (backed by ZFS on the Proxmox hypervisor) and use it. But.. yuck! You lose most of the advantage of TrueNAS managing physical disks. The other choice would be to not use the physical disks at all in Proxmox and just pass the hardware through to the VM and let TrueNAS manage them. I may yet end up setting that up.

Another option coming is virtiofs. That’s a way for a hypervisor to share filesystems to a VM without a network filesystem. I think it’s pretty fully baked in Linux now but not quite ready in Proxmox.

A third option fully supported by Proxmox is Ceph, a distributed storage system. I haven’t looked at it, Ceph seems far too big and complicated for my needs.

The NFS server on the Proxmox hypervisor is working OK with me. Mostly I hate how abstracted it becomes, how far removed a disk write on a Linux VM is from what the actual hardware is doing. Performance went to shit yesterday on my system when I moved a 100GB file from a virtual disk in a VM via NFS to a physical disk. The VM’s IO response went to multi-second latency. Load average on the proxmox server went to 9 as a bunch of nfsds sat there hanging in device wait. To be fair, the disk copy happened at max speed so it did complete reasonably but it sure reminded me of the cost of all these abstractions and virtualization.

tailscale, Magic DNS, proxmox, and LXC

Frustrating interaction. tailscale MagicDNS breaks LXC under Proxmox. The solution is to start tailscale with --accept-dns=false on the Proxmox server. This is well documented by Tailscale but I missed it. In detail...

I have tailscale installed on the Proxmox hypervisor host, with MagicDNS enabled. If I start an LXC container then DNS doesn’t work at all in the container’s guest operating system.

The underlying issue is how tailscale does MagicDNS, how it answers DNS queries to supply its own answers for your hosts at *.*.ts.net. On Linux it does this by rewriting /etc/resolv.conf setting nameserver 100.100.100.100. The details of how it does this are complex because so many other things on a modern Linux box are also trying to overwrite that file. (Yes, systemd is involved). But it seems to work fine on the Proxmox server.

What doesn’t work is MagicDNS inside an LXC container. When you launch LXC it seems to start with a copy of whatever /etc/resolv.conf is in the Proxmox host. (Every time; if you reboot the container it gets a new copy.) So if tailscale is running it can pick up that 100.100.100.100 nameserver. Unfortunately the LXC guest operating system does not have access to that IP address (nor to any of your tailnet, it shouldn’t!) So DNS doesn’t work.

The simple fix is to turn off tailscale on the proxmox server: tailscale down. But it’s nice to have tailscale to access the server! If you run tailscale up --accept-dns=false then there’s no MagicDNS on the Proxmox server and /etc/resolv.conf is left alone. This setting seems to be sticky, it’s persisting even though I didn’t edit any config files.

Another option the docs mention is writing a /etc/.pve-ignore.resolv.conf file in the LXC container’s filesystem. That’s part of a general mechanism to have Proxmox not overwrite files in LXC guests.

Restic for backups

I finally have a better backup solution: Restic. This project has emerged as the open source favorite for backups. It’s easy to see why: it’s very capable and a very professional product. Don’t be put off by the scary 0. version number: there’ve been releases for seven years now. And it seems really solid.

For many years now I’ve relied on rsnapshot for backups. It’s nothing fancy but is straightforward. But it basically requires you have root access on both the source machine and the backup server. (rsnapshot stores actual copies of your files, complete with timestamps and owners). And it’s slow and creaky and, well, time for something new.

Restic is very fancy. The underlying repository datastore slices your files up into 1MB blobs and storing them in a sort of content-addressable store. Everything is encrypted and indexed by the SHA256 hash of the data. That makes verification, deduplication, etc straightforward and fast. The downside is the backup format is entirely opaque; you need the restic binary to work to restore files. (It is documented, but far too complicated to easily reimplement.) The upside is it is very efficient.

The product packaging is fantastic for open source. It ships as a single self contained Go binary. The docs are terrific including a quickstart that gives a vey good experience. It supports a wide variety of backup server types from local disk to sftp to cloud providers (or rclone if you want to do your own thing). There’s good tools for inspecting backups, verifying them, restoring them (including a FUSE mount). Also a first class tool for removing old snapshots. The tool gives a lot of confidence.

restic runs really well and fast. I can back up 50GB of my data to 38GB in the repo in about 6 minutes, about the speed the disk runs at (and this over NFS). An empty incremental takes just 10 seconds.

The one thing missing is some usability for system integration; you’re left writing your own shell scripts and cron jobs to use it. Fortunately there’s a CLI frontend called resticprofile which helps with that stuff, driven by a simple config file. It’s not quite as clean a product as restic itself but it has good docs and seems to work well. And what it does is not mysterious, it’s just invoking restic, so I’m not as concerned about the niceties.

Edit: another option for managing restic is backrest, a web GUI. Update Aug 2024: finally gave this a try, it is very nice.

It’s a real pleasure to use a nicely built open source tool like restic.

Update 2: offsite backups

I’m using Backblaze now for offsite backups. It seems to work OK and is fast and cheap ($6/TB/mo with no minimum. plus extra for bandwidth if you use much.) Was fairly straightforward to get working with Restic. Configuring the bucket is a bit tricky; I turned off encryption (restic is encrypted already) and file retention.

I tried SFTP briefly to a small server I have. It was very slow, like 6 minutes for 2GB (or less). To be fair my server is slow.

Update: system backup config

Here’s the fairly simple resticprofile config I’m using to back up my main Linux system. It backs up to local disk once an hour and keeps old dailies, weeklies, monthlies, and yearlies on a reasonable schedule. The only subtle thing here is I’m backing up in two separate jobs, once for my home filesystem and once for the system root.

version = "1"

[global]
  ionice = true
  nice = 5
  scheduler = "crond"
  restic-binary = "/usr/local/bin/restic"

[default]
  repository = "local:/mnt/backup/restic"
  password-file = "/usr/local/etc/restic/password"

# Everything but my home directory

[root]
  inherit = "default"
[root.backup]
  source = [ "/" ]
  exclude = [ "/home/nelson", "swap.img" ]
  one-file-system = true
  schedule = "*-*-* *:37:15"
  schedule-permission = "system"
  schedule-log = "/var/log/restic.log"
[root.retention]
  keep-hourly = 24
  keep-daily = 7
  keep-weekly = 4
  keep-monthly = 60
  after-backup = true

# My home directory

[home]
  inherit = "default"
[home.backup]
  source = [ "/home/nelson" ]
  one-file-system = true
  schedule = "*-*-* *:07:15"
  schedule-permission = "system"
  schedule-log = "/var/log/restic.log"
[home.retention]
  keep-hourly = 24
  keep-daily = 7
  keep-weekly = 4
  keep-monthly = 60
  after-backup = true

Making a private subnet for Proxmox guests

I want a second private subnet just inside my Proxmox host, for the guests. Main immediate reason is I want to export an NFS filesystem with root access from proxmox to guests but I’m too lazy to set up Kerberos. I trust my LAN but not quite that much; I don’t want any dumb device in my house to be able to be root here. So I set up a second bridged subnet just for Proxmox guests.

By default Proxmox sets up a bridge vmbr0 connected to the LAN of the Proxmox server itself. Guest VMs can just use that interface (often named ens18 in the guest) like it was an ordinary ethernet, do DHCP to get an address, route packets to the Internet via it. it’s very convenient. Mine is configured on 192.168.0.0/24.

But it’s pretty easy to set up a second bridge. The manual is quite thorough but not quite a cookbook. I used the GUI to do it.

First, on the Proxmox server, I used the Network config to add a new bridge named vmbr1. (I set an advanced option that’s not visible, mtu 9000.)

Then, in the hardware definition of the VM, I added the bridge there.

Finally in the Ubuntu VM’s Netplan configuration, I set up a static config. vmbr1 seems to be called ens19 in the VM:

network:

version: 2
ethernets:
ens19:
addresses:
- 192.168.240.2/24

Proxmox will live reload the server config if you press the button. I forgot how to reconfigure netplan in Ubuntu so I just rebooted. And it all worked: now the two hosts can talk to each other on 192.168.240.0/24 addresses without involving the ethernet LAN at all. Now I can configure the NFS server and client to use those addresses instead and have some extra isolation.

I’m not certain what would happen if a malicious actor gained access to my physical ethernet and then started trying to talk to the supposedly private 192.168.240.0/24 subnet. I think they wouldn’t get very far, since none of my hosts have the bridge connected to the ethernet? But I haven’t tested it. I’m not worried about that aggressive of an attack, mostly just trying to prevent accidents.

As a bonus I configured the MTU on the bridge to be 9000. This is an often-recommended setting for NFS performance, I think because NFS itself will use up to 8KB data packets for things.

Update

This has been working well for me. I did some simple testing of performance in August 2024. First, the network interface itself:

  • 0.15ms ping latency
  • 50Gbits/s iperf3 throughput

So the virtual network is plenty fast. I don’t know how to test actual I/O throughput properly for an NFS server. I did a simple fio command an AI suggested and came up with a number of about 1.12GiBytes/s which is 10x faster than the spinning disk that’s being served. The NFS daemon on the server got to about 15% CPU while doing it.

My conclusion is “fast enough for anything I’ll do”. It’s more than double the speed of a good SSD plugged in locally, so I don’t think the networking inside Proxmox is a huge problem. At least for max throughput, not sure about lots of little file operations.

# fio --name=test_network_throughput --ioengine=libaio --rw=read --bs=64k --numjobs=1 --size=100m --runtime=60 --time_based --end_fsync=1 --direct=1 --filename=./testfile.fio

test_network_throughput: (g=0): rw=read, bs=(R) 64.0KiB-64.0KiB, (W) 64.0KiB-64.0KiB, (T) 64.0KiB-64.0KiB, ioengine=libaio, iodepth=1
fio-3.33
Starting 1 process
test_network_throughput: Laying out IO file (1 file / 100MiB)
Jobs: 1 (f=1): [R(1)][100.0%][r=1161MiB/s][r=18.6k IOPS][eta 00m:00s]
test_network_throughput: (groupid=0, jobs=1): err= 0: pid=975385: Fri Aug  9 16:37:31 2024
  read: IOPS=18.4k, BW=1149MiB/s (1204MB/s)(67.3GiB/60001msec)
    slat (usec): min=2, max=803, avg= 3.97, stdev= 1.38
    clat (usec): min=16, max=4110, avg=50.14, stdev=13.62
     lat (usec): min=35, max=4114, avg=54.12, stdev=13.82
    clat percentiles (usec):
     |  1.00th=[   40],  5.00th=[   43], 10.00th=[   45], 20.00th=[   46],
     | 30.00th=[   47], 40.00th=[   48], 50.00th=[   49], 60.00th=[   51],
     | 70.00th=[   52], 80.00th=[   53], 90.00th=[   56], 95.00th=[   61],
     | 99.00th=[   81], 99.50th=[   92], 99.90th=[  143], 99.95th=[  165],
     | 99.99th=[  375]
   bw (  MiB/s): min= 1016, max= 1373, per=100.00%, avg=1148.65, stdev=42.11, samples=119
   iops        : min=16266, max=21978, avg=18378.44, stdev=673.71, samples=119
  lat (usec)   : 20=0.01%, 50=56.83%, 100=42.80%, 250=0.35%, 500=0.01%
  lat (usec)   : 750=0.01%, 1000=0.01%
  lat (msec)   : 2=0.01%, 4=0.01%, 10=0.01%
  cpu          : usr=1.55%, sys=9.94%, ctx=1102796, majf=0, minf=27
  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=1102756,0,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=1

Run status group 0 (all jobs):
   READ: bw=1149MiB/s (1204MB/s), 1149MiB/s-1149MiB/s (1204MB/s-1204MB/s), io=67.3GiB (72.3GB), run=60001-60001msec

Making peace with journalctl

Journalctl is systemd’s much-maligned replacement for syslogs. Crusty old nerds like me are mad it’s not just a text file. But the binary format actually has a lot of advantages, you can efficiently do simple time and metadata queries. I also like the color pager it gives you. Now that I’ve learned a bit about the journalctl tool I like it more.

journalctl -b
Entries since last boot. Solves the big problem of journalctl spamming you with useless crap from months ago. journalctl -b -1 will show you the boot before this one.

journalctl -n 100
Last 100 entries

journalctl --since '3h ago' --until '2h ago'
Time slicing. The since and until format is defined in systemd.time(7).

journalctl -u chrony or journalctl -t chronyd
Entries matching a unit name or syslog identifier

journalctl -g chrony
Entries whose contents match a grep expression. Note this does not match the displayed text of the metadata, it’s not the same as grepping a syslog.

journalctl -p 4
Level warning or more serious. The levels are the same as old syslog.

journalctl -r
Reverse order.

journalctl -e
Jump the pager to the end (like pressing G).

journalctl -n 100 -f
Display the last 100 entries and keep scrolling new entries forever

journalctl --vacuum-time=7d
Erase all logs more than a week old. Useful for making disks smaller.

journalctl --dmesg
Emulate dmesg, only showing kernel messages (but in a different format).

usermod -aG systemd-journal nelson
Anyone in group systemd-journal can run journalctl without being root, at least on Debian. Note this includes the ability to modify the journal.

The big thing missing is negative filters. I want to show all log entries that are not from the spammy sshd and cron units. Can’t really do it.

You can still do journalctl | grep of course. There’s also a JSON output format you can manipulate with jq or the like.

Post-virtualization thoughts

Phew, my physical to virtual server migration using Proxmox mostly worked. I’ve now moved my main life server, the one I’ve been maintaining or evolving over 25+ years, for the first time into a VM. And it mostly works! Some collected thoughts after the fact.

Checkpoints and backups at the VM level are nice. Really looking forward to that.

This plan of virtualizing a server by first making one giant VM is nice. I can now hive off services to run in specific containers or VMs at my leisure.

Jeff N talked me into trying ZFS on the Proxmox host and so far I’m glad for it. ZFS seems complicated to me but Proxmox is clearly built to take advantage of it. Checkpoints already work better than on BTRFS.

I’m still working out where stuff should live and how it should be shared once I start containerizing services. The obvious thing is to put the primary home for everything in a ZFS pool maintained by the Proxmox server itself (just with ZFS, no Ceph.) My home directory, my Music library, my Video library, a place for backups. Share to containers via bindmounts. Sharing to VMs is harder. I think NFS is the best solution for now until virtiofs in Proxmox is a bit more finished.

Yes, I said NFS. Ugh. I’ve got it working with an NFS server on the Proxmox host itself and the VM mounting it. Setting up automount gave me bad flashbacks to the 1990s, although of course systemd has its own way of doing things. But NFS implies a lot of overhead. Also the confusion of user ID mappings. I’ve never really administered NFSv4 which has some nice things but I may gouge my eyeballs out of I have to set up Kerberos. OTOH I’m really not comfortable letting anything on my LAN mount stuff with root privileges. A work in progress.

Syncthing is working OK in the VM right now. Syncthing is peer to peer but I think of it as hub-and-spoke, with this server being the hub. I think I want to hive that Syncthing hub off to its own container. I see myself possibly also setting up a separate Syncthing instance in some containers or VMs but that sure seems dumb. More work in progress.

Syncthing + NFS is scary. The risk is that NFS is unreliable, so the directory for a synced folder might disappear. And in a bad case Syncthing might interpret that as a command “Delete all the files” and propagate that to all the clients. This really happens in practice and is very bad. They have a sentinel file to protect against this, the .stfolder. I still can’t help but think that syncthing is best run on a local filesystem and not a networked one.

I’ve got Plex running in a VM. Right now it doesn’t have access to the Intel GPU, so it can’t do hardware acceleration of transcoding with Quicksync. There’s ways to make that work but I think I should prioritize moving Plex first into a container, the tteck scripts work with hardware transcoding.

Backups are a big question mark. I’ve generally used rsnapshot but that requires root access to work well, since it’s setting file ownership. And root access to NFS is a no. I’m thinking of switching to Restic for backups instead. How this will work depends a bit on my “who should own what files” question.

I also want to make VM and container backups in Proxmox itself, separate from my personal data. And I’d like to back up the Proxmox server configuration itself; it’s crazy there’s no tool for that.

I need to rethink using RAM for tmpfs in the VM. Also using a swapfile. It’s all working but I bet it’s not optimal.

Proxmox physical to virtual take two (QCOW2 and tar)

I had so much success with Proxmox for my little home server that I decided to install it for my big home server, the one doing the important stuff. Like before I’m going to ease the transition by first cloning the whole Ubuntu server into a VM in Proxmox, then work on migrating individual services out to their own containers or VMs one at a time. Much thanks to Jeff N for email support learning how to do this.

The interesting thing here is various methods for cloning a physical Linux system into a Proxmox VM and making it bootable. I did this once already using Clonezilla. This time I’m trying two other methods: cloning with a QEMU disk image and cloning using tar on the root filesystem. I’ve now gotten all 3 methods to work. I think the QEMU disk image is my favorite route, it’s relatively compact and straightforward. Every method could be useful though.

Battle plan

The server I’m starting with is this one, with this hardware. The challenge is I want to replace the Ubuntu server OS on the machine with Proxmox, with the former server now running as a VM under Proxmox. The nerds call this a P2V clone. The general challenge is how do you clone a Linux system and make it bootable? A particular challenge is I’m trying to do it in-place, I don’t have a second server to clone to. And in particular I want to re-use the existing 2TB SSD, and even though I’m only using 80GB or so of that any simple full mirror will take forever and waste the other 1920GB.

I’m particularly scared of the moment where I install Proxmox over the old server’s filesystem. Once that’s done the clock is ticking to get the new VM up and running so I have my important services back. So first I did a couple of dry runs installing Proxmox on an external USB drive I had lying around. Here’s the plan I came up with:

  1. Remove unneeded files from the server like the apt cache or the systemd journal.
  2. Make simple tar and/or rsync backups of all the files and put them in a safe place. This is the “in case of disaster” recovery option.
  3. Turn off some services on the server that I don’t want to start immediately when the server wakes up as a VM.
  4. Shut down the server and boot a Linux system rescue disk.
  5. Use the rescue disk to clone the old system disk via either qemu (path 1) or tar (path 2) to an external USB disc. See below for details.
  6. Install Proxmox on an external USB disc on the server hardware. Don’t wipe the old server system! We’re going to test stuff is basically going to work before committing.
  7. Create a VM in Proxmox for the newly virtualized server
  8. Copy the clone into the disk for the virtualized server. See below for details.
  9. Boot the clone VM and get it working.
  10. Once satisfied, repeat the whole process but install Proxmox onto the SSD instead. Burn the boats!

It helps to have some spare fast SSD USB discs lying around for these 80GB copies of things. I used several. One for copying server clone images to. One to install Proxmox on (temporarily). And a couple of small jump drives for booting Proxmox and rescue disk images.

What I’m not doing is what I did last time using Clonezilla to make the clone. That requires two running servers (the original and Proxmox). Also the destination disk needs to be as big as the source disk and have room left over for Proxmox; not possible with my replace-in-place plan.

One thing I mostly didn’t do was try to resize the root partition or disk image to be smaller, closer to the 80GB I actually need instead of the 2TB of the source disk. It would probably make things go smoother but all the various resize options are a little scary. I did experiment with this once I got the VM working, see notes here. For the real thing I did resize the btrfs filesystem itself to 200GB, but the partition and the disk are both still 2TB.

OVMF bios notes

I’m trying to do all this with EFI and Secure Boot. It worked on my physical server, it should work on the Proxmox VM too. Some notes on that:

  • For EFI you must select the OVMF BIOS when creating the VM in Proxmox. It’s not the default.
  • The OVMF EFI shell is weird. It’s a 5 second timeout, then a command line I didn’t understand, and then if you exit that you get to a simple TUI BIOS menu like you’d expect. You can also hit ESC to bypass the 5 seconds and command line.
  • There’s a bunch of confusing boot config options. If you’re just trying to boot a specific thing, try Boot Maintenance Manager / Boot From File and then browse the filesystems. Ubuntu’s boot works from EFI/ubuntu/shimx64.efi
  • I could not get OVMF secure boot to work in a VM with the System Rescue ISO. You’d try to launch it and it’d just return. It works if you turn off secure boot in OVMF. Maybe it’s an issue with the ISO virtualization.

Path 1: QEMU image clone of the whole disk

This method creates a .qcow2 file which is conceptually an image of every block on the source disk. I got the idea to try this from a Reddit discussion. You make the .qcow2 file and load that in to QEMU/KVM on Proxmox and you’re done. It’s pretty straightforward but some details tripped me up.

Making the QCOW2 file was relatively easy with these directions. The key command is qemu-img convert -O qcow2 /dev/sda disk.qcow2. Note this clones the entire disc, not just one partition, which means the partition table, GRUB, and the EFI stuff stays intact. Fortunately the QCOW2 format is smart about unused sectors so my 2TB disc resulted in a 80GB QCOW2 file and was relatively quick (10 or 20 minutes?). (There’s also a -c to compress which might help?)

Using the QCOW2 file on Proxmox was a bit trickier. These notes were useful to me. Basically you create a new empty VM in Proxmox with no install media, no virtual hard drive. Then you use qm disk import to create a new disk from your clone. It converts the QCOW2 file into whatever format Proxmox wants. In my case that was a 2TB raw file on BTRFS. Thankfully it’s a sparse file so it only uses 80GB of the disk. (ls -l shows 2TB, du and btrfs filesystem du show 80G. ZFS also makes sparse files.) This new disk had two partitions cloned from my Ubuntu install: /boot and /. But I didn’t have to do anything special for each partition to make them work.

There’s some subtle configuration things I had to do in Proxmox:

  • It’s essential to select the OVMF BIOS for the VM so that EFI booting works.
  • Proxmox wants an “EFI disk” configured. That seemed to be the default once I told it to use the OVMF BIOS. It’s only 500KB, not sure what’s in it, maybe the BIOS? It’s not your system’s boot partition.
  • It’s important to specify a cache policy for a BTRFS disk image. The default is “no cache” which apparently causes corruption issues; I used “write back”. No need if you’re using ZFS on Proxmox.
  • I had to fiddle with the boot order of things in both Proxmox and maybe the BIOS to get it to actually boot the partition for the cloned Linux system.
  • I did not have to disable secure boot. It worked with my virtualized GRUB setup from the clone without changes.
  • I had to set the CPU type to “host” for KVM virtualization to work, so that my Ubuntu system could load the kvm_intel module that snapd wanted. This might cause a problem if you want to migrate a VM to another host in a Proxmox cluster. But it might also give a performance boost.
  • The graphical console was a bit wonky under Ubuntu; sometimes it’d be distorted early in the boot and then fix itself in a couple of seconds. I tried setting the graphics hardware to “VMWare Compatible” and that fixed the distortion, but then sometimes boot would fail mysteriously. See below.

With all that in place, the cloned system booted in a VM! The old familiar GRUB menu and Ubuntu loaded like a champ. Really this was pretty easy.

I initially created a VM with no network device because I knew that DHCP meant my Proxmox server had now stolen the IP address the old server was using. Not good having a VM boot and use the same IP as its host! Fortunately systemd boots pretty nicely if there are no network devices. It gets messier if there are network devices that aren’t configuring themselves; there’s a 120 second timeout for that.

I had to make some changes to the newly virtualized Ubuntu server to make it cooperate better. I did this with Ubuntu’s own recovery mode, a rescue disk would also work. I did these without networking, then rebooted for networking.

  • setfont Uni1-VGA32x16 to make the font readable in the Proxmox graphical console
  • Remove fstab entries for other physical disks. (Note this can prevent your system from booting if you don’t, in which case you need a rescue shell.) In the new setup I’m going to mount those disks in the Proxmox server and then NFS mount them in to the Ubuntu guest.
  • Edit /etc/netplan configs to use DHCP (for now). Also the new VM ethernet device is named ens18.
  • Disable Syncthing in the guest VM. The Syncthing data is no longer mounted and I was scared it’d propagate a “delete all files!” message. I’ll need to get this set up again eventually, ideally as a new Proxmox container just for Syncthing.
  • Disable all my cron jobs for things like blog updates, backups, etc. Again these need to be set up eventually or migrated to special purpose containers.
  • Eventually I should install the qemu-guest-agent and enable it in the Proxmox config so everything plays nice together.

Update on Path 1

I redid this whole process for the real server and ran in to some new problems.

The graphical console was giving me trouble. As noted above, there’s some bug in the default graphics hardware where the Ubuntu boot has a corrupted display for the first couple of seconds. That was hiding an error message, so I switched to “VMWare Compatible” graphics hardware. That looked fine but then my main Ubuntu system wouldn’t boot, displaying an error “hardware has no pitchlock” which froze everything in the Ubuntu boot sequence after about 0.6 seconds. Note this error was only findable in journalctl, it had long since scrolled off the screen. Switching back to “Default” display console the system boots. I should learn about SPICE and serial consoles.

The underlying error I was trying to find in the console is my restored virtual disk wasn’t mounting cleanly. There was a complaint about the GPT tables. I’m very grateful I went through the partition shrinking exercise because I sort of understood this; somehow the virtual disk changed size just a bit (a few megabytes?) from the physical disk, which breaks the secondary GPT table at the end of the disk. Fixing this isn’t too hard, this time I did it just by running fdisk and then issuing the w command with no changes. That rewrites the partition table and all seems well. gdisk is another option for fixing it, and maybe parted could. All this is very spooky. I can’t think why it failed the second time. I did resize the btrfs partition to 200GB before taking the new QCOW2 snapshot. But that shouldn’t change the full disk size and certainly not by just a few MB.

Path 2: tar clone of the root filesystem

Disk images are unwieldy; why not just clone the Linux root filesystem with tar or rsync or cpio? In theory this should work just like it would have in 1975. In practice it’s tricky because EFI booting and GRUB are such a mystery.

I found a nice blog post laying out how it should work. Basically you use tar on the whole system to create a snapshot (ideally when it’s offline). Then make a new disk with a bootable EFI partition and a root partition. Unpack the tar into the root partition, then ✨ just use grub-install ✨ to magically populate the EFI partition.

The GRUB step is the confusing bit. The guide above recommends using a chroot to run grub-install as if your old system were live. That’s what ended up working for me. (SystemRescue has its own idea for repairing GRUB. I couldn’t make either method work and it looks like the docs there may be several years out of date.)

Here’s the steps I followed.

Clone the old machine

  • Boot the system with the server to a rescue shell so the filesystem is not live.
  • Mount the rescue filesystem somewhere out of the way like /tmp/source
  • Tar the entire filesystem to an archive on an external USB drive. IIRC this is really as easy as cd /tmp/source; tar caf /mnt/usb/disc.tar.zst --one-file-system . The /dev/ files are harmless, tar is smart about those. Because the disk is not being used live there’s no need to exclude sys, proc, etc, even the one-file-system is probably redundant (but harmless).

At this point you have a clean tar archive of your server. It’s a nice backup!

Create the new VM and get it ready

  • Create the VM. I used systemrescue as the ISO for the boot media, then configured an empty disc for my new virtual server. See notes from Path 1 about OVMF BIOS, disk cache policy, and “host” CPU type.
  • On the Proxmox server command line set it up so the USB device containing your root filesystem tar file is passed through to the new VM. (There’s no doubt other ways to get the data into the VM.)
  • Boot the VM. In the OVMF bios menu, disable Secure boot in OVMF bios. Shouldn’t be necessary but it was the only way I could get the system rescue ISO to boot.
  • Boot system rescue and get to a Linux shell
  • Use parted to set up the new virtual disc. It starts completely empty.
    • Label the disk as GPT partition
    • Create one EFI system partition of 1GB. (See here).
      mkpart p fat32 0% 1GiB
      set 1 esp on
    • Create a BTRFS partition for the rest of the disc
      mkpart p btrfs 1GiB 100%
    • Create filesystems on the partitions
      mkfs.fat -F 32 /dev/sda1
      mkfs.btrfs /dev/sda2

Now you have an empty Proxmox VM all ready to go to have your filesystem transplanted into it.

Copy the filesystem in

  • While still in the rescue shell, mount the guest VM’s disc (/dev/sda2 in above) to somewhere like /tmp/dest and mount the USB source with the tarball.
  • Use tar to unpack the entire root filesystem from the USB disc. cd /tmp/dest; tar -xaf disc.tar.zst should do it.

At this point your VM’s disc has a clone of the server, from the tar file. All we have to do is get it to boot! In theory you can do this from a rescue disk right away, but let’s go ahead and install a proper boot system. But first...

Fix the block IDs

First it’s necessary to fix a few files in your new virtualized server’s root partition. The problem is the block IDs of your filesystems have changed and anything that refers to them by ID has to be updated.

  • Boot a rescue disk and mount the root filesystem to /tmp/dest
  • use blkid to identify the new blockids of the newly prepared filesystems.
  • edit /tmp/dest/etc/fstab to refer to these new block IDs. (or just use the /dev/sda names for now.)
  • edit /tmp/dest/etc/grub to include a line naming the block ID for the new filesystem.

Make the VM disk bootable

The last part is to let grub-install do its thing to set up the boot partition.

  • Boot the rescue disk and mount /tmp/dest
  • Prepare bind-mounts into /tmp/dest per step 7 of the guide.
  • chroot /tmp/dest and get a new shell in the Upside Down
  • Mount the boot partition: mount /dev/sda1 /boot/efi
  • Cast a magic spell for the ✨ EFI variables ✨
    mount -t efivarfs none /sys/firmware/efi/efivars
  • Run update-grub to pick up the new block ID you configured in /etc/grub
  • Run grub-install /dev/sda to install the EFI partition needed to boot
  • Exit the chroot shell and shut down the VM
  • In the Proxmox VM config, remove the SystemRescue ISO and the USB
  • Edit the VM options to include your new boot device
  • Boot!

This all actually worked and I had a working system. The downside is you have to make new partitions, new filesystems, and then install grub in a very weird way. The changed block IDs complicate things too. Overall this was much more complex than just making a disk image clone with QEMU or Clonezilla. But conceptually it might be “better”. I’m glad I learned how to do this but it’s not going to be my preferred method.

Path 3: restore from Proxmox backup

This is cheating, it’s not cloning a physical system. But just for comparison I tried using the Proxmox GUI to back up a working VM of my server to a USB disc and then restore it. It was very easy! This is the reward at the end of the tunnel. Next time I upgrade hardware I won’t have to reinstall anything other than Proxmox. Then I can just backup and restore VMs and containers. Or migrate them live in a cluster, maybe.

The backup of the ~80GB of actual disk data (160GB disk) was fairly quick (10 minutes?) and created a 56GB .vma.zst file. The restore took 20 minutes and took up 62GB of data on a ZFS volume.

Everything static was restored but the system had to be rebooted. Proxmox does support live system migration but that’s not what the backup does.

Thoughts

So that’s it, I now have tried four ways of migrating a working Linux server to new hardware. I’ve made all this sound very complicated. Honestly, it was complicated while I was figuring it out. I imagine half the readers are rolling their eyes saying “duh” and the other half are saying “wut?”. I’m not quite at the “duh” stage but I’m glad I’ve gotten past “wut?”. In particular I’m much more comfortable with manipulating Proxmox VMs, adding and editing hardware and disks and the like. And maybe GRUB is a little less of a mystery to me.

It’s remarkable how resilient a Linux install is to the hardware it’s running on. Virtualizing like this means changing every single hardware device, replacing them with virtual ones. Discs are entirely different. And yet everything still mostly works; putting in the new name for the network adapter was the only manual change required.

Shrinking a VM disk image: loss and recovery

A small experiment. I have a 2TB physical disk (SSD) with about 80GB of real data on it. I want to shrink that 2TB to a virtual disk that’s 150GB; 80GB of data and 70GB of free space. The disc has two GPT partitions, almost all of the space allocated to the second partition. That partition is formatted with BTRFS.

I managed to do this but it was kinda scary all the way, particularly the part where I broke everything and lost all my disk partitions. I did recover it in the end but I do not recommend the experience. I was playing around on a test VM so it wasn’t a catastrophe, but if this were a precious system I would have been very unhappy.

To cut to the chase: resizing the filesystem and the partition were easy. But shrinking the virtual disk with qemu-img caused big problems. The underlying problem is that GPT has two copies of the paritition table: a primary at the start of the disk and a secondary at the end. Changing the disk size screws up the secondary and Linux gets angry and won’t recognize the partitions. You can repair the GPT partition table manually with gdisk but it’s scary. This may not be an issue with old fashioned MBR partitions.

Battle plan

The simple way to do start is gparted’s GUI; it will resize a btrfs filesystem and partition for you. But I’m stubborn and using command line tools. The plan is roughly:

  1. Clone the physical disc to a QCOW2 image
  2. Clone the QCOW2 image with qm import disk to whatever raw format Proxmox wants.
  3. Build a VM around that Proxmox clone.
  4. Boot the VM
  5. Use btrfs filesystem resize to resize the filesystem inside the live VM.
  6. Use parted on the disk to shrink the partition for the filesystem we resized.
  7. Reboot and test it’s basically working but the partition is now really smaller
  8. Shut down and use qm resize on Proxmox to make the disc smaller. This is the part that broke.
  9. Repair the damage with gdisk
  10. Reboot and you’re done!

The first few steps are documented in other blog posts and are about moving a physical disc to a VM. The rest of this post is about resizing a Proxmox VM disk in QEMU raw format.

btrfs filesystem resize

The goal here is to make btrfs think the partition is smaller than it used to be, moving all the data to the front of it so you can then lop off the rest of the partition. It’s pretty straightforward and can (must) be done on a mounted disk.

# time btrfs filesystem resize 150G /

Resize device id 1 (/dev/vda2) from 1.82TiB to 150.00GiB
real 0m21.361s
# btrfs filesystem show /
Total devices 1 FS bytes used 72.25GiB
devid 1 size 150.00GiB used 95.02GiB path /dev/vda2
# df -h /
/dev/vda2 150G 74G 75G 50% /

The filesystem resize was quick and easy! As far as everything is concerned the filesystem is now 150GB big, not 2TB. However the partition is still 2TB.

Parted

Now I want to repartition the disk so nothing is using space beyond 150GB. I’m using parted to edit the partition table on the live disk, the one that is running the OS I’m running parted from. That’s not a good idea, it’d be safer to boot from rescue media. But I’m feeling spicy and this is a test VM.

It’s very important to separate “GB” (1,000,000,000 bytes) from “GiB” (1,073,741,824 bytes). btrfs filesystem is explicit about talking in GiB. parted understands both but seems to prefer the base 10 smaller numbers. You can change that with unit GiB in parted.

unit GiB print
Number Start End Size File system Name Flags
1 0.00GiB 1.05GiB 1.05GiB fat32 boot, esp
2 1.05GiB 1863GiB 1862GiB btrfs

(parted) resizepart 2 155GiB
Warning: Partition /dev/vda2 is being used. Are you sure you want to continue?
Yes/No? y
Warning: Shrinking a partition can cause data loss, are you sure you want to continue?
Yes/No? y

(parted) print
Model: Virtio Block Device (virtblk)
Disk /dev/vda: 1863GiB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number Start End Size File system Name Flags
1 0.00GiB 1.05GiB 1.05GiB fat32 boot, esp
2 1.05GiB 155GiB 154GiB btrfs

Note I chickened out and made the new partition 154 GiB, a few GiB bigger than the filesystem. I don’t trust my math. The correct number for the end of the partition would be 1.05GiB + 150GiB. (But oh god does parted round down by a few bytes?)

I rebooted and verified everything worked. I now have a 2TB disk with only 155GiB of partitions on it.

Resizing the QEMU virtual disc

This is the part where I broke things. I wanted to make the actual VM disk smaller, to shrink it from 2TB to 150GiB (or a bit bigger)

Proxmox explicitly does not allow shrinking a desk with the GUI or qm command line tool. The docs just say “that’s dangerous and we won’t help you”.

However it’s still possible to do it with command line tools. I did this with qemu-img on a raw image. That linked page talks about LVM as well. Note that both qm and qemu-img seem to work in binary sizes. Ie: 1G is 1GiB, 1,073,741,824 bytes. I sure hope this is consistent everywhere since it’s not explicit.

First, I shut down the VM. I did some experiments on a scratch monkey while the VM was still up and bad things happened. The file size of the .raw changed on the Proxmox host, but even after rebooting the size looked like the old size inside the VM. It must only work to resize a disk if the VM is offline.

# ls -l disk.raw
-rw-r----- 1 root root 2000398934016 Dec 30 18:49 disk.raw

# qemu-img resize --shrink -f raw disk.raw 156G
Image resized.

# ls -l disk.raw
-rw-r----- 1 root root 167503724544 Dec 30 19:18 disk.raw

# qm rescan
# rescan volumes...
VM 100 (virtio0): size of disk 'local-btrfs:100/vm-100-disk-1.raw' updated from 1953514584K to 156G

Looks like it worked! Note the qm rescan is necessary.

But then disaster. Reboot failed. Getting to a rescue disk , blkid didn’t show any of my partitions. fdisk and parted on /dev/vda showed scary errors like “GPT PMBR size mismatch (3907029167 != 327155711) will be corrected by write.”

I was able to correct things somewhat by using qemu-img resize again to grow the disk back to 2TB, its original size (to the exact byte). Even then nothing was working. But now parted and fdisk reported “The backup GPT table is corrupt, but the primary appears OK so that will be used.” I used gdisk (a new-to-me program) to interactively repair things. It used the primary GPT table for the info and rewrote everything. And it worked! But this was all super scary. And I’m back to a 2TB disk.

I have a theory for what went wrong here. Apparently GPT writes two copies of the partition table; a primary at the front of the disk and a secondary at the back. When I shrunk the disk the second copy was removed, then when I made the disk bigger again it was “back” but now zeros instead of data. And so there was a minor complaint with the secondary and gdisk could work around it. Not a big deal to recover from but spooky.

But I really wanted the disk smaller. So I resized it again, booted to rescue, and used gdisk. And ran the v command. Look at all these errors!

Not only is it unhappy about the secondary partition table being wrong but also it is aware that the disk used to be bigger and stuff is inconsistent.

I used the suggested e command (or was it r?) as suggested. That basically says “trust the primary” and generate a new partition table. Then w to write the change. That all worked fine; both gdisk and parted no longer reported errors. Is it done?

Reader, the system rebooted with no problems. Ubuntu was saved!

Ideas for doing this more safely.

gdisk has options to back up GPT partition data to a file and restore it. I’d definitely use that before monkeying around with any of this.

I would use the gparted GUI tool for most of the work. It handles both the btrfs resize and the repartitioning. It’s not going to anticipate the GPT partition weirdness of a qemu-img shrunk disk, but maybe it has nice tools for recovering from the mess too.

Proxmox: sharing files to container with snapshots

I finally figured out how to mount a directory in a container without making Proxmox refuse to do snapshots. The trick is to use lxc.mount.entry instead of a bindmount. Thanks to this Reddit hint. In detail...

I have a USB disc mounted on the Proxmox host as /mnt/usb-media. I want to share it to a container running a media server. When you look online for how to do this you quickly find that bindmounts are the way to do this. Basically it says “take this directory in the host and make it available to the guest”. This is the config in /etc/pve/nodes/pve/lxc/110.conf I was using:

mp0: /mnt/usb-media,mp=/mnt/usb-media

This works fine but has the side effect of Proxmox refusing to take a container snapshot. There’s an error in the GUI console saying “The current guest configuration does not support taking new snapshots”. I don’t know quite why that’s a problem, maybe it is concerned it can’t snapshot the contents of the mounted files? I’d be fine skipping those!

Anyway, the solution is a different config line:

lxc.mount.entry: /mnt/usb-media mnt/usb-media none bind,create=dir 0 0

This makes the files available, just like the bindmount did, but Proxmox will still take snapshots. The snapshots still seem to work. I didn’t test what they did with files on the mounted directory. In this particular application I should probably mark the mount read only...

The format is documented in the LXC man page but all it says it’s like an fstab entry. Note it’s very important that the third word, the destination directory, has no leading slash. It’s a relative path, relative to /, mnt/usb-media in this case. If you make it an absolute path there will be no error message but nothing is visibly mounted.

Proxmox’ docs are really not very helpful here. I have no idea what all a bindmount might do or how it’s more than the plain LXC entry. Someone else suggested trying to add replicate=0 to the bindmount options to make snapshots work. That didn’t work for me.

Anyway, I can play my mp3s and still snapshot the container, so mission accomplished.

Proxmox Linux container sizes (Alpine etc)

Continuing my Proxmox explorations, I’m looking for the smallest reasonable Linux container I can install to then do other things with. My starting point is Proxmox templates. Easiest to install with Proxmox tools but you can see the image sizes at the downloads here.

I’m mostly comparing the sizes of “df /”. That may not be a good measure. But for me it’s not just a measure of disk space, it’s also a proxy for memory usage and complexity. Of course I’m comparing systems without GUIs.

Alpine 3.18: 10MB

The gold standard for small Linux, really a lovely thing in just 10 MB. Hilariously almost half the storage (4MB) is in /lib/libcrypto.so.3, OpenSSL. I guess no one’s made a svelte SSL. Alpine gets to be so small by using libmusl instead of libc and replacing most of the userspace tools with busybox. The init is the very simple OpenRC. Despite that it has a huge number of packages you can easily install on top of it.

The downside is those replacements are very limited. The user space shell environment is enough to install something but can be frustrating. MUSL is also limited, see this post as an example of an obscure performance problem. It’s not bad, really it’s an impressive accomplishment, but it’d be nice to have an option that was both small and yet GNU libc based.

Debian 12: 540MB

Debian seems to be the default for a lot of Proxmox applications, but it’s half a gig on disk. From what I’ve read this is fairly pared down. Still it’s hard to quite understand where all the space is going. Some of it is just general system size. 136MB is shared libraries. 20MB for Perl, another 30MB for Python. Some of it seems superfluous: 50MB is locales (all of them?), 60 MB for the dpkg database, etc. It adds up.

One thing that’s encouraging is the Debian images keep getting smaller. Debian 12 is half the size of Debian 10!

Ubuntu: 640MB

No surprise, Ubuntu is bigger than Debian. More or less the same shape of things but just a little more of it.

Centos 9: 436MB

Not a fan of RedHat OSes but it’s a reasonable choice. Smaller than Debian but with similar sources of size. The locale library is 74MB! Also a 65MB GeoIP database that I bet isn’t necessary.

OpenSUSE 15.5: 178MB

I’d forgotten about OpenSUSE, to be honest, and am not sure whether it’s a good choice in 2023. It’s nicely small though! The bulk of it is binaries in /usr/lib64/ and /usr/bin. It’s still systemd and GNU libc. But there’s locale library at all, no python by default.. It meets the critera for “smaller”. Might be worth investigating what tradeoffs it implies.

Gentoo: 1800MB

Another distro I’d forgotten about, I picked this because in theory it supports musl. But not this template. And whoever built this was clearly not worried about size, it’s huge! There’s copies of package repos, SGML docbook, a 100MB test suite for Python, ... clearly no one spent time optimizing size here.

Other options

I should look beyond Proxmox templates. There’s a lot of other folks who’ve been working on the “smaller Linux for containers and VMs” idea. I should learn more about them. Docker’s got a bunch of them, in particular I keep seeing references to a “Debian Slim” that sounds promising. Docker’s overlay filesystem takes some of the sting out of bigger containers though, since the base OS storage can be shared.

Conclusions

I guess my ideal would be something with GNU libc but without systemd and without extra locales and binaries I don’t need. Ideally neither Perl nor Python required. Maybe what I want is “Alpine but with glibc and bash”. I’m willing to trade off some space for quality. I wonder if it’s realistic to be able to use pre-built Alpine MUSL packages for some things and glibc for others?

I’m probably overoptimizing. 540MB for Debian is probably what I should be using when Alpine won’t work, or maybe that 178MB OpenSUSE.

LXC by hand

Some rough notes on setting up LXC on a generic Ubuntu system with the command line tools. No Proxmox. I mostly followed this guide and made it difficult for myself by setting up an unprivileged container. This is easier if you’re root.

  1. sudo apt install lxc
  2. Follow the instructions in “Basic unprivileged usage” that have you creating a ~/.config/lxc/default.conf and as root adding permissions for networking to /etc/lxc/lxc-usernet.
  3. Run lxc-update-config -c ~/.config/lxc/default.conf
    This is not mentioned in the Ubuntu docs but seems necessary, I found it in a comment here.
  4. Create a container: lxc-create -t download -n u1 -h
  5. Configure it interactively (I couldn’t figure out command line switches). The list of containers is here. I chose alpine, 3.18, arm64.
  6. Start it: lxc-start -n u1
  7. Connect to it: lxc-attach -n u1

On the container:

  1. Verify networking works: ping 8.8.8.8 (note that “ping” can be fraught but it worked for me.) ip a shows me a 10.* address, not my usual LAN subnet. I guess some routing is involved?
  2. Verify you have process isolation: ps -axu. It’s a list of a few root processes just for the Alpine container, nothing for the host.

On the host:

  1. Verify user ID mapping: ps -axu | grep /sbin/init. I have some processes with a new user 100000.
  2. Learn some things about the container:
    lxc-info -n u1
  3. Check the container’s files in $HOME/local/share/lxc

I’m having a hard time getting any system stats about the containers. lxc-top reports nonsense, free inside the container shows the host system stats (yes, lxcfs is installed in the host), lxc-info does not show memory usage despite all the docs saying it should.

One thing I notice is all the help pages I find online in my searches are ~2014 era. I suspect most people have moved on from LXC to LXD or Docker or whatever. I’m only tinkering with LXC because that’s what Proxmox uses. But then they’ve built their own pct tool for managing things.

Proxmox what I installed

Following on my general post about Proxmox here’s a list of specific things I installed on my new home LAN server. As always this blog is mostly written for my own notes, but maybe other folks will find it interesting where I ended up.

Proxmox hypervisor

In general the idea is to customize the Proxmox host itself as little as possible, all my stuff should be going in guest operating systems. But Proxmox itself is a full Debian system with super cow powers and you can install other stuff. I kept it to a minimum just for administering the hypervisor:

  • apt install stress-tui stress-ng lm-sensors hwinfo joe sudo
  • Tailscale so I can access the management GUI from anywhere
  • The user “nelson” with my usual environment. Not really necessary.

I hand-mounted a USB disk of my media files by editing /etc/fstab. Proxmox seems to have no tool for managing USB disks. It doesn’t even automount them although I bet there’s some Debian thing you can install for that. As always be sure to use nofail in the fstab so it’ll boot without the disk.

I also wrote a script that uses pct list and pct exec to run a command in each container to print out their IP address. It’s kinda hard to find all your guest images in Proxmox’ UI if you’re using DHCP to assign addresses. (I wonder if there’s a way to get Proxmox to manage DHCP for its guests. Part of me wants a separate subnet for all the Proxmox hosted stuff.)

Ubuntu VM: old server clone (240GB, only 30GB used.)

My old server is virtualized now, see this blog post. I plan to migrate everything out of here and shut it down eventually but it’s real nice to not have to do that all at once.

Hacking container: Ubuntu template (1.4GB)

I have one container that’s just for general hacking projects. I suspect I’ll rebuild this from time to time other than preserving my home directory. I used the Proxmox Ubuntu template to make it, making sure to turn DHCP on. It’s unprivileged (which breaks ping). Here’s some stuff I did after install:

  • locale-gen en_US.UTF-8
  • apt install joe avahi-daemon git zip unzip rsync openssl webp ripgrep pigz python3 python-is-python3 python3-venv python3-dev pkg-config build-essential sqlite3 keychain curl
  • tailscale: have to enable tun access in Proxmox to make this work
  • My usual home directory environment.

Plex container: tteck (4.6GB)

I installed the Plex media server using tteck’s Proxmox helper scripts. These are a set of shell scripts to install a container in an OS and then the apps. Not sure why they don’t just distribute a template instead. I chose Ubuntu 22.04 instead of Debian and then it installed whatever Plex itself needs.

My media files are on the USB drive I mounted on the host OS. I used a bindmount to make the directory available in the container. Note that bindmounts break Proxmox’ snapshot mechanism, but backups still work.

The resulting image works great. Intel QuickSync, the GPU accelerator for transcoding, just worked with no effort on my end. Plex itself is easy to set up. I configured Plex to not run scans, intro detection, etc every night so it wouldn’t use all that CPU and disk I/O. But those jobs work fine.

4.6GB seems huge. over half of that is in Plex cache directories that were generated after it started running. I only gave this container 8GB, I wonder if it’ll run itself out.

Unifi container: tteck (2.1GB)

The Ubiquiti device management controller. Another tteck script, with Debian 12 this time. Also installed Tailscale myself. Ubiquiti’s system requires you migrate devices from an old controller to a new one which is fairly simple, basically making a backup of the config and copying it over. The actual migration process is a little scary, if it goes badly you might have to hard reset your devices.

Samba container: Alpine template (0.07GB)

A network fileserver for my music files, for Sonos. I did this one fully manually, starting with the Alpine 3.18 template. it was really easy, basically just apk add smb. I had to bindmount the media drive just like Plex. I wrote a new config file from scratch, smb.conf gets a lot more readable if you remove the hundreds of lines of comments from it. Dimly remembered the special downgrades Sonos requires to work (unix extensions = no).

Docker VM: manually (32GB not all used)

I set up a Debian VM to run Docker and Portainer using these instructions. I wanted to see how Portainer worked but I don’t know that I’ll keep using it. It’s not even running right now.

Monitoring container: TBD

The main thing left in my old server’s VM is a bunch of custom scripts I wrote to log monitoring data. I set this up a couple of year ago with Telegraf + InfluxDB + Grafana and it works well. So well I keep adding monitoring hacks without being careful about it, so now it’s a bit of a hairball.

I think the migration path is to set up Debian or Ubuntu on a new container, then install Telegraf + InfluxDB + Grafana there. Then somehow migrate all my Influx data and Grafana configs over. And all my monitoring scripts in Telegraf. That’ll let me turn off the VM versions of those things without much data loss.

But I’m sorely tempted to also improve things as I move them. Productize the monitoring scripts a bit so next time I move them it’s simpler. And maybe move off of Influx to TimescaleDB (a Postgres extension). That’d be more fun and having the VM working gives me time to do that.

I’m also unclear whether I should set up a separate container for each monitoring process, plus an extra for influx + grafana, and write the data with a network socket. That’s maximal containerization but seems like overkill, I probably won’t bother.

Backups and snapshots

One annoyance: there’s no tool for backing up the Proxmox server itself. Most people say “eh, just reinstall” but it’d sure be nice to have a copy of the configuration. Some folks have hacked things by copying off the config files with a script.

Proxmox does have backup tools for VMs and containers which are basically filesystem copies. I’m not certain how hard they are to restore but the web GUI has a “restore” button so presumably push-button. There’s a nice set of backup options trading off consistency vs disruption. If you stop the guest entirely you can make a cleaner backup but you don’t have to. Backups can be run manually or scheduled.

Proxmox also has “snapshots” which not only capture disk state but also memory. This seems to work great with a VM; I could snapshot, rollback, and my running processes are back in the old state. There’s also snapshots for containers but they don’t work as well. Bindmounts disable them entirely. And the restore of a container is not confidence inspiring; it took 30+ seconds and only restored file state, not memory or running processes. That all makes sense given what a container is, but makes me wonder whether container snapshots are useful.

Note that a backup run in “snapshot” mode is a different thing from a “snapshot”.

Proxmox, first impressions

So I’m setting up a new server and for the first time in my life I’m using containers and VMs instead of just installing a bunch of stuff into one Linux system and hoping for the best. It’s working pretty well so far, wanted to write down what I’ve learned so far. I’m new to all this, not an authority.

These notes are about the Proxmox Virtual Environment, a hypervisor OS you install directly on the bare metal. Its main purpose is to then host LXC Containers and/or KVM virtual machines which are running guest operating systems for your services. It also manages storage and some networking. Proxmox has been around 15 (!) years now.

Overall Proxmox has been a good experience. It hasn’t done anything dumb or frustrating and has some very useful capabilities. I’m glad I’m trying it.

Hypervisor choice

Why Proxmox? I picked it because it’s popular in the home lab / hacker communities and I have friends who use it. I definitely don’t want or need some enterprise-grade Kubernetes solution that’s designed for managing a fleet of hundreds of machines. I’ve got one $200 server, a couple of small disks, and very low requirements. But I do want it to be easy and fun to hack. Proxmox meets that market.

One special thing about Proxmox: it has equal support for full virtual machines and simpler LXC Linux containers. You can mix both with no problems. Of course you could run KVM in any Linux system, and you can also run containers in a VM with Docker or LXD or something. But Proxmox puts both front and center as equally supported options and I like that.

There’s a bunch of other choices for hypervisors or similar setups. I briefly looked at XCP-ng (a fork of XenServer), see this analysis. But it’s a little too new and I think doesn’t directly support containers. I also gave Portainer a quick try, it’s a GUI for Docker containers, but that’s really all it is and it doesn’t quite manage a whole system. Incus does have both VMs and containers, it’s a fork of LXD, but is too new for me. VMware ESXi is popular but proprietary, I wanted open source. There’s also a lot of solutions that are more command line / config file oriented, I was looking for something with a web GUI.

Finding guest systems

One thing that worried me in picking Proxmox was where I’d find images to use for containers. I want to install a Plex server: is it going to be a lot of work manually installing or can I just push a button? I think Docker Hub sets the standard for sharing images and was worried Proxmox’ use of LXC would be a problem.

No problem. Proxmox itself comes with some templates for generic Linux systems like Alpine or Ubuntu. tteck’s helper scripts are a popular way to install some complex products: I use it for Unifi and for Plex. Turnkey Linux also works well with Proxmox, it’s a set of cross-platform VM images.

Also creating a custom guest system from scratch is really not hard. For instance I wanted a guest Samba share for my music files. So I set up Alpine, then installed Samba in 15 seconds, then configured it with a text file and I was done. Now I have a 65MB container that’s serving my music. This was certainly no harder than installing Samba on bare metal and the ability to checkpoint and tear down / rebuild this one service made it easier than worrying I might break something.

BTW Alpine is a real pleasure if you want a lightweight Linux. It’s based on Busybox, so not a great general purpose environment, but plenty good enough to run a simple server or two. A new install in a container is 10MB of disk and 2MB of RAM and has almost nothing installed but you can bootstrap from there, there’s 20,000 packages or it. A VM install is 130MB of disk and 80MB of RAM.

There’s lots of other choices for Linux in a container. See this set of images and this discussion for some other ideas. I have a couple of Ubuntu guests for a richer experience. I haven’t tried doing anything GUI.

Various choices and learnings

I am trying to enforce a rule of one container per product / service. I currently have containers for Unifi, Plex, and Samba. I need to set one up for a collection of Grafana monitoring hacks I have. I currently have a grab-bag VM which is a virtualized clone of my old server that I’m migrating stuff off of. And I also have one scratch Ubuntu container for random hacks / interactive shell stuff and one VM that is running nothing but Portainer and Docker that I’ll probably end up never using. Creating a new container in Proxmox is under 10 seconds of effort, making new ones is fun!

Proxmox has a bunch of storage management options. RAID arrays, ZFS, LVM, Ceph. I opted out of all of that. I have one simple BTRFS partition for Proxmox and one external USB drive simply mounted into the host system and then bindmounted into the guests that need access to it. Guest systems are all on virtual disks, which Proxmox manages (files in the BTRFS partition, I presume.) I will revisit my storage setup at some point, the extra stuff adds complexity but I think there’s benefits. Maybe I’ll finally have a useful full system backup. There’s even options for migrating guests and something they call “high availability”.

I’ve almost exclusively been using Proxmox with its Web GUI. That’s remarkably complete, the only thing I’ve needed a shell command for so far was creating a bindmount. But Proxmox has an extensive command line interface which most of the docs treat as the primary product. I should learn it. It also has a rich API but I’m not sure what other clients that are that use it. I need to learn this. I haven’t even read the docs through yet! The GUI is good enough I can find my way to most things. (Except changing the font for the shell terminal emulator; that was hard to find.)

I’m mostly using containers for things instead of VMs, in the theory that they are lighter weight. The LXC containers are not really inescapably secure, something you mostly mitigate by not letting the containers have anything like root access on the hypervisor (“unprivileged”). VMs are fully virtualized and more secure but also add the overhead of running an extra kernel. I don’t really care about security; my alternative here is running all the processes in a single Linux system. But I do care about enough isolation to keep things understandable.

I’m not really clear on how much overhead all this encapsulation is costing. So far I haven’t come anywhere near the limit of my 16GB of RAM, 512GB of storage, or 4 relatively slow CPUs. Proxmox puts a cap on each guest’s resources but doesn’t preallocate them, so my various service containers are only using ~10–500MB of RAM each and no appreciable extra CPU. The one full Ubuntu VM is using most of the 2GB of RAM I gave it, but half of that is for disk cache (does a VM mean I cache the same disk blocks in both the host and the guest?).

There’s also latency and jitter overhead. But maybe not much? I run some 50 millisecond-scale timing code as part of my Starlink monitoring and I have no idea how much uncertainly the containers will add to those measurements. Just eyeballing the graphs, running in a VM (on an unloaded host) doesn’t add any noticeable delays. And I’m guessing LXC doesn’t add any significant delay either.

It’s annoying how every guest OS wants a root password. There is support for ssh or direct console login but that password is still there as a primary authentication. That feels very old fashioned.

File ownership and user IDs are a total mystery to me. The Unix user model is really not very helpful in the one-container-per-service model. I’ve been ignoring the problem and using root or whatever user the image I installed created. It’s going to be an issue when I share files on disks between containers though, like that USB drive with my media on it.

I’m not sure exactly what the containerization is really getting me. End of the day I have more complexity for the same services. But.. it feels right having each product isolated. Like that’s an important simplification. Also Proxmox has the ability to checkpoint and backup guests which could definitely be an improvement over what I used to do. I think it’s worth the investment and the overhead isn’t too high.

Things I’m missing

Here’s some things I haven’t figured out yet or that don’t exist. I haven’t read the Proxmox docs through yet, so maybe it’s there for me to discover.

Every container has its own IP and hostname. But Proxmox has no facility for helping you track those, does not provide any sort of automated DNS for them. I’ve been installing avahi-daemon in some containers so .local mDNS names work but that seems silly. I’m also a little worried about running out of addresses in my /24. I guess I could expand the home subnet.

It feels like Tailscale could also be integrated in to Proxmox somehow. The main option seems to be to install Tailscale in each container and treat it as a separate host on the tailnet. (Which requires some config for unprivileged containers). That’s probably the right model but feels a little awkward. Also Tailscale’s binaries are 50MB, or 5x the size of the Alpine container ;-)

I still haven’t worked out how to share files across containers. Web searches suggest networked file systems: SMB or NFS or even 9P running as a server on the host and mounted on the guests. Yuck! I’m using a bindmount for a USB disk right now, that basically just shares the Unix directory from the host to the LXC guest. (You can also pass the USB device itself through and mount it only in the container, but that’s not really sharing.) I’d like some general solution for sharing disks, need to research. Maybe there’s an answer in Proxmox’ storage system which I’ve been ignoring so far.

Cloning a physical Linux system into a Proxmox VM

Working on replacing my failing server hardware with a new server running Proxmox. Finally realized I could just clone the whole OS off the old system rather than laboriously rebuild every service in a new way as containers on the new server. Clone first, then migrate later. Easy right?

Actually not too hard. The Proxmox wiki has several ways to do what they call “Physical-to-Virtual”, the primary one being “use Clonezilla to clone the entire disk into a KVM on Proxmox”. That’s what I ended up doing but it took about eight tries.

First, though, a minor complaint. It should totally be possible to move a Linux system solely by copying the files with rsync, not the physical disk block by block. I know this can work. But in practice the challenge is making it bootable. I think the modern way to do this is to install Grub in a second UEFI partition, then configure / use it to invoke the kernel on your main system. But the details of that are fiddly and opaque. So I cloned the disc.

The instructions on the wiki more or less worked. I wasted time on a few tries trying to migrate to a smaller virtual disk on the new server: the old server had 20 GB of data on a 256 GB partition. Proxmox has various options that look like this should work but I never could make it work, made doubly exciting by the way the clone tool doesn’t even check if you have space on the receiving disk for what you are cloning. (It worked for 15% and then failed on a seek error, lol.) Anyway, here’s my detailed notes during the process:

  1. Did a quick cleanup on the old server of disk usage, removing old log files etc to get the size down.
  2. Used Clonezilla to back up the whole disk to a USB drive as a safety measured.
  3. Booted Clonezilla remote source on the old server per these instructions.
  4. Booted Clonezilla remote destination on the new server
  5. Tried cloning to smaller partition. First time failed immediately (with no resizing options) without a clear error. Second time I told it to resize partitions proportionally; that failed a couple minutes in on a seek error, presumably trying to write past the end of the new smaller partition.
  6. Fortunately Clonezilla is fairly quick. It’s smart about not cloning unused space, also uses zstd. My copy operated at a nominal 12GB/minute (over gigabit ethernet from SSD to SSD).
  7. Finally gave up and allocated a destination partition bigger than the source. Clone succeeded but it didn’t boot; hung with 1 core at 100%.
  8. Searched the net for advice, found my way to this thread which suggests using an EFI BIOS in the VM instead of the default legacy Seasonic BIOS.
  9. First time cloning to EFI BIOS failed with a bit error on the copy. (Did I mention the old hardware is failing?) Filezilla detected the error, then ignored and made a valiant effort to recover from it. The resulting image was incomplete and did not boot.
  10. Cloned a second time and it worked! The new VM successfully booted to my Linux partition.
  11. systemd hung because fstab was trying to mount a hard drive on the old server that didn’t exist in the VM. Used rescue shell to remove those entries from fstab.
  12. Reboot did better, but got stuck getting network configuration up.
  13. Used a rescue shell to edit /etc/netplan/10-nelson.yaml to rename the ethernet device. (Use “ens18” instead of old “eno1”.)
  14. Reboot, comes up, but now no networking. Realize I’d left the old system running on the same IP. Ooops.
  15. Turn off old system, reboot VM and it works! I have successfully cloned the old server.
  16. apt install qemu-guest-agent. Not strictly necessary but helpful. Despite what the wiki says you can’t start this with systemctl in Ubuntu 23.04. It seems to start automatically somehow if you’ve enabled it in the Proxmox host options and reboot.

Clonezilla does work, and it is free. But oof is it old fashioned and clunky. I could see it totally being worth paying money for a nicer system cloning tool if you did this more than once every few years.

Boy does the BIOS make things complicated. I sort of understood the old legacy boot process but UEFI and GRUB are complex enough they make me nervous. I have zero motivation to sit down and really learn them.

Linux and bad memory

This post has more than the usual flailing around. Don’t follow this advice.

My Intel NUC server is failing, twice now it’s corrupted database files with single bit errors. I confirmed with memtest86+ that the problem is bad RAM. I’ve got new hardware on order but meanwhile I want to make things work again.

First I used memtest86+ in summary mode (pressing F1 and F4) to get the above display. It’s telling me that RAM is bad between 868MB and 996MB, also with the hex addresses. Probably not all 130+ MB there is bad but who knows. (In detail I can see that the 5th bit is bad, mostly in a single 4k page. Happily this coincides exactly with the data corruption I was seeing in my database files.)

Then I convinced Linux not to use this RAM by adding the memmap=140M!860M to the Linux command line (by editing /etc/default/grub.) That avoids the whole region memtest86+ identified as bad. This Stack Exchange discussion was very helpful in figuring it out, and this web page has a great detailed explanation of how memmap works. The real purpose of this option is to tell Linux not to touch the memory because some other fancy performance system is using those addresses specially. I rebooted and confirmed the reservation was happening thanks to this line in dmesg:

[ 0.000000] reserve setup_data: [mem 0x0000000035c00000-0x000000003e7fffff] persistent (type 12)

Some fuckups I encountered along the way:

  • Linux has a CONFIG_MEMTEST where it can run a simple RAM check and automatically avoid RAM that tests bad. Apparently memtest=17 is a good setting, according to the cargo cult. I never got the system to boot with this; it’d just go to a blank screen and nothing would happen. I waited 20+ minutes, longer than the 4 minutes one guy who had 128GB of RAM said it took. Perhaps the system overheated and froze up.
  • The old way to do deal with flaky memory was using the BADRAM setting with a confusing mask. This apparently was never in a standard Linux kernel but the patch is in Ubuntu’s kernel. But it doesn’t work in UEFI Secure Boot so forget it.
  • A bug in ubuntu installer from 2016 left /etc/default/grub.d/50-curtin-settings.cfg lying around with a variable that clobbers my setting in /etc/default/grub with the empty string. Here it is eight years later and I just now got hit by the legacy of this bug. (They sorta fixed it, but didn’t do anything to repair systems that had the bug). So I was making changes to the GRUB config, always a scary and confusing thing, and they weren’t taking.
  • Sometimes on booting my poor machine would display “alloc magic is broken at 0x.....” early in the GRUB boot process, I think loading the init ramdisk. Searching Google for this error gives even less than the usual semi-useless info. But one common explanation is.. bad RAM! I noticed the address in the error was close to where my error is, so I think flaky RAM caused it. No idea why it works sometimes and not others, but it seems to work better after I let the system cool down a bit.

Truthfully, every time I’ve tried to use software to cope with flaky hardware it’s ended badly like this. Better just to throw money at the problem and get new hardware. I have an embarassingly cheap N100 system on order, hoping it’s not total garbage.

Influx corruption / hardware failure

My Influx time series database corrupted itself. Hard to even see what was going on. Grafana couldn’t load data. The process was using 100% CPU. I finally figured out the logs are in journalctl -u influxdb.service -n 1000 but are super spammy. And don’t use useful error levels, so filtering with -p isn’t helpful. But I got lucky and saw a real message in the sea of log spam. And figured out Influx was restarting itself and then panicking every few minutes. Here’s the real error.

Nov 23 06:54:10 gvl influxd-systemd-start.sh[1801566]: panic: keys must be added in sorted order: dsm1_cache,database=telegraf,engine=tsm1<hostnamu=gvl,id=794,induxType=inmem,patx=/var/lyb/influhdb/data?telegraf/autoge~/794,retentionPolicy=autogen,walPath=/var/lib/influxdb/wal/telegraf/autogen/794#!~#writeDropped < tsm1_cache,database=telegraf,engine=tsm1,hostname=gvl,id=794,indexType=inmem,path=/var/lib/influxdb/data/telegraf/autogen/794,retentionPolicy=autogen,walPath=/var/lib/influxdb/wal/telegraf/autogen/794#!~#snapshotCount

Note the bogus path there that starts /var/lyb/influhdb. Looks like corrupted data in Influx’s internals and the code isn’t smart enough to recover from the file not existing. It’s helpful to see the ID 794, presumably that’s the particular table / series / whatever that is corrupted.

So wutdo? Naturally I don’t have any backup. Here’s what I did to brute force remove the corruption.

  1. Stop influx with systemctl stop influxdb. Also stopped all processes like telegraf that were writing to it.
  2. Make a backup of all the files in /var/lib/influxdb. It’s about 4.5GB and gzipping it is a mistake.
  3. Look at influxdb/data/telegraf/autogen/794/fields.idx. Happily this is readable text that gives a clue as to which series is corrupted. It’s some old data related to PVS6 monitoring that I’d like but can live without.
  4. fgrep -r 'var/lyb' . in the data files to see if I can spot the corruption. Yes, it’s in data/_internal/_series/02/0000. Also in data/_internal/monitor/2090/000000064-000000001.tsm.
  5. At this point use Google and search for info on rebuilding a corrupt InfluxDB. I found this page about “Rebuild the TSI index” that looks promising. In particular it involves removing all the _series files; one of those is what’s corrupt for me.
  6. Double check the backup is good, then follow those instructions. I remove all the _series directories.
  7. Joke is on me! influxd inspect returns unknown command "inspect"
  8. Try to start Influx anyway, maybe it’ll rebuild what it needs on its own?
  9. Get same error, now it’s tripping over that monitor file I didn’t remove.
  10. Look in the data directory, see a bunch of new _series directories. I guess it did rebuild them?
  11. Delete the monitor file that matches var/lyb. Also delete all the _series directories again since one seems to have picked up the corruption. Brute force but we’re desperate here.
  12. Restart influxdb.
  13. Success! It started without any freakouts. Presumably I lost that one data series but the others seem to work. I hope.
  14. Reboot as the easiest way to restart all the processes that want to write to InfluxDB.
  15. Launch Grafana and verify most of my stuff is still there. Also verify the PVS6 project whose data I clobbered is not there. RIP.

This is not the right way to fix a valuable database! But this database is only sort of valuable and it’s 6am on Thanksgiving and I haven’t had coffee yet. This will do fine.

What I should do next is set up Influx backups. Or maybe this is the time to try switching to timescaledb, a Postgres extension for time series databases.

Really what I should be worried about is how random data got corrupted on my machine like that. Cosmic rays do happen and if so well, eh, that’s the hidden cost of cheap hardware. But the machine is five years old and not 100% stable (this is the NUC that overheats) so maybe the hardware is failing.

I took a look at system metrics and what I found is disturbing. Telegraf stopped logging at around 17:30 (local time), an unexplained failure I’ll chalk up to InfluxDB failing. There’s gaps of data until about 01:00 when it finally gets stable again. CPU load spiked around 21:00, that may be when the Influx process started failing so badly. Although a lot of data got written after that.

I don’t see any evidence this happened before, at least not in the last week. I guess I’ll keep an eye on it and the second there’s second evidence of random data corruption I replace the hardware.

Update

Ugh, it happened again. This time it’s related to autogen 893 (not 794) and a small snippet of corrupt data: datarase=telugraf,enwine=tsm!,hostna}e=gvl. Very glad I wrote up notes last week, I’m just doing the same thing again to blow away the corrupted data and recover the rest.

Oddly this corruption is also in my PVS6 data, something I haven’t read from or written to in months. Maybe that’s just a coincidence, I think the specific corrupt data is different this time. Also I think it got triggered by my reading data for some other measurements in Grafana. Huh.

Given the pattern of substitutions, something’s flipping the fifth bit in random bits of storage or, more likely, memory. Presumably hardware failure, unless for some unlikely reason I’m the target of a state-sponsored rowhammer hack. Looking for new hardware now, probably a Beelink system.

task-spooler

This Hacker News discussion taught me about a great new-to-me tool: Duc Nguyen’s task-spooler. It lets you queue up a set of jobs on a Linux box and have them run in parallel in the background. It’s available in Ubuntu and has the shell command tsp.

I’ve used GNU Parallel before for this and it’s great but the model there is you run one big command and the jobs run in parallel all together. The queueing interface in task-spooler means you can keep throwing work at the system and it gets done eventually. Task queues are one of the great computing paradigms IMHO, along with event publish/subscribe.

The interface is very easy. You run tsp command to enqueue a new command, it returns immediately. It sets up a background process to run the command if there isn’t already one and puts the job on the queue. The default parallelism is only 1; you can run tsp -S 4 if you want to run 4 jobs in parallel. Output is written to files in /tmp by default.

There’s more complex commands for querying job status, etc. There’s minimal support for more complex queue management. including options for “wait for a job” and “the job will be run only if the job of given id ends well”. I wouldn’t use this to replace a complex task queue system but it’s nice to have those basics available.

$ tsp -K
$ ps xu | grep tsp
nelson    3983  0.0  0.0   6304   652 pts/0    S+   11:45   0:00 grep tsp

$ tsp sh -c "sleep 1; date"
0
$ tsp
ID   State      Output               E-Level  Times(r/u/s)   Command [run=0/1]
0    finished   /tmp/ts-out.H7AJLG   0        1.00/0.00/0.00 sh -c sleep 1; date
$ cat /tmp/ts-out.H7AJLG
Mon 21 Aug 2023 11:45:47 AM PDT

$ !ps
ps xu | grep tsp
nelson    3985  0.0  0.0   2548    84 ?        Ss   11:45   0:00 tsp sh -c sleep 1; date
nelson    3999  0.0  0.0   6304   648 pts/0    S+   11:46   0:00 grep tsp

$ tsp -K
$ tsp -S 3
$ date; for i in {1..6}; do tsp sh -c "sleep 5; date"; done
Mon 21 Aug 2023 11:54:10 AM PDT
0
1
2
3
4
5

$ tsp
ID   State      Output               E-Level  Times(r/u/s)   Command [run=3/3]
0    running    /tmp/ts-out.Ifxnc9                           sh -c sleep 5; date
1    running    /tmp/ts-out.estpmo                           sh -c sleep 5; date
2    running    /tmp/ts-out.vDtaPG                           sh -c sleep 5; date
3    queued     (file)                                       sh -c sleep 5; date
4    queued     (file)                                       sh -c sleep 5; date
5    queued     (file)                                       sh -c sleep 5; date

$ tsp
ID   State      Output               E-Level  Times(r/u/s)   Command [run=3/3]
3    running    /tmp/ts-out.IgWMfx                           sh -c sleep 5; date
4    running    /tmp/ts-out.tSSCYL                           sh -c sleep 5; date
5    running    /tmp/ts-out.j003cY                           sh -c sleep 5; date
0    finished   /tmp/ts-out.Ifxnc9   0        5.00/0.00/0.00 sh -c sleep 5; date
1    finished   /tmp/ts-out.estpmo   0        5.00/0.00/0.00 sh -c sleep 5; date
2    finished   /tmp/ts-out.vDtaPG   0        5.00/0.00/0.00 sh -c sleep 5; date
$ tsp -t

Mon 21 Aug 2023 11:54:20 AM PDT

Ubuntu: slow login / sudo after changing hostname

Amazing Stack Exchange answer that solved a mystery for me: sudo and ssh logins were taking a few seconds. Turns out if you change your hostname on an Ubuntu box with hostnamectl it doesn’t add an entry to 127.0.0.1 for the new hostname. So you have to add it manually.

The delay isn’t so bad you can’t live with it. Maybe 2 seconds? But it’s annoying! I felt like it was DNS related but was assuming it had to do with the DNS server my datacenter was setting. But there’s no reason sudo should involve network DNS at all.

While I’m here, trying to change the DNS servers on Ubuntu is still a total clusterfuck. Not sure if the problem is netplan or systemd-resolve. resolvectl status is helpful but the output is confusing. I’m not sure if I’m getting the “global” setting or the “link” setting. I wish there were some easy way to test it. nlsookup just tells me I’m using systemd’s goofy 127.0.0.53 as the resolver.

# resolvectl status
Global
           Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
    resolv.conf mode: stub
  Current DNS Server: 8.8.8.8
         DNS Servers: 8.8.8.8 8.8.4.4
Fallback DNS Servers: 1.1.1.1 1.0.0.1

Link 2 (enp2s0)
    Current Scopes: DNS
         Protocols: +DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 192.187.107.16
       DNS Servers: 192.187.107.16
        DNS Domain: nocix.net

Link 3 (tailscale0)
Current Scopes: none
     Protocols: +DefaultRoute -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported

Yet another new datacenter server

My server for somebits.com broke (hardware failure). My notes from last time I set this up were helpful so I’m taking boring detailed notes again.

I really need to stop having a custom configured bespoke server like this. It’s almost entirely used for web traffic these days, and most of that is static. If I can ever successfully convert my blog over to a static generator I could be done with needing a custom server.

Fairly generic stuff

  1. Change password for user “customer”
  2. Add my ssh pubkey for user root
  3. Install Tailscale
  4. Set hostname with hostnamectl set-hostname
  5. Add DNS A records to somebits.com for both main IP and Tailscale IP
  6. Run apt upgrade
  7. Install a bunch of useful packages
    apt install joe stress-ng stress s-tui smartmontools zip unzip rsync openssl webp plocate ripgrep pigz python3 python-is-python3 python3-venv python3-dev pkg-config build-essential sqlite3 chrony rsnapshot
  8. adduser nelson
  9. usermod -aG adm,cdrom,sudo,dip,plugdev,lxd nelson
  10. reboot
  11. file a ticket for reverse DNS
  12. Copy all my old server files from backup to a subdirectory under /root
  13. Set up /home/nelson from the backup
  14. Set up rsnapshot backups. This is very fiddly; rsnapshot -t is useful for testing things. On the newly installed server to be backed up it requires a new user and an entry in /etc/sudoers.d.
  15. apt install mail and set up a local-only postfix
  16. Skipping this time: autossh, munin

Service specific stuff

  1. Change *.somebits.com and somebits.com DNS to new server. I did this early, before the new server was fully set up, because the old one was already broken.
  2. Change DNS entries for other services I run (check Hover DNS).
  3. apt install apache2
  4. Copy over /var/www from the backup
  5. apt install certbot python3-certbot-apache
  6. Restore /usr/local/etc from backup
  7. Restore /etc/apache2 from backup
  8. Make subdirectories in /var/log/apache2
    for d in logsoflag n177xy somebits weblog windhistory; do mkdir $d; done
  9. Restore /etc/logrotate.d entries that are relevant
  10. Set up Perl environment for Blosxom
    apt install libcgi-pm-perl libimage-size-perl
  11. Migrate old Let’s Encrypt install over to new server
    Restore /etc/letsencrypt from backup
    Test https works on new server (beware of DNS expiration times)
    Test certbot renewal with certbot renew --dry-run
    Remind yourself to check in three months
  12. Copy over and test secret stuff from /usr/lib/cgi-bin (no, really!) Also requires
    apt install python2
  13. Set up linkblog user and test it
    adduser linkblog
    restore ~linkblog from backup
    On home server: /home/nelson/somebits/linkblog/prod/update.sh -p -f
    Probably have to swizzle cached ssh keys with this.
  14. User crontabs in /var/spool/cron/crontabs.

Testing

  1. Look at dmesg and /var/log/syslog for anything troubling
  2. Try various websites
  3. Look at /var/log/apache2/*/error.log for anything troubling
  4. Add a new linkblog entry, verify it shows up

One hidden gotcha is all the other client hosts that might have the wrong entry in .ssh/known_hosts for the domain name for the new server. You have to run ssh-keygen -f "/home/nelson/.ssh/known_hosts" -R "somebits.com" to remove them, then manually accept the new ones once.

I managed to break my first attempt at setting up the new server by adding a disk to /etc/fstab forgetting an earlier lesson. Linux systems won’t boot if something in /etc/fstab isn’t working! Fortunately the datacenter has automated system reimaging so I could start over without wasting anyone else’s time.

Diagnosing a failing Linux disk

My datacenter server failed, bad power supply, and when it came back it’s sort of working but is very very slow. I poked around and got the impression the problem is a failing disk. How to be sure? These notes are for a spinning SATA disk, not an SSD.

iostat

The main thing I noticed is everything writing to disk was taking a long time (ie many seconds instead of 100ms). Also a lot of processes in device wait. Here’s how I quantified the problem

# iostat -d 1 --human -xs /dev/sda
Device             tps      kB/s    rqm/s   await  areq-sz  aqu-sz  %util
sda               7.94    415.3k     8.93  380.72    52.3k    3.01  90.8%

sda             111.00    444.0k     0.00    7.36     4.0k    0.80  83.2%
sda              31.00    660.0k   134.00   55.77    21.3k    1.70 127.6%
sda             240.00      1.1M    30.00    4.31     4.5k    0.99  87.6%
sda              13.00     96.0k    12.00  189.85     7.4k    2.45 102.8%
sda               9.00     44.0k    55.00  340.44     4.9k    3.04  97.6%

Note with iostat -d 1 the very first row is since system start, then it’s a continuous report for the last second. The alarming thing here is the “await” column. That’s milliseconds waiting for a single read or write; 380ms average since system boot! Something’s not right. The throughput numbers are also a clue, disks should be doing 30 MB/second, although that does depend on what the programs using the disks are doing. The 100% utilization is a very bad sign too. You can get more details from iostat if you remove the -s flag, but it gets a little confusing.

hdparm

hdparm can be used to test read rates on a disk. Here’s what I got

# hdparm -t /dev/sda
/dev/sda:
 Timing buffered disk reads:  30 MB in  4.27 seconds =   7.02 MB/sec

That’s 7 Mbytes/second. That’s awful. Even a slower spinning disk should be in the range of 100 MB/sec. Something is wrong.

smartctl

smartctl -x /dev/sda is also important, using SMART diagnostics on the disk itself. -x means “all, no really all”. Unfortunately its output is still really hard to understand, the confusing “VALUE WORST THRESH” stuff. I have previous notes on understanding smartctl output that are helpful. This weird Maxtor drive I have has confusing numbers and doesn’t report the Raw_Read_Error_Rate I’d most like to see.

I do have an error log with lots of entries like

Error 46140 [11] occurred at disk power-on lifetime: 36305 hours (1512 days + 17 hours)

There’s no easy way to tell how old those errors are or exactly what they meant. But their presence and the number “46140” sure gives me concern.

smartd displayed this helpful error in the syslog, also suggesting a problem.

Jul 4 17:05:56 wl smartd[3197]: Device: /dev/sda [SAT], 1 Currently unreadable (pending) sectors

Remapping bad blocks

Modern spinning hard drives have the ability to remap bad blocks and avoid them in the future. Linux has historically been bad at letting the disk do this, I think on the theory that destroying data is bad and it should be a manual process (or better, avoided). Here’s some recent notes on the topic. I think manually remapping a known bad block is still really awkward and difficult. Reading that makes me think the disk should itself eventually recover if the block is re-written. But if it’s a read only file that’s corrupted that won’t ever happen!

SSDs change how all this works.

Influx: seeing table (measurement) size

I’ve been accumulating data in Influx DB for a long time. Here’s how to see how much (in bytes)

influx_inspect report-disk -detailed /var/lib/influxdb/data |
  jq '.Measurement | sort_by(.size)'

I’d like to set up a retention policy to auto-delete some old data but unfortunately policies seem to be per database. I’ve got a lot of stuff in a single database named telegraf and some of it I want to keep forever, others I want to discard after a month. I imagine there’s a way to configure the telegraf agent to start writing data in different databases and/or retention policies.

telegraf vs timestamp precision

Learned something the hard way: telegraf by default rounds (some?) timestamps to 1 second.

I’ve got some code that runs IRTT and emits influx format lines every 100ms with precise timings and timestamps. Output like this:

irtt_packets,remote_address=45.66.249.240:2112 delay_rtt=49890590,ipdv_rtt=-25723094 1683647662430925080
irtt_packets,remote_address=45.66.249.240:2112 delay_rtt=100696672,ipdv_rtt=50806082 1683647662530279079
irtt_packets,remote_address=45.66.249.240:2112 delay_rtt=66017146,ipdv_rtt=-34679526 1683647662630672054
irtt_packets,remote_address=45.66.249.240:2112 delay_rtt=56583224,ipdv_rtt=-9433922 1683647662731135862

Those are nanosecond timestamps and the interval is roughly 100,000,000 nanoseconds (ie: 0.1 seconds).

But in influx the data comes out looking like this:

1683646020000000000 43842340 gvl 12180311 45.66.249.240:2112
1683646021000000000 43708652 gvl -11768007 45.66.249.240:2112
1683646022000000000 36362863 gvl -4289225 45.66.249.240:2112
1683646023000000000 40232640 gvl -47825 45.66.249.240:2112

It’s filed all the numbers off my timestamps! Worse, it’s combined ten 100ms measurements into a single 1s measurement. I think new entries just clobber old ones although I’m seeing some signs of it actually combining data from several measurements (‽)

The culprit is precision in telegraf.conf. This can be set both for the whole agent and on a per-input plugin. Maybe also per-output.

My Ubuntu had this set to the empty string. What that means is not well documented on the website but the .conf file had this helpful comment

## By default or when set to "0s", precision will be set to the same
## timestamp order as the collection interval, with the maximum being 1s.
## ie, when interval = "10s", precision will be "1s"
## when interval = "250ms", precision will be "1ms"

So that’s super confusing. But I had my interval at 15s and was seeing timestamps with precision of 1s. I added a precision = "1ns" to the input of interest and now it’s logging timestamps properly.

I can see how truncating timestamps like this could be useful; it hides slight jitter in data and everything lines up neatly. But in my case I really need precise timings. Also the way this causes multiple entries to be lost (because of timestamp combining in influx) is bad. Particularly surprised that it’d throw away precise timestamp info from influx wire format data. If someone went through the trouble to output nanoseconds they probably meant to.

Overheating Intel NUC

My 2018 home media server (an Intel NUC7i5BNH) is failing. It crashes under load; seems to fail when I use it for something intensive (like watching video via the Plex server there). Long story short, the hardware is flaking out; limiting the CPU speed to about 90% of maximum seems to make it stable again. Detailed notes on diagnosing and fixing it below.

When it crashes it locks solid; doesn’t respond to network, doesn’t send pings out (from an in-memory process), syslog doesn’t get updated, hard drive light doesn’t blink. Nothing in the syslog, it just stops writing, nothing in the dmesg file either.

Thanks to this blog post I realized telegraf was logging temperatures even though they weren’t on the dashboard graph. So I added them. Temperatures were going up to 84°C as the CPU load went up. That seems hot, but the CPU is rated to 100°C and looking online I see folks running NUCs at CPU temperatures of 95°C or more. (All temperatures I’m talking about here are from the CPU Package sensor.)

I installed the system stress tools s-tui and stress-ng and was able to crash the system again after stressing (with s-tui defaults) for 2-3 minutes, at around 83°C. Definitely crashing under load, but am not positive it’s temperature.

Thinking it was overheating, I figured the root cause is I added a USB drive to the system and stacked it on top of the NUC. It’s not blocking any vents or anything but will impede passive cooling. So I moved the USB drive. I also took the case off the machine and blew some dust out. When that didn’t work I took the thing apart and give it a proper cleaning, although I did stop short of removing the heat sink since that’d require new thermal paste. I also updated the BIOS and set the fan settings, raising it from “quiet” to “balanced” and eventually “cool”. The fan is definitely spinning and speeding up under load.

But I was still able to crash it with s-tui after just a couple of minutes. Even after all the cleaning, and running with the case off, it still gets to 83°Cish and crashes under load. 83° isn’t that hot! So maybe it’s not actually overheating but failing under some other stress? I wish I had a second power supply to test with.

A full run of memtest86+ passes.

I tried turning off turbo boost in the BIOS; that limits the CPU to 2.2GHz and never lets it run at 3.4GHz. This seems to help; under stress temperatures max out about 57°C. System still works under load after 45 minutes. Of course I’m losing a lot of performance. I don’t think this particular NUC lets you tune overclock parameters in detail, the options are not available in the BIOS.

I got most of my speed back by using Linux’s fancy drivers for controlling CPU scaling and power usage. intel_pstate is the name of the driver, this Arch doc page is a good start as are these RedHat docs. cpupower is the recommended userspace tool but the systemd service definition isn’t available on Ubuntu.

Turns out intel_pstate has a file interface at /sys/devices/system/cpu/cpufreq/. A simple thing is just to write a max frequency to the /sys interface files.

if grep -q i5-7260U /proc/cpuinfo; then
        echo -n "(nelson) throttling CPU in /etc/rc.local for flaky Intel NUC. Max speed: "
        echo 3000000 | tee /sys/devices/system/cpu/cpufreq/policy*/scaling_max_freq
fi

The system seems to be stable at 3.2GHz, just a bit under the 3.4GHz max. At 3.1GHz I was able to stress for a full hour and the system got up to 78°C but never crashed. I set the max to 3.0GHz just to be safe.

Still wish I knew what specifically was failing. I suspect it’s only going to get worse and I should be looking for replacement hardware now. Also curious what changed. December 14 the average temperature climbed from 37°C to 48°C; that’s when I upgraded from Ubuntu 20.04 to 22.10. All sorts of stuff changed then but the only obvious thing is that there’s a new behavior where average load creeps up from 0.15 to 0.2 over the course of a month (before, 0.15 steady was typical.)

Some graphs:

Temperature and CPU during a recent crash
Temperature for the last six months
s-tui after the system crashed

Setting up SSH in 2023

I’ve been using SSH for over 25 years now. Haven’t really re-evaluated how I do that in a long time. I’ve been using the same 2048-bit RSA key since 2007. And mostly without an ssh agent of any sort, typing my key passphrase (or worse, Unix password) like a barbarian. So I’m setting up something new.

I’m struck by how little has changed. I might have gotten something wrong, feel free to comment. The Arch docs were a primary reference for me.

For advanced users, the things I learned this time are: ed25519 keys, that the ancient keychain is still the tool of choice, and that it doesn’t work well with agent forwarding. Really, keychain? Has nothing changed in 20 years?

Generating a key

Go to a secure Linux box that’s been up for at least a few minutes (so it has some entropy in the random numbers) and run

ssh-keygen -t ed25519 -C "name@example.com 20230212" -f id_2023

Two files will be generated: id_2023 and id_2023.pub. The first is your private key and while it’s passphrase protected, best to keep it secret and safe. You can spread your public key far and wide. It will look like this

I’m following Github’s advice here on the type of key. 3072 bit RSA is the default and is probably fine. ed25519 is a fancy elliptic curve that a lot of folks like. I like it because the keys are shorter, not that it matters much. The comment includes a date it was generated; ssh doesn’t store that in the key file. Be sure to set a strong passphrase when prompted.

$ cat *pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEKye4EydeuVQ8h5wG8GyluQ5+RK7BeaW76d0aYchiUj nelson@monkey.org 20230212

$ ssh-keygen -lvf *pub
256 SHA256:nJE3PwWMgAhll0EDbmBCNRwEUG2AOHwtNJa6hnIOrco nelson@monkey.org 20230212 (ED25519)
+--[ED25519 256]--+
|B=%&B+=+.. o.    |
|++.O*oo. .. ..   |
| .o.+   o o   .  |
| . .   . + o .   |
|...     S   o    |
|+oo          .   |
|o=               |
|o .              |
|oE               |
+----[SHA256]-----+

Authorizing a key

Now that you have a key you can use the public key anywhere to authorize it. The whole public key is just one line of text so you can easily copy and paste it. Append it to ~/.ssh/authorized_keys and now most Linux machines will let you log in remotely with it. There’s also the fancy ssh-copy-id tool which will append the key for you.

Some websites like GitHub will let you add your key, generally you just paste in the one line from the .pub file.

Using a key manually

The simplest way to use a key is just name it on the command line

ssh -i ~/.ssh/id_2023 example.com

If all goes well you’ll be prompted for the passphrase for the key instead of your Unix password. I find this is a little confusing and unpredictable but ssh -v helps me sort out any problems. The “-i” flag to explicitly name the key isn’t necessary if you use one of the default filenames like id_rsa or id_ecdsa. You can also put stuff in ~/.ssh/config to name a key to use for a particular host.

Using ssh-agent and keychain in Unix tty consoles

Typing your passphrase all the time sucks. ssh-agent will maintain a persistent copy in memory of your unlocked key and use it automatically. eval `ssh-agent` is the easy way to start it, but you have to do that in every shell (and remember to kill it when the shell ends!).

The better solution for Unix console / ttys is keychain. keychain is a wrapper for ssh-agent that maintains a persistent agent process running all the time, even when you’re not logged in. (Sounds dangerous! But handy.) In a tty environment there’s an easy way to start it, just drop this in your .bash_profile

eval `keychain --eval --agents ssh id_2023`

Keychain will look for an ssh-agent and attach to it if it can. Otherwise it’ll start one and prompt you to type your passphrase to unlock it. It’s a chatty program, you may want the --quiet flag. Also it is a little obnoxious if your id_2023 file doesn’t exist on the machine, so my login script checks for that (see below)

You can run keychain --stop all to remove all agents. There’s also a --timeout option.

Keychain vs agent forwarding

SSH agent forwarding lets you forward your ssh credentials so they can be used on the remove server after you log in. The private key stays on your original machine but the intermediate machine can query your ssh agent to log in to further machines. It’s very handy if you regularly bounce through one host to another. You have to manually enable ssh agent forwarding for each host you log in to in your config file (see the link).

keychain interacts badly with agent forwarding; it’ll ignore that you have a working agent and override it with one running locally. So it’s best to only run keychain if there’s no agent already defined in SSH_AUTH_SOCK. This is what I have in my .bash_profile

SSH_KEY=$HOME/.ssh/id_2023
if [ -z "$SSH_AUTH_SOCK" -a -e "$SSH_KEY" ]; then
        eval `keychain --eval --agents ssh "$SSH_KEY"`
fi

GUIs for Keychain

All this setup is for 1970s Unix tty user interface. A modern system from the 1990s has a GUI. I used to have ssh-askpass wired up in my X session so I’d type my passphrase once per X GUI login, it was great. I’m sure MacOS folks have something similar, maybe using Apple’s own keychain. Windows also has some GUI ssh agents but none of them seem designed for a WSL-centric work mode. I’ll probably just stick to the tty thing unless it gets really annoying with VS.Code, the only Windows GUI program I use that uses ssh.

Passwordless / restricted access

All these instructions assume you have a passphrase you have to type to unlock your key. It’s possible to generate ssh keys without them, very useful for automation. But it’s also dangerous; now all your security is in the privacy of the file only. There’s ways to restrict an ssh key to only be able to run certain commands to make that safer. I’ve done this a couple of times but it makes me nervous.

Yubikey / FIDO

Ultimately ssh-agent is storing an unencrypted version of your login key in memory. Best practices now are to use a secure hardware device of some sort to store that key, particularly a Yubikey plugged in to USB. There’s support in OpenSSH for keeping your key on a Yubikey. Also for generic FIDO authentication, which I think will ultimately let you use the OS own secure enclave for key management. I bet MacOS already has a good system for that and Microsoft is working on it. I’m not using any of that, I’m content with 1970s-era security apparently.

Ubuntu 20.04 to 22.10 upgrade

I upgraded my old Intel NUC home server from Ubuntu 20.04. To 22.04 first, then to 22.10. Went smoothly, no problems.

Below are my running notes as I do the work. Good time to remind folks this is my secret work blog; you’re welcome to read, but there’s no pretense these notes are of interesting to anyone else.

Services on the system I care about. netstat -l --program | grep tcp was a help for finding these, that --program flag is neat.

  • Influx and Grafana with a lot of old data
  • Plex
  • Samba
  • autossh for a tunnel to a public machine
  • tailscale
  • unifi / ubiquiti controller, which includes mongo

I had Home Assistant and Infinitude installed via Docker but didn’t want either of them. I removed them with help from docker ps --all and docker images. Some other things to remove: munin, motion.

I always forget to start do-release-upgrade under screen. Dumb of me! I’ve had bad experiences with it being interrupted in the past (because, say, my ssh terminal failed.) Also when the system says you need to reboot go ahead and reboot, don’t try to do a few things first; the system is in a slightly odd state.

Every time you do-release-upgrade it moves all your /etc/apt/sources.list.d to *.distsave versions and then edits the important .list files to disable third party repos. Doing an upgrade twice in a row means you lose the original file entirely (because *.distsave was copied to twice). It’s no big deal to hand-edit to fix it, but it’s a pain. It’s probably a good idea to refresh the sources anyway; most of the repos have a distro like “focal” hard coded in the paths. Ookla’s packagecloud repository is broken; it installs expecting “kinetic” which doesn’t have releases. “jammy” works, “stable” doesn’t.

btrfs

One change in my new Linux system is I’m using Btrfs as the filesystem. I’ve been using ext2 to ext4 for 25+ years now, time for a change. Btrfs is a fancy modern copy-on-write transactional filesystem similar in vein to ZFS or ReiserFS. For some reason Btrfs has a reputation as not being entirely stable; it doesn’t help the FAQ says “Is Btrfs stable? Maybe.”

but that seems outdated, although there are still some cautions about using it for a filesystem spanning multiple devices. If I were doing something complicated I’d care more but for a simple system, it’s fine. Several Linux distros use it as the default.

Some nice features

  • Robust to failures thanks to copy on write design
  • Grow and shrink volumes, span across devices
  • Snapshots of the filesystem
  • Transparent compression. (But not encryption, sadly.)
  • Checksums for file integrity. Default is CRC32, there are others.

Some tidbits:

  • The docs (also) are pretty good. The sysadmin guide is a good conceptual overview. Subvolumes are a key concept.
  • The btrfs tool has various administration programs in it. btrfs filesystem is the main one I’ve looked at.
  • There’s a default commit timeout of 30 seconds. That seems kinda long!
  • GRUB boots fine off my simple Btrfs disk. There are some less than optimal support things though.
  • btrfs detects SSDs and behaves differently on them
  • There’s no lost+found directory! I wonder what fsck does if it finds an orphan file? Maybe that can’t happen.
  • My btrfs partition had a UUID but also a UUID_SUB. That second thing is the UUID of the subvolume and can be safely ignored unless you know you need it.
  • There’s a lot of docs about maintenance: defragments and balancing and stuff. I’m hoping Ubuntu just installed something reasonable for me. OTOH the btrfs-progs package doesn’t have any sort of cron jobs or other maintenance scripts, so maybe not?
  • The COW semantics are a little confusing. /bin/cp has a --reflinks flag that seems to be important to understand if you want to be precise.
  • The btrfs docs say it works best when 15-20% of the filesystem is free. Yowch! 10% was the old overhead.

The main reason I picked Btrfs was the hope that snapshotting would result in some better backup option. I think this is possible but there’s no obvious consensus script. I found a lot of 8 year old experiments. Folks are very excited to use snapshots as check points so you can easily find a month old copy of a file. rsnapshot does that but awkwardly; a COW filesystem is great. But I also want redundancy: I want my files copied to a completely different disk. And different filesystem; if you set up Btrfs to use two disks for redundancy and Btrfs itself blows up, you still lose your files. There’s something to be said for a separately mounted disk entirely. Another avenue is btrfs send / receive; a way to serialize a filesystem and restore it elsewhere. Anyway I’ll look into Btrfs backups again later some day; rsnapshot still does the job for me.

One bad experience; converting from ext4 to btrfs. There’s a tool to do this safely in place, which is very cool. But it’s very slow. It seemed to read every single allocated block on the disk, then do about the same amount of work for every inode. It took about 5 hours for 2GB of data. And then the resulting filesystem is in a less than optimal state; you have to do more work to clean it up. It would have been faster and better to simply clone the files elsewhere and reformat the disk.

systemd, fstab, and nofail

It’s always like this; I just got my new server all put away in the closet where it’s hard to get to, then it failed to boot. So I had to drag out an old monitor and plug it in and see what was going on. Turns out I’d put a disk in /etc/fstab with options “auto” and then reformatted it, changing the UUID. So it couldn’t be mounted on reboot. And by default systemd blows up in that circumstance because it doesn’t know if the disk is essential. The console showed I was in “emergency mode” with a logged in root shell.

Easy mistake to fix but how to prevent it in the first place? The solution is to add nofail to the boot options. May want to change the hardware timeout too; it’s 90 seconds by default. So something like

defaults,nofail,x-systemd.device-timeout=15s

For such an essential piece of the system /etc/fstab and how systemd processes it is very poorly documented. The systemd docs should be authoritative. As usual the Arch Wiki is helpful. Also as usual the Ubuntu docs are actively harmful garbage last edited in 2017 and not even mentioning nofail. The man page isn’t very good either.

Searching with Google offers an alternative of nobootwait but AFAICT that’s something that predates systemd so I avoided it.

To compound the hassle here: no trace of this emergency boot shows up in any log file. Not in dmesg, not in /var/log/syslog, not in journalctl. The only place I could find the message was on the console tty. WTF?

I sure wish there were some easy way to have a Linux console be available on a network. I know Linux supports a serial port console, I bet there’s some hardware device that emulates a serial port but is online. Having Linux itself use a network thing as a console would of course be tricky; how do you set up the networking before the system’s working?

New Ubuntu 22.04 homelab server notes

I set up my new home server with Ubuntu 22.0. Here’s notes on what I did in August 2022. See also January 2019 and July 2019. Still doing all this stuff by hand like a craftsman; no Docker for me! The Ubuntu docs are worse than ever and Google has gotten much worse for looking for info. Adding “arch” to Linux search terms often helps find useful docs.

Generic system things:

  • Install Ubuntu 22.04 server image, UEFI boot, btrfs for the root partition
  • Use tmpfs for /tmp
  • Enable universe packages, updated apt
  • Set up a static IP address
  • Install chrony
  • Install mainline kernel via the cappelikan PPA. 5.19 includes i5-12600K tweaks not in 5.15.
  • Set up watchdog daemon with iTCO_wdt hardware watchdog and watching ethernet. (Does not seem to actually be rebooting the system when needed.)
  • Install libnss-mdns so .local DNS queries work
  • Install mailutils and set up Postfix for Local only
  • Turn off sudo email spam
  • Install a bunch of command line software via apt
    joe stress-ng stress s-tui smartmontools zip unzip rsync openssl webp plocate ripgrep pigz
    python3 python-is-python3 python3-venv python3-dev pkg-config build-essential sqlite3
  • Install Samba, configure SMB1 (aka LANMAN) support. Gave up trying to make this work for Sonos.
  • Set up port forwarding on my router. Had to reboot the Ubiquiti Dream Machine; config changes weren’t taking.
  • Set up rsnapshot. I’ll eventually move to a btrfs-specific backup program if I can find one.
  • Verify BIOS allows virtualization
    apt install cpu-checker; kvm-ok

Special apps and personal configuration:

  • Set up my /home/nelson environment
  • Install jellyfin ffmpeg from a PPA for hardware accelerated transcoding
  • Install nodejs 18 from a PPA
  • Install plexmediaserver from the secret apt repository. Also install intel-opencl-icd. Reconfigure.
  • Set up a group nzb for various Usenet things to all belong to. Make sure to set up each system to use this group as its primary group and make things group writeable.
  • Install sabnzbdplus from the Ubuntu repository. Set up user nzb to run it. Copy config from old system. Manually install par2-tbb because there’s no jammy build in the PPA.
  • Install sonarr from Sonarr focal repository. Reconfigure and re-add all my data because they moved config files around too much.
  • Install radarr into /home/radarr by copying from my old install. They don’t have any sort of packaging for Linux.
  • Install syncthing from their apt repository. Copy config from old machine (which is risky); be sure the files are in place on the new system before starting to sync!
  • Install Caddy as a web server. Just couldn’t stomach another round of Apache config files. Caddy doesn’t support cgi-bin (easily) so it’s not a perfect fit for my “light dev server” need. But it’s definitely a lot simpler than Apache 2.4.

Things I didn’t have to do this time:

  • Configure fsck at boot. The default is now “preen” which means “fix safe things automatically”.

I’m a little cranky how hard some of this stuff was to get working. Particularly anything outside standard Ubuntu packages. Lots of things haven’t been updated for jammy / 22.04.

APT changed things so apt-key add is now deprecated but the new method is not clearly documented. Apparently I’m supposed to manage my own keys using gpg? See my blog post for info on what to do, or example here or instructions here. What a UX regression.

New Linux homelab server hardware, 2022

Building a new server for my home; using it for Plex video serving, general service, and occasional heavy compute jobs. Here’s the parts list (PCPartPicker)

Intel Core i5-12600K 3.7 GHz 10-Core Processor$280
Cooler Master Hyper 212 Black Edition 42 CFM CPU Cooler$50
Asus PRIME B660M-A D4 Micro ATX LGA1700 Motherboard$130
G.Skill Ripjaws V 64 GB (2 x 32 GB) DDR4-3600 CL18 Memory$200
Thermaltake Core V21 MicroATX Mini Tower Case$70
Fractal Design Focus G Mini case$60
SeaSonic FOCUS Plus Platinum 750 W 80+ Modular Power Supply$160
SAMSUNG 980 PRO SSD with Heatsink 2TB$260
Assembly labor$275
Total (without tax and shipping)$1400

The big choices here are the Alder Lake (12gen) i5-12600K with a B660 motherboard and the MicroATX form factor. I trusted Logical Increments for this. The Z690 is the other obvious consumer chipset but the main feature that offers is overclocking the CPU which I have no interest in doing. (The RAM is overclocked; DDR4’s official speeds are weirdly low.) It uses about 25W when idle (ie, almost all the time) and 160W under heavy CPU load. May push 200W if I stress the integrated GPU too. (Update Jan 2024: with Proxmox installed but still mostly idle it’s using about 48W. Not sure what it was using with the same workload before Proxmox intervened.)

Ended up being pricier than expected but this may literally be the last home server like this I ever build. I was holding out for an ARM system now but it’s just not quite there yet. (Also 25W idle is pretty impressive from Intel!) Could have saved $550 by screwing it together myself and reusing an old drive. I cratered and bought a new drive mostly because I realized I wanted to start with a fresh Linux install and hey, why not the new hotness.

I’m impressed with most of the components. The CPU, motherboard, and RAM all seem to do the job just fine. The power supply is very nice and quiet, although I did buy a bigger one than I really needed. mATX is a nice compromise between being slightly smaller and yet not weird or fiddly. The case I bought is the only disappointment. It’s too cheaply made, whole panels are replaced with mesh and there’s a lot of plastic. But it gets the job done. Update 2024: the actual case is a Fractal Design case, not a Thermaltake case I originally thought I’d ordered. No idea why the confusion.

The one thing I don’t have is some fancy GPU for machine learning work. I just don’t do enough of that now to make it make sense. Intel’s integrated UHD Graphics 770 GPU is pretty nice now; it’d certainly be fine for basic desktop work and seems to accelerate video transcoding pretty well. Not clear if it can be used with common machine learning packages, particularly not under Linux. Part of why I got the big power supply is I could add an NVidia GPU if I need it.

This server replaces the Linux server I built 10 years ago. That served me well, with small upgrades over time, but a few years ago it developed a failure where it’d lock up under load. I used a hardware watchdog for awhile but it was failing so often I couldn’t finish things.

The new system is about 4x faster on CPU jobs (ffmpeg without GPU) and theoretically 10x faster for disk I/O. 64 gigs of RAM is a bit silly but perfect for running today’s fashion of bloated containers and VMs.

SSD lifespan in my Linux server

I put a 2.5″ Samsung 860 EVO SSD in my Linux server in January 2018. It’s the root drive, 1TB, but only has about 90GB written to it. How’s it doing?

OK I think? smartctl -a tells me the value of Wear_Leveling_Count is 099, with a raw value of 8. That should mean it still has 99% life in it (apparently the raw value is inscrutable).

Total_LBAs_Written also has a value of 99, which I think is very good. The raw value for that is 23318240262 which works out to about 10TB, or writing each sector 10 times over the life of the disk. The data sheet has a warranty for 600 TB Written, so I’m not even at 2% of that. Plenty of life left in it.

hdparm and dd both show read and write speeds of about 500MB/sec. That’s about the datasheet performance. The drive is connected via SATA 3.1 at 6Gb/s, and I’m getting about 4Gb/s. A fancy new M.2 Samsung 980 Pro is 10-15x faster but I really don’t much care. In my head all hard drives are still more like 1Gb/s and then only if you’re reading sequentially from data on the inside tracks. Even this old SSD is plenty fast for what I do.

I did decide to give my SSD a little break and move /tmp to tmpfs, which is RAM only. systemd can do this easily, see these instructions. For some reason Ubuntu doesn’t offer this as a default option, I think folks worry that it might be too small (or alternately, eat up all the RAM and start swapping). The default size of tmpfs is 50% of system memory, so 8GB for my small NUC system.

Linux spinning drive failure

My backup disk on my Linux box failed.

[    6.006233] kernel: sd 1:0:0:0: [sdb] tag#26 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
[    6.006302] kernel: sd 1:0:0:0: [sdb] tag#26 Sense Key : Medium Error [current]
[    6.006358] kernel: sd 1:0:0:0: [sdb] tag#26 Add. Sense: Unrecovered read error - auto reallocate failed
[    6.006428] kernel: sd 1:0:0:0: [sdb] tag#26 CDB: Read(10) 28 00 00 00 0b b8 00 00 08 00
[    6.006496] kernel: blk_update_request: I/O error, dev sdb, sector 3000 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 0
[    6.006568] kernel: Buffer I/O error on dev sdb1, logical block 119, async page read

That’s read errors, I think during fsck. I think it can’t read anything at all; badblocks just returns a list of integers from 1 to whenever I hit Ctrl-C. Higher level tools complain they can’t find a superblock, so that’s bad. Fortunately it’s just a backup volume so I don’t need to read the data off of it.

It’s a 2TB Western Digital Drive I bought back in 2015, six+ years is not too bad. (Confused it shows only 31313 hours = 3.5 years of power on time). I didn’t notice it failing; the errors from the backup script were going to root mail which I never read. Also I don’t have proper SMART alerting. Oops.

I’m replacing it with a WD Red Plus drive, 4TB. Spinning drives are basically a dead end product category. Except for server storage, so now there’s a lot of marketing around these “NAS drives”. The Seagate Ironwolf brand also gets recommended for NAS storage but Seagate drives tend to be noisier so I stuck with WD.

In theory drives will map around a few bad blocks but Linux has a long-standing thing where this process doesn’t (always?) happen automatically and I’ve never found a good tool to force it. There’s some instructions in a FAQ somewhere for an elaborate procedure of mapping that “logical block” to a physical sector on the disk and forcing a write to the sector, which causes a remap. But it’s scary. Meanwhile you already know the disc is beginning to fail; is it really worth trying to recover it? If you need the data ddrescue is probably the safer bet.

Raspberry Pi 4 thoughts

I got a new Raspberry Pi 4. It’s neat! Some thoughts on it. Bottom line: it’s a great little computer and my only complaint is the SD card I/O is slow.

First, context. A friend gave me an original RPi Rev B way back in 2012 or so. I’ve used it every year or two when I needed a small Linux box to do something. For awhile I had RetroPie on it for gaming. I dusted it off last week to serve as a network proxy for my SunPower PVS6 solar power monitoring system. It’s working great for that! But it’s a very slow, limited system.

So I bought a new RPi4. I got a Vilros kit that includes a case, a power adapter, heatsinks, an SD card, various cables. It’s very convenient. The core computer is $55 but the kit is $135. Probably not a great value but this was in stock at Amazon; like everything else these days, availability is not great.

The RPi4 is the first RPi capable of running a 64 bit OS. The ARM Cortex-A72 CPU in it is quite capable but nothing too exciting, but since it’s the ARMv8-A architecture it’s pretty well up to date. You have your choice of 1-8GB RAM wired on the board. And all the IO integration that makes the RPi so popular. 4 USB ports, gigabit ethernet, two HDMI ports, WiFi and Bluetooth built in, an audio jack, and of course the famous GPIO pins for hackery.

A word on cases. A nice case goes a long way to making it feel like a “real” computer. The Vilros case is a nice aluminum case that fits just right. RPi4s apparently run hot, at least when actively used. My case has an always-on fan. There’s a bunch of passive cooling cases that basically turn the whole chunk of aluminum into a heatsink, that seems like a better idea if it’s sufficient.

On power: the RPi4 uses 3-5 watts. Everyone recommends a good USB power supply, the official one is 5.1V/3.0A. Alternately the RPI4 can be powered over ethernet with a small extra board. Note 3A is a lot of power for USB; that’s a device intended for charging, not just a random computer’s 0.5A USB port.

Operating system

Vilros shipped an SD card with Raspberry Pi OS (aka Raspbian) installed. Full desktop environment. I used it for a few minutes and it seemed to work but was as unlovely as any Linux desktop. Also slow; you could see the background picture repaint when I dragged windows. I only want this as a headless server so I wiped it and put Ubuntu 21.10 server on it. How about that? Stock Ubuntu, compiled for aarch64 and with a clean boot loader. Shout out to the RPi folks for creating a great disk imager. There was also a thing called NOOBS, a small boot system which let an RPi install its own OS, but I guess that’s deprecated.

The RPi4 has some complex boot loading and firmware overlay stuff. I don’t understand it but it seems to work. USB booting is supported via a bootloader on the SD card.

One drawback with Ubuntu is it’s less clear how to tinker with the Raspberry Pi-specific stuff. Raspbian has raspi-config which lets you adjust things like clock speeds, GPU memory usage, etc. It looks like you can just edit config.txt on the Ubuntu boot partition, this works sort of like BIOS settings but for the RPi.

Another useful tool for RPi-specific hacking is vcgencmd. This lets you get at a bunch of state on the GPU, which apparently in this Broadcom implementation is controlling the whole system. This lets you get at things like how much RAM is dedicated to video (78MB for me) and what the current temperatures, voltages, etc are.

There’s a whole lot of software dedicated to working with the GPIO pins. This capability is the really neat hidden feature of the RPi and gets pretty complex as you mess with different modes of I/O: I2C, Serial, etc.

Performance

No one buys an RPi4 for performance. But it’s pretty impressive, particularly by historical standards. Unfortunately it feels slow for interactive stuff. But then I’m spoiled by fast machines with SSDs. The main issue with the RPI4 is the SD card is slow. Some comparisons to an Intel NUC based on a i5-7260U.

With the cheap SD card Vilros sent me hdparm reports about 45 MB/s. Compare 100 MB/s for a spinning disk on an Intel NUC or 1600 MB/s to SSD. I’d hoped the SD would be faster. And that 45MB/s is for synthetic tests: this blog post says 7 MB/s for reads for random access reads. SD cards are clearly not a fast medium. This blog post suggests 100-300MB/s with a proper SSD drive plugged in to USB 3, which is big boy PC speeds but nothing amazing. The RPi4 can boot off USB so you can eliminate the SD entirely if you want. It’s too bad they don’t have an NVMe interface, but then that’d require a PCI bus. (The Compute Module product does have one.)

Another word on I/O: older RPis implemented ethernet on the USB bus so performance was severely limited, particularly if you wanted to use it as a router with multiple ethernet interfaces. Raspberry Pi 4 has a dedicated channel for its ethernet separate from USB, so that helps.

RAM is reasonably fast. Testing with sysbench I get about 4GiB/s on the RPi 4; compare 17GiB/s on the Intel NUC.

CPU is impressively fast. Again testing with sysbench, using one or two threads the RPi was about 1.35x faster than the i5-7260U. With 4 threads the RPi is 1.6x faster. The Intel CPU is 4 threads but only 2 real cores; the RPi4 has four cores. I have no idea if this is a real world CPU benchmark, probably not.

I played around with overclocking a bit. Boosting CPU speed from 1500MHz to 2000MHz gave me about 1.3x speedup. Max temps were 45C and 52C respectively. Then I found the arm_boost=1 config.txt setting, which apparently gets you 1800MHz as a temporary boost with extra voltage. I don’t normally overclock but since they say it’s safe I’ll leave that enabled.

I found a note in the docs that suggests there is no hardware support for video decoding.

Thoughts

What an impressive bit of kit. What I like best is how contained it is; a small pack of cards running a real 64 bit Ubuntu with zillions of hardwaer ports. The only drawback from a conventional computing point of view is you’re limited to USB 3 for disks. And hell that’s not bad at all, with an SSD significantly faster than computers I was using on the daily a few years ago. If I were using the RPi 4 interactively I’d be sure to set up USB booting to a fast disk.

But I’m not using it interactively. In fact I probably won’t use this RPi4 much at all. The old RPi B is doing fine as my proxy device. But now I’ve got this little swiss army knife computer sitting around for the next project where I need something this flexible. I’d like to learn more about ARM as a practical server platform. Or maybe I’ll use it as a web a server for my plotter. Or a base for some home automation tinkering via those tasty GPIO pins.

One other thought; the RPi 4 is the flagship product but there’s other devices. The Raspberry Pi Zero 2 W is a smaller, cheaper system suitable for less demanding uses (like being a web proxy). I/O ports are limited but for a certain type of application it might be more suitable. There’s also a Compute Module which looks like an RPi 4 only without all the I/O ports (and with the SD card built in). I think this may only be of interest to folks designing embedded systems.

Fixing syncthing apt repository

It’s been six weeks since the Let’s Encrypt certificate expiration debacle and I’m still finding errors. This one today from running apt update

Err:3 https://apt.syncthing.net syncthing Release
  Certificate verification failed: The certificate is NOT trusted. The certificate chain uses expired certificate.  Could not handshake: Error in the certificate verification. [IP: 82.196.13.137 443]
Reading package lists... Done
E: The repository 'https://apt.syncthing.net syncthing Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

The problem is syncthing is signing with a certificate in the expired chain. Or rather used to be. I tried various cargo cult solutions that did not work. The one that did was running apt install ca-certificates. That package was already installed but the command also forces an upgrade. Probably just running apt upgrade would have fixed it so the next apt update would have worked, too.

I’m fascinated by all the systemic failures from the certificate expiry. The Let’s Encrypt team thought carefully and tried really hard to head off problems. They failed. I found this one post-mortem but honestly there’s a masters thesis in systems complexity in analyzing all the global failures.

Grafana and InfluxDB: rollups

Now that I have a few months of data some of my Grafana graphs were getting slow. I realized I’d made no provision for data rollups. I’m recording data every few seconds. Great for a detailed graph of the last 24 hours, but far too fine grained for a report for a full year. Clearly I need some data aggregation / rollups, just like rrdtool did 22 years ago.

Joke’s on me: there’s no easy way to do aggregates or rollups in Grafana + InfluxDB. It’s a frequently requested feature, this discussion from 2016 is the most complete I’ve found. No clear answer but the fact it’s still not present (even in InfluxDB 2.0) speaks volumes. To be fair, doing a general purpose rollup is kind of hard, lots of weird corner cases.

InfluxDB does have reasonable support for creating a rollup table yhourself; see the Downsampling and data retention docs. You set up a continuous query to populate records and then a retention policy to delete old data. (Hysterically, the docs suggest you create the retention policy first; those only run every 30 minutes so you’ll probably get lucky!) But that amounts to creating a second table for the downsampled data. Whatever queries that data is then responsible for selecting the right table (or worse, merging data). There’s a variety of hacks for working with this in Grafana; the usual suggestion is to make the Grafana query select from the value of a variable rather than a static data source, then populate the variable appropriately. I imagine this can be made to work but what a PITA!

Looking at my own problem again I realized that I only had a million points at worst; that’s not awesome but why is the system choking on that? InfluxDB is super fast! Turns out my problem was the weird dashboard I’d imported didn’t have any sort of group_by clause defined. The ordinary Grafana boilerplate includes a group_by($_interval) as part of the query. InfluxDB is still having to read all the records but at least it’s only shipping a rolled up version to Grafana. Once I added that back my existing dashboards got speedy again. Problem avoided. That won’t work for a system with a lot of data, but for a small data system it’s fine.

A simple systemd unit file

I wrote my first systemd unit file today. It’s a thing that runs code to import stats from Starlink’s GRPC into InfluxDB using this Python code. Nothing remarkable about this but it’s the first time I’ve ever used systemd like this.

[Unit]
Description=Starlink GRPC monitor
After=influxdb.service
StartLimitIntervalSec=5
StartLimitBurst=5

[Service]
User=nelson
ExecStart=/usr/local/src/starlink-grpc-tools/collect.sh
Restart=always

[Install]
WantedBy=multi-user.target

OK, the remarkable thing is Restart=always. I was having trouble with the script crashing after running a long time. OTOH it turns out it was crashing because Starlink’s protocol changed and the code had to be updated; no number of restarts would fix that. That’s what those StartLimits are for; if it fails to start 5 times in 5 seconds then systemd gives up trying.

Also I’m naughty and run this as myself, not some dedicated system user.

Syncthing status from the command line

I’ve written a little tool to show me the status of Syncthing on the command line. I now rely on it to get my files off of computers that will then be turned off and inaccessible. I didn’t have any way to know if it was really working. I don’t have a reliable outage monitoring system for all my personal tech crap. (I mean, who does? Hmm..)

Anyway this turned into a bit of a yak-shaving exercise. Syncthing does not really have a command line tool. There is a syncthing cli command (and formerly the syncthing-cli third party tool) but they don’t report the status I need. What syncthing does have is a very nice REST API for querying status, so I wrote a tool to check that.

The other tricky thing is defining what it means for syncthing to be synced. I’m not sure I got this right. The algorithm I’m using is it enumerates all folders and all remote devices and checks completion on each one. In practice folders seems to catch outgoing changes, remote devices catches incoming changes. It ends up being O(n) HTTP calls, not ideal, but here we are. It might be possible to get it down to 3; I didn’t quite understand how the bundling in rest/db/completion worked.

Anyway, the Python script below mostly works. I wonder if someone else has already done this and I reinvented the wheel? One last wrinkle; when to run this. I was originally thinking in MOTD (hence my earlier post) but for now I’m running it in .bash_login.

#!/usr/bin/env python3
"""
Status report for syncthing, suitable for including in /etc/motd.d. By Nelson Minar <nelson@monkey.org>

Note that this will show "completely synchronized" if a file was very recently created or altered and
syncthing is not yet aware the change has been made. See the scanning and fsnotify docs in Syncthing for details.
"""

import json, urllib.request, platform, itertools, sys
from pprint import pprint

"Configure the URL endpoint and API key based on hostname. API key is in Settings."
HOST = None
API_KEY = None
config_table = {
	'ub': ('http://127.0.0.1:8384', 'XXXXX'),
    'Nelson-Win10': ('http://127.0.0.1:2103', 'XXXXX')
}

def st_api(command):
	"Call the SyncThing REST API and return as JSON"
	req = urllib.request.Request(f'{HOST}/{command}')
	req.add_header('X-API-Key', API_KEY)
	resp = urllib.request.urlopen(req, timeout=2).read()
	return json.loads(resp)

def main():
	global HOST, API_KEY
	try:
		HOST, API_KEY = config_table[platform.node()]
	except:
		# Exit silently if we're not configured
		sys.exit(0)

	folder_report = []
	device_report = []
	try:
		# Explicit error handling for first REST connection. Others are YOLO.
		devices = st_api('rest/config/devices')
	except Exception as e:
		print(f'Syncthing: Error connecting to {HOST}.')
		sys.exit(0)

	# Check completion for all remote devices
	for device in devices:
		completion = st_api(f'rest/db/completion?device={device["deviceID"]}')
		device_report.append((device["name"], completion["completion"]))

	# Check completion for all folders
	for folder in st_api('rest/config/folders'):
		completion = st_api(f'rest/db/completion?folder={folder["id"]}')
		folder_report.append((folder["label"], completion["completion"]))

	# Show a short status message
	if all([c == 100 for n, c in itertools.chain(folder_report, device_report)]):
		print('Syncthing:', f'Completely synchronized.')
	else:
		incompletes = ((n, c) for n, c in itertools.chain(folder_report, device_report) if c != 100)
		print('Syncthing:', 'Incomplete.\n ', '\n  '.join(f'{n}: {c:.2f}%' for n, c in incompletes))
		print(f'Details at {HOST}')

if __name__ == '__main__':
	main()
	sys.exit(0)

My Grafana / Starlink setup

I did a bunch of work setting up Grafana to track my Starlink system and promptly forgot about it! Documenting it now.

I’m graphing Starlink stats using InfluxDB and Grafana. Telegraf is not involved.

The data collector is from starlink-gprc-tools. It runs as a background process and writes data in to InfluxDB. I haven’t changed the code from sparky8512’s repo, although I do have my own fork on Github.

I’ve installed a frozen copy in /usr/local/src on my Grafana server. Here’s the “collect” script that fires off the background process. This runs forever, no need for cron:

#!/bin/bash
stats="status usage obstruction_detail alert_detail ping_drop ping_run_length ping_latency"
interval=60

cd /usr/local/src/starlink-grpc-tools
source venv/bin/activate

python ./dish_grpc_influx.py -U starlinkstats -P PASSWORD -t $interval $stats

I haven’t really configured Grafana yet. I found some stock dashboard (in the repo?) that looks like the screenshot below. But it’s storing a lot more stats and I should drill into it at some point.

Telegraf / InfluxDB / Grafana

For years and years and years I’ve been using Munin to monitor servers. Sure it’s old and limited but it still worked reliably and simply without too much software to install. But I’ve finally modernized, mostly so I could collect more data off my Starlink satellite.

I went with the combination of Telegraf, InfluxDB, and Grafana. The so called “TIG stack”. The end result is a system that works remarkably like Munin. Only instead of crappy Perl scripts there’s a clean fast Telegraf agent collecting data. The simple MTRR databases are replaced with InfluxDB, which seems a bit complicated for the purpose but works well. And rrdtool’s old busted graphs are replaced by Grafana, a very fancy enterprise-level dashboard construction system.

I followed a couple of guides for installing stuff: this one and this one. The install breaks down to “install some packages from third party repos” followed by “configure Telegraf and Grafana”.

The configuration is.. not simple. First you have to set up the database with a user, etc. Use the default names! They are baked in to things you will be using either. Then you have to set up Telegraf to log what you need. You can do this incrementally, you don’t have to get it all right at once, but there’s a whole lot of options and things to learn about. I think it took me almost two hours to tweak to what I wanted.

Grafana’s the real monster though. One nice thing about Munin is if you started logging a new number with a plug, the rest of the system would automatically figure out it should graph that number and show you. Not so with Grafana; instead you have to go through a very powerful but complicated web configuration to develop your systems. Fortunately Grafana is pretty good at auto-detecting variables and making some suggestions. The Explore query system is also good at figuring out what you might have in the database.

But the real win with Grafana is you can load other people’s dashboard designs from a community sharing site. For instance, I’m graphing most of my Telegraf system data using this dashboard. Notice how they helpfully supply a Telegraf config too; you can just copy and paste that stuff in and it will probably work.

Anyway, now I finally have some Starlink monitoring using sparky8512’s tools. It doesn’t use Telegraf but has its own little agent to log to InfluxDB directly, plus a sample Grafana dashboard. The dashboard is pretty limited, I’ll probably spend some time configuring my own eventually. But what’s there works for now.

Grafana Starlink screenshot

I was inspired by this Starlink enthusiast and his speedtest charts. Ironically the Starlink setup doesn’t give any speed tests, but I’ve added that using this telegraf plugin. Note if you use that you must install SpeedTest.net’s own client, not the one in the default Ubuntu repos.

All in all I’m pretty happy with the TIG stack. Despite (or maybe because of) all the complexity the new system consumes a lot less CPU than Munin did. And it’s way more flexible and modern. Sometimes it’s good to update to new things. It’s a shame it’s so complicated to configure though; it’s hard to imagine how Ubuntu could ship this as an easy turnkey install.

Propane tank monitoring

Wanted to give a shout-out to Tank Utility, a company that makes a gauge for monitoring your propane tank level via the Internet. Unlike most IoS devices it works great!

It’s very simple; $200 gives you a ruggedized battery powered outdoor thing you mount on your propane tank. There’s a small sensor that clips on the “remote ready dial” on your propane tank, I think it reads the needle setting via a Hall effect sensor. You do a one-time setup with a phone app for the WiFi and then the device will just quietly report the propane level a couple times a day to their free cloud service.

For end consumers they provide a decent mobile app for monitoring propane level, they also have a simple API for downloading the status. I think their real business is selling to propane companies, they have a commercial offering that I imagine tells the propane company when it’s time to deliver more fuel.

The clever thing in the device is it works off a few AA batteries but is designed for a battery life of up to 5 years. I think the thing is basically fully powered off most of the time and only powers up to connect briefly to the network to send a reading.

The main risk with this device is if the company disappears it will stop being useful. I wrote and asked them if they had a contingency plan for that and unsurprisingly for a small company, they didn’t have a good answer. The company seems just cool enough I could imagine them doing some one last update that enabled people to run their own monitoring server. Hopefully the company has a long life and the question never comes up.

Ubuntu 19.10 to 20.04 upgrade failure

I seem to be cursed when it comes to Ubuntu updates. I just tried upgrading Ubuntu 19.10 to 20.04 (ie: eoan to focal) on a ordinary home server. Once again do-release-upgrade failed right as systemd was being updated. In the past that’s because the systemd upgrade broke my network configuration, because of course I’m doing the upgrade via ssh. (In a screen session though!) This time around it was worse, because the system wouldn’t boot:

- - -[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) ]- - -z

Well that’s exciting.

Turns out this is a well known problem with an easy solution. Basically if something interrupts an apt upgrade of the kernel at the wrong time, the kernel will be installed and chosen as the default but the matching initrd ramdisk to make it bootable won’t be properly installed. (ramdisk creation seems to be deferred to the very end of the apt process). The result is the system won’t boot with the new kernel. UEFI may be part of what makes this a challenge.

Fortunately there are usually other older kernels also installed that still work on the hard drive, so all you have to do is convince GRUB or whatever boot loader you’re using to boot an older kernel. Then you can go in and fix things.

The command that seems most clearly to fix things is
dpkg --triggers-only linux-image-5.4.0-29-generic
Of course you need to substitute the right package name there, for the latest kernel that’s not booting. You can find it this way by listing all packages installed with “triggers pending”:
dpkg -l | grep ^it
Another bit of advice on that Stack Overflow page is to run
dpkg --configure -a
This will force any packages that were installed but not configured to configure themselves. My aborted Ubuntu upgrade seems to have left me with ~40 unconfigured package, this fixed them all in a jiffy.

I sure wish I knew why upgrading systemd sometimes breaks networking on Ubuntu. It’s happened on two different systems of mine. And it’s an absolute disaster if you only have local access to the machine. Hilariously, do-release-upgrade still advises against running it if you’re ssh into the machine. How am I supposed to update the machine, fly to the datacenter and type at the keyboard?!

I also wish that apt or do-release-upgrade were a little more robust in leaving you with a bootable kernel.

The good thing here is that apt and dpkg are very robust themselves. This is the third time I’ve had do-release-upgrade fail on me now, but each time I can pretty much rely on apt and dpkg to fix whatever mess was created.

Bonus round: USB keyboards

This whole ordeal got a lot more complicated because I couldn’t find a keyboard to plug into the Intel NUC hardware to access the boot console. I use an old USB wired Apple Mac 101 key keyboard on my regular computer. For some bizarre reason that fails to work when plugged in to the NUC for accessing the BIOS. I ended up having to wait two days for Amazon to ship me a cheap $10 Chinese keyboard. That’ll teach me to not have a bunch of old computer parts lying around the house.

Upgrading from an unsupported Ubuntu (18.10 to 19.10)

Update (March 2020): I’ve heard from 10+ people who say these instructions work for them, I think it’s reliable. See also this Ask Ubuntu post. Some folks are finding their way to this blog searching for “An upgrade from ‘cosmic’ to ‘eoan’ is not supported with this tool.” That makes sense, it’s the error the upgrade tool gives. Finally, if you see an error about “Upgrades from 18.04 on the i386 architecture are not supported” that is sadly true; 32 bit support stopped in 18.04. I don’t know how to help you with that.

A couple of weeks ago I blogged about being unable to upgrade from Ubuntu 18.10 (cosmic) to 19.10 (eoan), or even 19.04 (disco). Ubuntu 18.10 is fully end of life and deprecated and the do-release-upgrade tool we normally use to upgrade things refused to run. (Note that this tool is bundled in the ubuntu-release-upgrader-core package) Fortunately one of my readers Alejandro saw my post and suggested a solution. I just tried it and it works. Details below.

The underlying problem is do-release-upgrade on 18.10 was trying to upgrade directly from 18.10 → 19.10. But that’s not possible. And it’s no longer possible to upgrade 18.10 → 19.04 because 19.04 is also not supported. So you’re stuck.

The gist of the solution is to hack a config file to force an 18.10 → 19.04 update. It turns out Ubuntu’s do-release-upgrade tool is a generic program, the version installed on an 18.10 system is not 18.10 specific. Instead it downloads metadata files from the Internet and uses those to figure out what to do. Alejandro’s suggestion boils down to intercepting those metadata files after download and hacking them to point to 19.04 instead of 19.10. The packages needed to do the 18.10 → 19.04 upgrade are still online, do-release-upgrade just wasn’t finding them.

Needless to say, the instructions below come with a big warning this may break your system. It worked for me, but no idea if it will work for you.

18.10 → 19.10 steps

  1. zRun do-release-upgrade on the 18.10 system. This will give you an error about being unsupported. But behind the scenes, the tool will download some metadata files we want to modify.
  2. As root, go in to /var/lib/update-manager and copy the file meta-release to a new file meta-release2. This file was downloaded by do-release-upgrade from the Internet and tells the upgrader how to upgrade.
  3. Edit meta-release2. Remove all entries for eoan entirely. Modify the disco entry so it says Supported: 1
    Update April 2020: reader F.K. write to say “I found that ubuntu repo returns 404 and `do-release-upgrade` can’t run update. I changed all link in meta-release2 for disco to  http://old-releases.ubuntu.com/  and its works.” I can’t test this but it seems plausible of Ubuntu finally moved the disco update files out of the live repo (say, in preparation for the 20.04 release.)
  4. Edit the file /usr/lib/python3/dist-packages/UpdateManager/Core/MetaRelease.py. Change this line of code
    self.metarelease_information = open(self.METARELEASE_FILE, "r")
    To read
    self.metarelease_information = open(self.METARELEASE_FILE + "2", "r")
    That will tell the upgrader to use your modified file instead of the original. (It will also avoid any redownloads overwriting your changes.)
  5. Run do-release-upgrade. It should now be doing an upgrade 18.10 → 19.04. Let that run as normal and reboot.
  6. Congratulations! You’re now running 19.04. Remove the /var/lib/update-manager/meta-release2 you made.
  7. Since 19.10 is supported, all you have to do to upgrade 19.04 → 19.10 is run do-release-upgrade again. No hacks necessary, you’re back on the main path.

Like I said, it worked for me. I’m a little surprised Ubuntu doesn’t support this officially out of the box, it seems simple enough. I suspect they just want to have nothing at all to do with older systems. Still if it were me I’d add some flag to enable at-your-own-risk upgrades for people like me who were stuck.

I think I also could have upgraded my system simply by editing /etc/apt/sources files and relying on apt dist-upgrade. That’s the underlying tool that’s doing all the work anyway. But the Ubuntu upgrade scripts have a little extra stuff in them and it’s nice to be able to run it just in case it’s important.

I’m very grateful to Alejandro for his emailing me the suggestion on the fix.

Adding a new SyncThing node

I’ve been using SyncThing for awhile now to keep several Windows PCs in sync. Mostly the Documents folder, also some saved games. It’s been working great since I set it up, so well I’ve nearly forgotten how it works.

I decided to add it to my laptop today. Which begs the question; what’s it like to bring in a new machine to an existing sync cluster, one with possible conflicts in the folders? It mostly went OK but some awkwardness.

To add a new machine to the node all you have to do is install SyncThing and then go to “Add New Device” on the new machine. I have a hub-and-spoke system (3 Windows spokes, one Linux hub that’s the primary copy) so I just added the Linux hub device. Approve it on the GUI of the hub machine, accept the folders it offers, and it all worked OK.

Well mostly. I had some file conflicts, as expected. There’s a conflict resolution tool but it’s very confusing. It talks in terms of “original” and “conflicted” file and I’m wondering; original to whom? It seems to have no idea of three way syncs or merges. I looked and realized I had a backup of all the files and none were important anyway, so I just blindly accepted “take the newest” for all the conflicts.

The uglier problem was errors that some files were not transferring, with an error in the GUI of “file modified but not rescanned; will try again later”. I looked online and found this is often a symptom of a case mismatch. Windows filesystem is case insensitive but still stores cases, maybe it got confused with the Linux copy. I finally resolved these by deleting the files everywhere across my cluster and then restoring it to the hub from a backup, then letting the new copy propagate. Ugly but effective.

The last problem I had was one file refused to copy: sync_ffs.db. That’s a file that a different sync system (FreeFileSync) uses. It has some magic properties that make it unwriteable or something. I simply instructed SyncThing to ignore that file, no more problem.

So all in all a bunch of ugly manual work. Which is in keeping with SyncThing; it’s a great tool but it’s not exactly civilian friendly. The good news is that once it’s set up and syncing it seems quite reliable.

I can’t imagine what topologies more complex than hub-and-spoke behave like.

Cheap PC hardware watchdog

I have a Linux PC server that flakes out and locks up solid every few weeks. I tried using a software watchdog to fix it but it didn’t help. My guess is the whole CPU is freezing, so even the watchdog can’t run.

I’ve fixed the problem for now with a hardware watchdog. Some $10 anonymous Chinese hardware designed for Bitcoin mining rigs.

It looks like a USB device, but the USB is only for power. The main I/O are two pairs of wires: one that connects to your hard drive activity LED, one that connects to your hardware reset switch. Yes, it’s that dumb. Basically it just watches the LED and if it hasn’t flashed in awhile (no idea how long, maybe a minute?) it sends a reset to the motherboard.

It looks like a USB device, but the USB is only for power. The main I/O are two pairs of wires: one that connects to your hard drive activity LED, one that connects to your hardware reset switch. Yes, it’s that dumb. Basically it just watches the LED and if it hasn’t flashed in awhile (no idea how long, maybe a minute?) it reboots the computer.

It seems to work, although I haven’t had a real test yet. Most importantly, it hasn’t caused a false reboot after 36 hours of testing. It did reboot the computer when I ran /sbin/halt though, which is a good sign. I had to stare at the panel of my computer for awhile to verify the HDD activity light was actually flashing. Apparently this light works even for modern SSDs plugged in via M.2!

(Fun fact: /sbin/shutdown -h, the command I always use to halt computers, doesn’t actually halt. See this systemd man page for details. “-h” is a synonym for “--poweroff”. You want “-H” or “--halt” to actually halt the CPU without also shutting off the system power. I imagine this is for historical reasons; back in the old days you couldn’t turn the power off with software. Then when that became possible it became the default because it’s almost always what you want.)

There’s a bunch of versions of this hardware watchdog idea; this one is reasonably well documented. Power could also come from an old school Molex connector or using the 9 pin USB motherboard connector, maybe with an adapter. I just routed the wires outside the case and used an external USB port. It’s all spectacularly dumb.

The one hassle with the device I bought is it doesn’t have cable splitters, it replaces the existing LED and switch. I bought some ridiculously overpriced splitters. (Turns out this kind of cable and connector is called “Dupont Line” or “Dupont Cable”.) Now my LED isn’t flashing any more; either I screwed up the wiring or there’s not enough power once split.

When I saw the USB port I assumed this device worked by monitoring the USB port itself. Test if the USB host was working. But that’s a fairly high level test and you could imagine various scenarios where it wasn’t appropriate. I imagine most computers doing useful work are still tickling the hard drive regularly enough this approach is better; if nothing else, than for logging.

Update Mar 29 2020: I’ve had this for a few weeks now and it’s rebooted my computer twice. At least one time I looked closely and it seems it really should have, the machine had locked up. So good job!

Can’t upgrade Ubuntu 18.10 to 19.10

(Major update: see this blog post for a workaround to upgrade from 18.10.)

I’ve got an Ubuntu 18.10 (cosmic) system. I want to upgrade it to the latest (19.10, eoan). I understand I probably have to upgrade it to 19.04 (disco) first, that’s fine.

Except I can’t.

# do-release-upgrade
Checking for a new Ubuntu release
Your Ubuntu release is not supported anymore.
...
An upgrade from 'cosmic' to 'eoan' is not supported with this tool.

That’s it. No options to help. I get it, 18.10 isn’t supported anymore. But it’s only 15 months old. Surely the old upgrader files are lying around somewhere?

So off to the cargo cult Internet I go.

First thing that looks promising is “How to install software or upgrade from an old unsupported release?” They advise using the old-releases sources as a way to get, well, old releases. That seems promising except following the advice about updating sources.list and running apt update doesn’t work

# apt update
Err:9 http://old-releases.ubuntu.com/ubuntu cosmic Release
  404  Not Found [IP: 91.189.88.153 80]
E: The repository 'http://old-releases.ubuntu.com/ubuntu cosmic Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.

So something about the source repo directory structure doesn’t match what apt wants? Or did Ubuntu somehow screw up the release signatures? Beats me.

So I went in to sources.list and tried hacking them all to include [trusted=yes], to ignore this error. Yeah, that’s a scary idea. Doesn’t work though. Or rather “apt update” seems to run an O(n^2) update on 124 different URLs, for ~15,000 separate updates. Or something, I dunno, it’s clearly wrong.

I’m stuck. I understand Ubuntu’s support window, or I thought I did. I didn’t realize that being just a few months out of date left you out in the cold forever. I think a full reinstall is my only option.

Update

I tried asking on FreeNode #ubuntu. No one there knew an answer. Got some suggestions on things to try though. By far the best solution is a full reinstall, but I really hope not to do that. The other suggestion is sort of documented here: basically you just hack your sources list and rely on apt-get dist-upgrade to correctly upgrade the system, bypassing the do-release-upgrade script entirely.

My concern is that do-release-upgrade does some extra thing, like modifying config files, that the dist-upgrade won’t do. But after talking about it I think that’s not true, apt really should be able to do the job. I also remember now I had trouble with do-release-upgrade once before and relied on apt to finish an upgrade for me and it worked fine. It may be it’s OK not to run that script.

Update 2

I updated a different system from 19.04 to 19.10 using do-release-upgrade. It sure didn’t look like that script was doing much other than setting up sources and running apt. I think doing this by hand for my 18.10 system (to 19.04 first, then 19.10) is OK.

Update 3

I went a little further down the rabbit hole of “what does do-release-upgrade” actually do. Useful resources: this old Stack question, this gist essay.

A key thing it does is download an updater from a metadata file and presumably run it. (There’s a shell script named “disco”). It might work to do that by hand, or else you can inspect it to try to figure it out. It’s a lot of code though.

I downloaded the disco updater (which is for 18.10 -> 19.04) and took a quick look. A specific thing to inspect is DistUpgradeQuirks.py. The disco updater has a couple of quirks. IT checks if you’re on an i386 and refuses to run. And it runs a function called _replaceDebsWithSnaps(), which is sort of self explanatory. I didn’t bother trying to figure out which debs were involved. There’s also a list of demoted packages which I imagine is a way to remove obsolete stuff. The powerpc build chain features prominently in the disco version.

So anyway, I now know that do-release-upgrade is doing more than just setting up sources and running apt. But it’s not doing a lot more, at least than I can see, and ignoring that stuff may be safe.

Linux watchdogs in 2019

My home server is dying unexplainedly. Totally locks solid, nothing in the logs, very confusing. While I figure out what’s wrong (power supply?) I decided to go implement a watchdog to reboot the system if it fails.

This turns out to be hard in 2019, with Ubuntu 19. tl;dr there are two choices: systemd or the good ol watchdog daemon. See also: softdog.

systemd has watchdog support. Unlike many things in the systemd hydra, this one makes sense to me to integrate. It’s configured in /etc/systemd/system.conf. However it’s not well documented and relatively limited, so I decided not to use it. Even so my system has a PID 77 named [watchdogd] that I think is part of systemd. No idea what it’s doing, if anything.

watchdog is the old school Linux daemon that does watchdoggy things. Ubuntu 19 offers version 5.15-2, and if you install it by default it doesn’t do much. You have to configure it via /etc/watchdog.conf, ensure it loads at startup, and (maybe) install a kernel module to help it.

watchdog works by running a bunch of different tests. It’ll try pinging a network address, check if a file has been modified, see if the load average is too high or if there’s no RAM available. If not it’ll reboot the system. The shutdown is internal, it doesn’t fork any processes.

By default the Ubuntu watchdog.conf has no tests enabled. I think this means it does nothing at all. (It’s possible there’s some “if the system is totally dead then reboot” thing still hiding in there, but if so I don’t see it.) To be useful you want to configure various tests. I have it pinging my router; in theory my computer is still working even if the router is down, but in practice it seems more likely my server’s networking has died. (There’s a systemd upgrade bug.). I’m sure this will end up shooting me in the foot some day.

This is what a watchdog shutdown looks like in the syslog

Oct 13 18:57:31 ub watchdog[30919]: no response from ping (target: 192.168.3.1)
Oct 13 18:58:33 ub watchdog[30919]: message repeated 31 times: [ no response from ping (target: 192.168.3.1)]
Oct 13 18:58:33 ub watchdog[30919]: Retry timed-out at 62 seconds for 192.168.3.1
Oct 13 18:58:33 ub watchdog[30919]: shutting down the system because of error 101 = 'Network is unreachable'

BTW, this is the point to note that in theory if you screw up a watchdog config bad enough, the system might reboot itself so fast you can never get in and fix it without rebooting single-user mode at a console. Fortunately the default config is to reboot after 1-2 minutes of failure, giving you time to get in and fix anything dumb or disable watchdog entirely.

What happens if the machine is so locked up that the user space watchdog process can’t run at all? What will trigger a reboot then? Enter kernel support for watchdogs, a feature that goes back to 2002. The basic idea is if some process ever writes to a file named /dev/watchdog, if that file is not written to once a minute the kernel will reboot itself. The kernel’s own watch on itself is implemented at a low level with some sort of CPU timer. Serious systems have extra hardware for this kind of self monitoring, but this method should work reasonably well on a consumer PC unless the kernel itself or the whole CPU locks up.

However if you look on Ubuntu you don’t have a /dev/watchdog file. You have to install it. The simple way is to “modprobe softdog”. Getting this to happen at boot time is remarkably difficult because the module is blacklisted and systemd refuses to load it. The best workaround is to modify /etc/default/watchdog to load “softdog” as a module, fortunately they thought ahead on the need for this. Once you can do that you can enable the test in watchdog.conf.

Putting it all together, here’s how to enable a watchdog in an Ubuntu 19 system

  • apt install watchdog
  • edit /etc/default/watchdog to load the “softdog” module
  • edit /etc/watchdog.conf to enable the tests you want. I enabled ping and watchdog-device.
  • run “systemctl start watchdog” to enable it (or reboot)
  • check the syslog to see that watchdog is logging your active tests and looks reasonable

Update

Sadly the softdog isn’t enough to fix my problem; apparently the computer freezes so solid that the little bit of software needed to reboot doesn’t run. Maybe the CPU locks up entirely, I have no idea.

One escalation would be a USB hardware watchdog like this or this. Looks like it doesn’t require software at all; it plugs right into the hardware reset switch on the motherboard. Presumably it uses USB to power itself and monitor if the computer is working. These are sold for Bitcoin mining rigs, that’s hilarious.

I wish I could find out what was causing the computer to freeze up and replace it. Could be the power supply or motherboard or CPU or RAM.

Update 2

Turns out PCs and Linux do have a proper hardware watchdog, called the TCO Watchdog. There’s some info about it here. The key thing is the iTCO-wdt kernel module and the wdctl userspace tool. Also more info about systemd’s support here, which includes some useful details on the TCO thing.

I worked around my problem with an external hardware watchdog.

Upgrading systemd kills Ubuntu networking

Two or three times this year I’ve had a bug in a relatively fresh Ubuntu install where upgrading systemd kills the networking. I’ve got no idea what’s wrong and no physical console on the machine to inspect it. It feels like something simple like the upgrade script shut down networking but then didn’t bring it back again, but of course it could be anything.

So far this is happening only on my 18.10/19.04 box in San Francisco. Fortunately I have physical access so at least I can reboot it (usually). I haven’t seen it happen on my 18.04 box in a datacenter.

Ubuntu has a couple of recent bugs about this. Bug 1803391 boils down to a one time bug in an upgrade script in systemd. Bug 1782709 is open and confirmed with many reports and no clear idea what might be wrong. It looks like the kind of bug report that stays open for 4 years until someone closes it as irrelevant :-(

I do not want to learn so much about the guts of systemd and dpkg to diagnose this. systemd is particularly gnarly to debug since it does so much. Among other things it’s also capturing system logs, so there’s a risk whatever is being logged about the error is disappearing during the upgrade. Or not, who knows?

Again, I’ve made my peace with systemd, but this bug is a great example of the danger of centralizing so many functions into one component.

Edit I’ve placed a hold on systemd upgrades for now. Never upgrading systemd is not a solution, but this will serve as a reminder for me to only do the upgrade if I’m able to access the physical machine.

systemd and PolicyKit1

I’ve mostly made my peace with systemd but its usability sure leaves a lot to be desired. My fun interaction for today, trying to start a small service:

$ systemctl start hover-dns-updater.service
Failed to start hover-dns-updater.service: The name org.freedesktop.PolicyKit1 was not provided by any .service files
See system logs and 'systemctl status hover-dns-updater.service' for details.

A surprising error, particularly since I’m not even using any sort of desktop Linux. And no, the suggested systemctl status command doesn’t show any information at all about why the service failed to start, the log is empty.

The simple fix was to re-run systemctl as root, with sudo. Everything worked! That’s probably what one should do in reality anyway. I’m not up to date on Ubuntu’s current status of least privileges and user accounts, but in general “starting system services requires root” doesn’t surprise me.

However, there is another way. Install the policykit-1 package with apt. That will allow that systemctl command to work without being root. It requires you type your user password to authenticate yourself (again), so it’s not clear where it’s really useful.

I’ve never heard of policykit. This is what the README says:

polkit is a toolkit for defining and handling authorizations. It is used for allowing unprivileged processes to speak to privileged processes.

Yet another new server setup post

My little projects server at somebits.com is dying. The disk errored and remounted itself read-only two weeks ago and I only just noticed. Time to set up a new server. Last time I did this five years ago I took careful notes and they are useful to me now. So another boring blog post about the new server. These recent notes for my home server were still useful.

I’m still treating Linux servers as these little carefully customized hand crafted collection of installed packages, configurations, crontabs, etc. The real world has moved on to managed services but every time I look to do that for myself it’s either too much work for a little tiny service (docker, chef/puppet/whatever) or else too expensive (cloud hosting). This time around I got recommendations to look at Ansible for low-impact server setup automation, but given I set up one server every 5 years it seems overkill. Also recommendations for Dokku as a free hosted service manager. That in turn creates Docker images and also feels like overkill and a bad match for Apache.

Part of me would love to just push all this server management “to the cloud”. But it’s still not cheap to do that for anything custom / dynamic. My old server was $59/mo, my new server is $25/mo. For a dedicated bare metal machine. It’s hard to match that price using fancy cloud stuff. My long term goal is to get my services down to simpler static files so I can just host them that way, without complex software. And any new complex software I do make, do it with cloud management.

It’d be really nice to replace Blosxom with some static site generator; then literally everything I serve on the Web would be static files. Doing that requires resolving my other blogs too; this secret work blog, also my linkblog / Pinboard account.

What to install

Looking at my list from 5 years ago I still run most of the same services. Except now I feel it’s time to shut a few down. The live rivers map; it’s a tutorial for outdated technology. And logsoflag, it’s also outdated and not something I want to keep working on. The rivers system was the most complex thing I ran (postgres, tilestache, nginx proxy, ...) so not reinstalling it saves a lot of time.

Most of what I serve is via Apache and virtual hosts. Things to get working:

  • somebits weblog: Blosxom CGI
  • somebits.com: static files
  • windhistory.com: all static files
  • somebits.com/rivers: replace with shutdown notice
  • logsoflag.com: replace with shutdown notice, maybe leave the tool working in legacy status.
  • n177xy.com: shutdown notice
  • daedalusbits.com: shutdown notice
  • Let’s Encrypt certificates for *.somebits.com, windhistory.com, logsoflag.com. Separate certificates for the three this time.

I also have some other stuff running that needs installing:

  • autossh tunnel to my house
  • crontab entries for blog, linkblog
  • munin: default config
  • chrony: default config

Configuration Notes

apache. Default Ubuntu 18 config is OK; it uses the event MPM which is reasonable. I added the following modules: cgid expires headers rewrite ssl userdir. Configured charset to utf8, added my own nelson.conf. update I forgot some content was in /usr/lib/cgi-bin; had to restore that three months later!

blosxom. Had to install libimage-size-perl for one of the Blosxom plugins. Also had to patch a problem in the atomfeed plugin; the use of {{{updated}}} as a template fell afoul of a backwards incompatible language change in Perl 5. <3 ancient languages. Also had to install python-minimal to get a /usr/bin/python (that’s Python 2), for some ancient cron jobs.

munin. Has to be installed after apache, or the apache stuff doesn’t get installed.

autossh. Same as before.

rsnapshot. Same as before.

Outcome

New server is all set up, remarkably easier since I could just look at the live running server and copy files from it. I had a backup, but nothing like a live system to clone...

Then I tried to get the disk back read-write so I could wipe it. What a mess. Trying to remount failed because the block device was marked read-only, presumably by the device driver. Trying to re-mark the block device just didn’t work. So then I ran fsck on the disk, the one mounted read-only as the operating system. Lol. Machine locked up solid. Also didn’t reboot. I guess I was hoping fsck would either refuse to run if the disk was mounted, or else somehow magically the OS would keep working even with fsck running. Nope.

RIP little server. 5 year at $59/month comes to about $3500. The hardware probably cost $1500, but then I’m playing for hosting too.

SyncThing

After getting NextCloud set up I was uncomfortable with how complicated it was. So I gave SyncThing a try and it’s much more to my liking. It’s a much simpler system. NextCloud has a full database and users and passwords and APIs and stuff. SyncThing just synchronizes folders. In that way it’s a lot like Unison, or FreeFileSync. (More complicated than rsync, since it maintains state between synchronization runs). But it’s built for network synchronizing.

Installation is simple. Every machine that wants to sync a folder runs the SyncThing binary in the background. That publishes a nice Web UI on port 8384, also an application specific socket on port 22000. Getting two machines to sync is a little weird. Every machine has a name and you can just tell machine 2 “sync with machine 1”. A dialog pops up on machine 1 then to authorize the connection. No visible passwords, but presumably some public key crypto under the hood. Once the machines are talking to each other you then set up synchronizing folders.

I may have made things complicated myself but the folder setup seems complicated. For every new machine I add to my sync cluster I had to go through each folder and share it. There’s something called an “introducer” where one machine will offer a list of folders to the other machine, but I either don’t understand it or broke it somehow.

I also made things more complicated than necessary by disabling machine discovery. I mentioned way above machines have names; how do you find a machine on the Internet given its name? There’s some global discovery protocol built under the hood, a peer to peer network sharing names. It’s quite neat but I’d rather not be quite so promiscuous so I turned it off. You can manually configure via IP addresses if you want. (They also have a relay network for cases where two machines are so firewalled they can’t connect to each other. Neat!)

I haven’t stressed the sync algorithm too hard but it seems to be working for me. It even does something reasonable for conflicts.

I took a quick look at GitHub and the primary author is Jakob Borg, aka calmh. He also has a consulting business called Kastelo. He seems super nice and helpful on the community forum answering lots of questions. Development started late 2013.

All in all I’m quite impressed with SyncThing. It’s simpler and less featurful than DropBox/NextCloud/ownCloud, which is exactly what I want. Keep two folders in sync, that’s all I want.

(A thorough blog post would include an investigation of Resilio, formely BitTorrent Sync. By all accounts SyncThing is quite similar to it.)

Hosting your own Dropbox clone

I decided to set up my own private file syncing service. Dropbox recently degraded their free level, limiting you to three devices. Fair enough but ugh. Also I’ve been doing a funky hack with FreeFileSync where I keep personal files on two Windows boxes in sync via an external hard drive I carry back and forth. That works and solves the bandwidth problem, but is kludgy.

So.. what’s out there for free Dropbox alternatives? A quick search turns up ownCloud, NextCloud, and Seafile as popular choices. NextCloud is a fork of ownCloud and seems to be doing well so I picked that one.

NextCloud requires you’re running a server on an always-on Linux box somewhere. Installing the server is either a complex mess or as simple as could be. If you go the old school manual route it’s a mess; the server requires MySQL and a web server and a bunch of PHP stuff. They have detailed docs on how to install it on Ubuntu, but ugh.

Happily they also have a containerized server, Nextcloud Snap. And I’ll be damned but it really is as easy as a couple of lines of shell to install and get running. The only wrinkle I ran into is they really want to be running a visible web server under the / URL, and I already have a web server. So I had to change the ports the web server uses

sudo snap set nextcloud ports.http=81 ports.https=444

So far it seems to be working, we’ll see how it does in a month. The product is probably overkill for personal use, it’s really set up for a whole small office with many users, fancy integrations with apps, etc. I just want a better rsync!

The one thing I didn’t evaluate is SyncThing, the outcome of the old BitTorrent company that is in fact a better rsync. I’d like to try that and see if it’s a lightweight alternative.

Update: a second wrinkle; all my user files are being stored in the Snap directory, which is on the small / fast SSD. I wanted to replace that data directory with a symlink to a slow hard drive, but of course the symlink goes outside the Snap container’s boundaries and doesn’t work. There’s various workarounds for this but for now I’ll just live with it.

Learning about containers

I decided it was time I learned about containers. My immediate goal is considering running the Pi-Hole DNS server in a container via docker-pi-hole or manually installing it under LXC. It’s a toy problem, but it’s one I’m considering at the moment. Really it’s an excuse to learn more about containers. I’m a newbie here and there’s a lot of depth I don’t have, but maybe my notes are helpful to someone.

What’s a container? It’s a way to run a program or collection of processes so that the service they implement is relatively isolated from the host operating system and other services running on the host. The isolation is mostly for system administration convenience, a little like we use virtualenv in Python or node_modules in Node to keep libraries separate. Only a lot more complicated than just a bundle of files. Containers package up files, running processes, network access, I/O, device access, etc.

A key reason people like containers is they provide a way to isolate a complex software package in a repeatable lightweight environment. You can hand a new employee a Docker image for their development environment without laborious instructions on how to get set up to work. Or a developer can spin up an environment on their dev machine that’s just like the one in production, run some tests, tear it down, and rebuild it frequently and fast. See this AWS Lambda emulator as an example.

Another key piece of containers is they are lightweight. A VM takes 10-60 seconds to start up (or more); a Docker container can take less than a second. The container doesn’t need much more memory than the processes running natively. And there’s a lot of tooling that makes it easy to build container images and manage them in a space-efficient manner.

Some overview reading:

Not containers

To understand a thing, first understand what is not that thing.

Virtual machines are not containers. Well, a VM is a container in some sense, but it’s more heavyweight than what people usually call a container. In a container there’s not a whole kernel and guest OS running; the processes are running directly on the host kernel. But those processes are isolated in important ways. A container is more like the traditional Unix security model of running a service as a user with access limited to just some smalls et of files. Or like the venerable chroot, which dates back to v7 Unix in 1979. But the old Unix methods of isolating a service’s processes don’t work very well, so modern containers use a newer set of kernel interfaces to enforce isolation.

AppArmor is also not containers. AppArmor uses Linux Security Modules to grant certain programs a very narrow set of permissions. These are configured with files in /etc/apparmor.d, you can browse Ubuntu’s here. For instance chronyd is limited to things like setting the time, binding a network socket, and writing a few files like logs in specific chronyd directories. If chronyd starts trying to do anything else AppArmor should stop it.) AppArmor has some overlap with container tech (LSM is a bit like seccomp). And some containers (like Docker) use AppArmor as extra security. but AppArmor is intended as a security measure, not a devops tool. (Same goes for SELinux; can be used to help secure a host running containers, but not a core component of the container.)

Container technologies in the Linux kernel

Containers implement isolation with help from the kernel. Unix has always had a modest concept of processes being isolated from each other. Memory isn’t shared by default, user permissions enforce some isolation on who can access files and other resources. But it’s not very secure and it’s not very flexible, so modern containers rely on newer APIs developed in the last 10-15 years. Many of these are fairly Linux specific, although both BSD and SysV were influential in the 90s and 00s developing isolation technologies like BSD Jails.

Namespaces are a Linux kernel feature for completely isolating one set of processes from another. In normal Unix you can see another user’s processes even if you can’t do anything to them. Inside a PID namespace you can’t even see others’ PIDs to try to access them. Same goes for filesystem namespaces, network namespaces, etc. Namespaces are created with the unshare(1) command which uses the unshare(2) system call. See also namespaces(7). You can create separate namespaces for mounted filesystems (a bit like chroot), hostname, IPC, IP network, PIDs, cgroups, and users.

cgroups (“control groups”) are a way to manage resource usage for a group of processes. nice(1) is an example of a very simple form of CPU resource usage. cgroups let you control not only priority (like nice) but also absolute amount of CPU used in a period of time, memory usage, I/O, process creation, device access, etc. The API is quite complicated, I think mostly because it works on groups of processes (and threads). See also the cgroup v2 design doc.

Seccomp-bpf is a way to control what system calls a process makes. System calls are the primary way a process affects the rest of the world; limiting system call access can greatly isolate a set of processes.

capabilities are a different way to restrict what a process can do, based on abstract capability concepts instead of system calls. I mostly think of it as a way to avoid giving a process full root access just to do one simple thing. Instead you can give a process just the ability to bind privileged ports or set the system clock or whatever specific capability it needs.

A word on security

I can’t figure out how secure containers are supposed to be. How hard should it be for a rogue process to break out of a container? The best answer I’ve gotten is “it depends on how secure you made your container”. (Which in practice seems to be “not very”). FWIW I asked on Twitter and pretty much no one considers a Docker container to be a significant security measure.

I looked a bit closer into this with Docker in particular. Docker is so complicated and uses so many different Linux security mechanisms that exploitable bugs are inevitable. And Docker is designed to not be fully isolated or virtualized; most Docker containers deliberately have at least some access to the host system, a network port or part of the filesystem at least. The Docker folks do take security seriously, and when security holes are found they get the full CVE treatment. Still it seems no one considers Docker a full solution for running untrusted code safely.

One big thing I learned is if a process has root privileges inside Docker, then if it escapes the container it very likely will have root outside the container too. There is a way to map root-in-the-container to a non-privileged user outside the container, but it’s complicated and I’m not sure how common it is. Pretty sure it’s not the default.

Bottom line: don’t assume a malicious program inside a container is really trapped inside the container. Too bad, I’d been hoping Docker would be a good way to mitigate the risks of daemons that run as root. It might yet be such a tool but it ain’t simple.

Update: containers vs. Zones vs. Jails vs. VMs is good reading.

Container implementations and tools

So there’s a bunch of low level kernel support for isolating processes in Linux. How do you use them conveniently? A container implementation bundles all those mechanisms together into one easy-to-use tool. And miraculously, a tool that might even work on something other than Linux (perhaps with a VM to help things along). There are a bunch of container implementations out there, let’s look at a few of them.

Docker is the big player for containers and whole books are written about it. Docker wraps up a bunch of those isolation technologies and makes them easy for an end user to use. Docker is cross platform: you can run other OSes both as Docker guests and as Docker hosts, although often when you look there’s a VM involved in making that possible.

To use Docker you start by getting a Docker image from a repository like Docker Hub or else create your own image. Docker images are created from a specification in a Dockerfile; the image is a collection of files and expected behavior. You then launch the image via Docker’s runC / containerd system, which creates a container. Inside that container environment is whatever the image was specified to do; one simple command line tool, a persistent daemon, a full-fledged operating system image with interactive shells. Docker takes care of managing file persistence so you can shut a container down and restart it again with the same files. Docker’s use of overlay file systems is particularly nice here, you can assemble a container out of a stock Ubuntu file system, an overlay for (say) a database server, and then an extra overlay for your actual database state that’s changing all the time. It’s all quite efficient.

The key thing about Docker is that it’s a pretty solid tool, friendly for developer-users. Also Docker Hub is amazing, it’s a community managed library of operating system images with all sorts of complex and useful things preinstalled. My devops friends also like the way a developer can run a Docker container on their dev machine to test their product, then run basically that same container on production machines to serve live traffic.

Docker’s not the only game in town though. Linux Containers (aka LXC/LXD) are a nice smaller alternative. (Docker started life as an LXC wrapper although it has since evolved.) I liked this tutorial on running Pi-Hole in LXC because it’s so straightforward and simple compared to all the stuff surrounding Docker. OTOH it lacks all the conveniences the Docker ecosystem has built up.

Snap also has my attention because it’s built in to Ubuntu. It’s Canonical’s answer to Docker. I haven’t heard of many people really using Snap but there’s a few hundred Snap-packaged apps in the store (including some that baffle me; why package the command line tool jq as a Snap?) Most of what I’ve read about it is trying to use Snap to solve the “how do I distribute user applications on Linux?” problem. Canonical wants Snap to work across Linux distros. Also I’ve read a claim that Snap is somehow better suited for GUI apps than Docker would be. It’s interesting that Firefox and Slack and the like are available as snaps.

gVisor is an interesting alternative I mention briefly because it takes a different approach. Instead of a bunch of Linux isolation technologies it works by emulating most of the Linux kernel in a user space process. That makes it more like a VM, and also a little like the Windows Subsystem for Linux. I have no idea if anyone uses it, but it’s nice that it drops in to Docker as an alternative for runC.

So there’s a bunch of ways to run a single container. In addition there are complex orchestration software layers out there to help you manage a machine cluster running lots of services in containers. Kubernetes is the one that gets most of the attention right now, there’s also Docker Swarm and Apache Mesos and a bunch of others. I haven’t looked into using any of these but I can say back in the day Google Borg was The Shit, a key part of how that company could operate at the scale they do.

So what about Pi-Hole in a container?

So now that I’ve read several books on yak shaving.. should I run Pi-Hole in a container at home? I think no. The main problem is that at least with Docker, I still have to make changes in my host computer in order to use Pi-Hole on it under the container. And there’s no real reason I can’t just run Pi-Hole directly.

Pi-Hole distributes a nice Docker image I got up and running. But it’s a bit tricky. First, Pi-Hole wants to own port 53/TCP and 53/UDP on your host, to provide DNS services. Fair enough but by default in Ubuntu systemd-resolvd already laid claim to it and gets in the way because of the strange way Ubuntu machines do DNS. So you have to modify the host network config to make it available, which sort of obviates the whole “I’m running Docker so I don’t have to make changes on my host machine” argument. Pi-Hole also wants 80/TCP and 443/TCP; not just for the admin page but also to redirect ad HTTP requests to something that returns an empty page. Again same problem, I already have a web server.

Bottom line; the Pi-Hole service wants to do stuff in the host’s network namespace, and that’s all a bit awkward since the whole point of Docker is to contain things. I’m out of my depth here but it’s a shame there’s not some way to just publish the services on a second IP address for the container, like the docker0 network device listening on 172.17.0.1. Actually that may be entirely possible, but then I have to convince my whole home network where it can find 172.17.0.1 and that’s more routing infrastructure than I have.

On top of it being awkward, Docker does introduce a fair amount of overhead. There’s the docker daemon itself (1 gigabyte of RAM mapped! Although only 100MB used.) Also containerd. Those are more daemons to fail, or have security holes, or just to have to know about.

Still Docker does all more or less work. And the overhead wouldn’t be such a big deal if I were using Docker for other things; installing various versions of PHP, say. And if I didn’t quite trust Pi-Hole to be well behaved Docker would be a more appealing choice. I kind of like the idea of an OS where every user process runs in something like a container. We’re not quite there yet.

I’m glad I did all this learning about containers! They’re neat! But they mostly solve a complexity problem I don’t really have in my little world. I still get by OK hand-managing a single Linux server and making sure my stuff is all installed in separate directories as systemd services or whatever. I definitely see where Docker is a huge help though when coordinating with people or reusing stuff in a more composed way.

Ubuntu 18.10 install notes

I’m updating my venerable home Linux server to Ubuntu 18.10. Installing on an SSD, and I figured I’d take the advantage to start over rather than bring along this Ubuntu install I’ve been coddling since 2011. Nothing like a little spring cleaning.

It’s remarkably tough to tell what all is running on a crusty old barnacle server like mine. I found the output of “ps -xaf” and looking at crontabs to be most useful. systemctl’s output is so noisy to not be very helpful. nmap is a good backstop for checking out network services.

All told it took about 2 hours to get the software environment set up more or less like I used to have it. That seems incredibly fast to me! It took 2-3 more hours to install more persnickety things and I am still apt installing various random command line tools I’m missing.

Boy SSDs are nice. The machine boots in about 6 seconds. Really 3, but then we waste 3 seconds (or more) waiting on the buggy r8169 Realtek driver for the ethernet to come up. I tried ordering a replacement Intel NIC but the one that arrived from Amazon was counterfeit.

The drive I’m replacing has run for 61289 hours, or just about 7 years. Been turned off and on 41 times. Smart has logged 0 errors for it. Not bad, li’l WD Blue!

Things I did and random notes

“curtin” is the name of the Ubuntu installer. It leaves a couple of little named turds behind in /etc/apt/, /etc/cloud, and /etc/default/grub.d.

A lot of Ubuntu wiki docs are seriously outdated, often describing things that were only relevant in 2014 in the pre-systemd days. Caveat lector.

Configuration change

Immediately run apt update; apt upgrade. No idea why this isn’t done automatically.

Add a static IP configuration in /etc/netplan, removing the old 50-cloud-init.yaml that was there. The default DHCP configuration is perfectly reasonable but I want my server to work even if DHCP is down.

Edit /etc/default/grub to add fsck.repair=yes to the kernel command line. I’m not certain but I think this is the systemd way to ensure the boot disk is really fscked at boot time. Note there’s a bug in Ubuntu where /etc/default/grub.d/50-curtin-settings.cfg overrides the setting of GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub. I swore a little and then edited the offending 50-* file. This bug may be fixed in December 2018.

Stuff I installed

python3.7 and python3.7-venv. Cosmic (18.10) defaults to 3.6.

chrony to replace the crappy systemd NTP implementation.

plexmediaserver from their Ubuntu repo. Bless their hearts, this is still buggy so many years later, but it mostly works. Ignore any weird warnings about “Conflicting distribution”.

postfix as a local machine. this means mail stays entirely local, so mostly useless, but lets cron errors get through

munin. good ol’ system monitoring. I love the inscrutable graphs.

rsnapshot for backups both local and remote. I like the idea of Duplicati but after its last install corrupted itself I’m not in a hurry to install it again.

samba. This just worked?! I borrowed bits of my config from before but that was pretty simple, just set up a couple of shares. Samba used to be such a heartache to get working, amazing.

SABnzbd for Usenet downloads. This turned out to be remarkably complicated. Ubuntu 18.10 has a recent version in the repo, but the setup script is not great.

  1. Install sabnzbdplus. Ignore the suggested packages
  2. Create a nzb user. useradd -r nzb; usermod --lock -s /usr/sbin/nologin nzb
  3. Edit /etc/default/sabnzbdplus. You have to change USER. Default port is localhost:8080, I changed that too.
  4. service sabnzbdplus start
  5. point a web browser at the instance, use the configuration wizard
  6. if you had an old config, it’s stored in ~nzb/.sabnzbd/sabnzbd.ini. Server passwords are helpfully in plaintext.

Stuff I didn’t have to do

Some things I’m used to doing on new systems, but weren’t necessary.

Install locate, the doodad that lets you do a fast find for a filename. Ubuntu 18.10 comes with mlocate already installed.

Set up unattended-upgrades for security fixes. It was already installed for me.

Set up powersaving. The default configuration is powersaving for the CPU, you can verify via cat /sys/devices/system/cpu/cpu$FIRSTCPU/cpufreq/scaling_available_governors. (To configure this see systemd ondemand or else cpufrequtils).

Change the I/O scheduler. CFQ looks to be the default now.

Kernel module blacklist

Ran across a fun part of my Ubuntu system today, /etc/modprobe.d/blacklist*. It comes from the kmod package and contains a list of kernel modules which are included in the Linux sources, were compiled and shipped with Ubuntu, but nevertheless are being banned because someone made the choice they didn’t like the module. It’s kind of hilarious.

I can’t find a web-linkable version of the default Ubuntu files, but here are some gems from them. I suspect each entry here is a series of hard-earned lessons.

# causes no end of confusion by creating unexpected network interfaces
blacklist eth1394

# ugly and loud noise, getting on everyone's nerves; this should be done by a
# nice pulseaudio bing (Ubuntu: #77010)
blacklist pcspkr

# Framebuffer drivers are generally buggy and poorly-supported, and cause
# suspend failures, kernel panics and general mayhem.  For this reason we
# never load them automatically.

# Many less commonly used network protocols have recently had various
# security flaws discovered. In an effort to reduce the scope of future
# vulnerability exploitations, they are being blacklisted here so that
# unprivileged users cannot use them by default. System owners can still
# either modify this file, or specifically modprobe any needed protocols.

I was looking for this because I’m reinstalling Linux on my server and there’s still some drama about the r8169 driver, with some suggestions to lacklist it and build a vendor driver from source.

In the grand old days I used to build my own Linux kernels. But I always statically linked them, no loadable drivers, no init ramdisks. One kernel carefully sculpted to work on my one particular computer. It’s kind of a dumb way to make a system work.

Let’s Encrypt refresh

Back in 2016 I did a half-hearted attempt to enable SSL on my web servers, by using Let’s Encrypt. At that point all the scripts were relatively new, I think I used certbot 0.27. The little project is all grown up now and is already deprecating a protocol I relied on (ACME TLS-SNI-01). They were nice enough to send out a warning email about it, although dumbly the sent the “Action Required” email before the site’s docs have been written.

I read enough docs to realize that changing protocols basically means getting a new certificate. Also realized I needed to upgrade certbot, or at least really should, so basically I started over. Here’s what I did

  1. Removed the old certbot. Bits of it were in $HOME/ssl, $HOME/.local/share, /etc/letsencrypt, /var/log, and root’s crontab. Kind of a mess.
  2. Follow the Ubuntu instructions to follow a PPA for the new certbot
  3. apt-get install python-certbot-apache
  4. apt-get install python3-pyasn1
  5. Run certbot --apache and trust its configuration
  6. Test with ssllabs

Really all was super simple, hats off to EFF and Let’s Encrypt for building such a turnkey tool. The only wrinkle in my config is that all my server’s domains share a single SSL certificate with a bunch of different domain names on it. It’d be cleaner to have those separate, I imagine there’s some way I can do that.

I haven’t tested that all my sites work right under SSL. Both Windhistory and Logs of Lag are complaining about mixed SSL/nonSSL content. Meh.

Linux: adding a drive, UUIDs

I replaced a 7 year old drive in my Linux server. The drive had been complaining about bad blocks in SMART forever (which still mystifies me; drives should be able to just remap those). But I was seeing other signs the drive might be failing, so better safe than sorry.

The thing that made this complicated is I wanted to be sure I understood how device names worked so I didn’t screw up which drive was mounted where. Old school names like /dev/sdb1 seem fine, but those names change if you remove drives, add new ones, etc. So I read up and learned the new hotness is to mount drives by naming their UUID, some stable unique string based on the drive partition’s geometry. /etc/fstab will take a UUID in the first column instead of a device name and happily mount it for you. That’s it, pretty simple. In particular udev is not involved and there are no symlinks required anywhere. I have no idea how mount finds the device named by UUID but it works, so I’m happy to remain ignorant.

I replaced the old 7200 RPM WD Blue with a 5400 RPM WD Blue. That’s kind of a cheap drive for a Linux server but I’m only using it as a backup volume. I keep being tempted to get an SSD for the main system volume.

Here’s the steps I followed for the new drive, mostly following this guide.

lshw -C disk: find the new hard drive. Easiest way is to match it via serial number, or other characteristics like size and model name. My new disk got named /dev/sdb, which awkwardly was what the disk I just took out was named too.

smartctl --smart=on /dev/sdb: turn on SMART for the disk. Honestly I don’t exactly know what this does but it seems like a good idea.

fdisk /dev/sdb: partition the disk. fdisk is the old school MBR partitioning, which is limited to 2TB maximum. My disk is 2TB so that’s OK. Newer systems use GPT (an EFI thing) and parted. I just made one large partition for the whole disk.

mkfs -t ext4 /dev/sdb1: make the filesystem. There’s some options here you could consider setting to get a bit more disk space or add checksumming to metadata but I stuck with the defaults. Fun fact: I was taught in 1990 to print out the list of superblock backups because if the disk failed it was the only way you were going to find them backup block IDs. I assume recovery tools have improved in the last 28 years. (Or more realistically, that the disk will be a lost cause.)

blkid | grep sdb1: find the UUID for the new partition

fstab: edit fstab to mount the new disk named by UUID.

All very easy really.


Linux I/O schedulers

My Linux server is mostly idle, but every few hours I run a backup and then the disks get very busy. I’m also trying to rebuild a corrupted Duplicati database now, a second heavy I/O load. If both run at once the system does not run very well. Worse, interactive performance it terrible; like 30 seconds to log in and get a shell.

I think a fix for this is changing the Linux I/O schedule. I checked and all my hard drives were set to the deadline scheduler. I changed them to CFQ and interactive performance seems better, although I didn’t test carefully.

I’m not clear why CFQ isn’t something you’d just use all the time. I guess there’s some overhead associated with it vs. noop but I have to think it’s not very much under normal workloads. Deadline seems like a bad idea unless you’re in a very special environment. But I don’t really understand this stuff.

Ubuntu 18, Samba, and ntlmv1

I have a security camera that writes videos to my Ubuntu 18 machine, mounting the disk via Samba. it stopped working recently. Turns out Bionic Beaver shipped a tiny little security patch which includes this:

  * SECURITY UPDATE: Weak authentication protocol allowed
    - debian/patches/CVE-2018-1139-*.patch: Do not allow ntlmv1 over SMB1
      and add tests.
    - CVE-2018-1139

They’re not wrong to change this; ntlmv1 is a terrible ancient insecure authentication protocol. But it’s just the kind of thing some old firmware is likely to require, like my camera.

The simple workaround is to restore ntlmv1 by adding this to the smb.conf:

ntlm auth = yes

Don’t do this if you don’t trust your network. For that matter don’t run Samba at all if you don’t trust your network. I mean it’s supposed to work, but I sure wouldn’t.

 

Munin and NVMe SSD drives

Summary: Munin seems to have no support for monitoring the life of NVMe SSD drives.

NVM Express is the new hotness for SSD drives.  Those are the little M.2 cards you plug in that are actually hard drives, but with more direct access to the system bus than the usual SATA interface. They are fast and compact and great. I’d like to use Munin to graph some stats on my drives, to see how busy they are and how close they are to wearing out.

Munin has an excellent SMART plugin for monitoring important drive health measures. Unfortunately it doesn’t work for NVMe drives. smartctl only started supporting NVMe drives at all last year, and they did so with a brand new output format that looks totally different from the old tables that smartctl knows how to parse.

Update: see smartctlcvt for a solution.

It’d be simple enough to make a new plugin to grab data from the new format. Main thing holding me back is I don’t really understand what all the values in the SMART report really mean. I think “Available Spare” and “Data Units Written” are probably the most interesting fields along with the various error columns, but I dunno.

Here’s an example output

 # smartctl -A /dev/nvme0
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-23-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF SMART DATA SECTION ===
SMART/Health Information (NVMe Log 0x02, NSID 0xffffffff)
Critical Warning:                   0x00
Temperature:                        33 Celsius
Available Spare:                    100%
Available Spare Threshold:          10%
Percentage Used:                    0%
Data Units Read:                    16,973 [8.69 GB]
Data Units Written:                 488,334 [250 GB]
Host Read Commands:                 463,571
Host Write Commands:                16,861,501
Controller Busy Time:               19
Power Cycles:                       13
Power On Hours:                     80
Unsafe Shutdowns:                   1
Media and Data Integrity Errors:    0
Error Information Log Entries:      0
Warning  Comp. Temperature Time:    0
Critical Comp. Temperature Time:    0
Temperature Sensor 1:               33 Celsius
Temperature Sensor 2:               33 Celsius

autossh in Ubuntu 18

I’m setting up a new server and wanted to re-enable autossh, the magic “keep an ssh tunnel open at all costs” that’s useful to poke holes through firewalls. I ended up following my old notes pretty much exactly, down to using /etc/rc.local. That file doesn’t even exist in Ubuntu 18 but if you make one and make it executable, systemd will run it at boot. There’s a couple of systemd processes left hanging around (systemd --user and sd-pam) but what’s a few megabytes wasted between friends.

I did try to make this harder though. I spent some time trying to make this systemd service work, for instance. Never could get it to work. Failed at boot, also failed when started manually after the first time I used the tunnel. systemd is doing more magic than I understand.

It’s not clear you even  need autossh if you’re using systemd. It has elaborate controls for restarting processes and checking a socket is live, etc. Here’s a sample of using systemd to keep an ssh tunnel open. I didn’t try it though. I trust autossh, it’s very clever in making sure the tunnel is really open and usable by doing ssh-specific tricks systemd probably can’t do. Also I already had certificate management working, so screw it.

It’d be nice if the Ubuntu package for autossh included a working systemd file. Ubuntu switched to systemd, what, 5 years ago? But I guess not all the packages have been made to support it.

 

NUC thoughts

I put together my new home media server. This is my first time working with a tiny Intel NUC, here’s some thoughts. See also this review.

Hardware install

  • The core hardware kit is very nicely designed.
  • There’s a lot of ports. 4 USB, HDMI, Ethernet, Thunderbolt / USB C, analog audio.
  • Building it is easy, way easier than building a custom PC. Case, power supply, motherboard, CPU are all already assembled. All you need to do is plug in RAM and an SSD and an optional spinning drive.
  • Installing the RAM is super easy. Just be sure and get SODIMMs (laptop RAM) and not regular DRAMs like some friend of mine I heard about did.
  • Plugging in the SSD is a little fiddly because you have to anchor it with a tiny screw. It looks like the screw could get trapped underneath the motherboard. It’s too bad they didn’t come up with some clip solution for it.
  • Installing the hard drive is very easy too. There’s a nice tray that pulls out. Also requires screws, but these are much less fiddly.
  • The case is very nice. The power supply brick is pretty good.
  • There are fancy blinkenlights on the front of the case you can configure, including driving via software.

It was pretty easy to put the NUC together but I’d consider paying $50-$100 to someone to pre-select and install all the hardware for me. System76 will do that but for more like $300, at least for the system I priced out.

Software, BIOS

  • The Arch Linux page on NUCs has some useful info.
  • Ubuntu 18’s server installer kernel doesn’t seem to include a driver for the WiFi. It only recognizes the onboard ethernet adapter at install time. Once installed though there’s a iwlwifi driver that seems to work. I didn’t bother trying to configure it.
  • By default the fan is running even when idle in the BIOS screen. This seems to be a particular problem with the i5 NUCs but you can adjust the settings in the BIOS to let it run hotter and quieter. I put it in the “quiet” preset which isn’t too aggressive but seems to let the fan spin down when idle and keep the CPU at about 36C.
  • lm-sensors doesn’t detect a lot of useful info, just basic CPU temperature. No fan speed and apparently it’s impossible because the interface is Intel proprietary.
  • It boots really fast. Like < 20 seconds from power on to ssh login.

Transcoding performance, GPU encoding, temperature

  • Plex supports hardware acceleration of video transcoding but it requires you be a paying subscriber, which I’m not.
  • I think general Linux hardware support for video encoding is enabled via libva but it’s complicated. I got as far as verifying with vainfo that it can use “Intel i965 driver for Intel(R) Kaby Lake - 2.1.0”. I didn’t test ffmpeg, that would be the next thing to do.
  • With software encoding Plex converts 1080p HEVC to 1080p H.264 just fine. It bursts up to 400% CPU at the start and then seems to settle down around 180% CPU. Fine for a single stream, wouldn’t work for 10.
  • CPU temperatures when transcoding vary from +50.0°C to +78.0°C. The fan is definitely running but is not very loud at all, I’d be fine with it sitting on my desk.
  • I don’t have my power meter but this review says the machine takes 13-50W.

New home media server

So I need a new media server for home for music files and Plex. My friends over at daily.co have had good luck with Intel NUCs, so I’m going to give that a try. Running Linux of course. I do sometimes use it as a generic Unix system and server for other things, but it’s not for heavy duty computation.

Parts list:

  • $343 Intel NUC7i5BNH
    The main system, based on an i5-7260U. This one is the “tall” version with room for an extra internal 2.5″ drive.
  • $163 16GB of DDR4-2133 RAM, Corsair CMK16GX4M2A2133C13
    FAIL. This is desktop RAM and will not fit in the NUC.
  • $190 16GB of SODIMM DDR4-2133 RAM, HyperX HX421S13IB2K2/16
    16GB may be overkill, but I like RAM. Also this is remarkably low latency ram (CL 13). $90 for 8GB of Crucial RAM is probably just fine.
  • $108 256GB SSD, Samsung 970 EVO
    The current hotness in SSDs for the operating system.
  • $50 1TB 2.5″ hard drive, WD Blue
    A cheap internal drive for media files. Could be bigger or faster but I don’t need it. I think the NUC is limited to 9.5mm high drives.

Total without tax is $690. FWIW Apple’s similar system is $700 for a slightly faster CPU but no SSD and only 8GB of RAM. So I’d put the Apple tax at about $120 which isn’t that bad when you think about it.

I’m a little bummed that Intel hasn’t updated this NUC in awhile; this model was first sold a year and a half ago. But nothing really important has changed in the intervening time, and there’s something to be said for a tried-and-true system.

One confusing thing; Intel is also selling NUCs with “16GB of Optane memory installed”. This is not system RAM. Optane is more of a cache for the hard drive. There’s no Linux support and anyway I’m going with a real SSD.

I’m going to build this myself. A reasonable alternative would be to get a System76 Meerkat, a rebranded NUC where they do the installation work for you. A similar system from them is about $1000.

Understanding smartctl

I have what I think is a failing hard drive in my little Linux server. Unfortunately it’s a 2012 Mac Mini so replacing the drive is a huge PITA. So.. just how bad is that drive, do I really have to replace it?

The first thing to do is enable SMART on the drive. It might already be on. But if it’s not no big deal, just turn it on.  Some of the historical data the drive has been tracking will suddenly be available, although the tables of attributes may not be. It’s safe to enable SMART and run tests while the drive is active. Here’s how to turn on SMART and also enable some automatic smart testing.

smartctl --smart=on --offlineauto=on --saveauto=on /dev/sda

You can then do a quick health check, but beware that a drive with some errors may still show as healthy

smartctl -H /dev/sda

Attributes

The next thing to do is dump all the smart data on the drive

smartctl -x /dev/sda | less

There’s a lot of data there and you can kind of read it. The confusing thing is the table of attributes; this guide here helped me understand it better.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAGS    VALUE WORST THRESH FAIL RAW_VALUE
  1 Raw_Read_Error_Rate     PO-R--   100   100   062    -    65536
  2 Throughput_Performance  P-S---   100   100   040    -    0
  3 Spin_Up_Time            POS---   208   208   033    -    1
  4 Start_Stop_Count        -O--C-   095   095   000    -    7921
  5 Reallocated_Sector_Ct   PO--CK   043   043   005    -    1490
  7 Seek_Error_Rate         PO-R--   100   100   067    -    0
  8 Seek_Time_Performance   P-S---   100   100   040    -    0
  9 Power_On_Hours          -O--C-   029   029   000    -    31378
 10 Spin_Retry_Count        PO--C-   100   100   060    -    0
 12 Power_Cycle_Count       -O--CK   100   100   000    -    158
160 Unknown_Attribute       -O--CK   100   100   000    -    0
191 G-Sense_Error_Rate      -O-R--   100   100   000    -    0
192 Power-Off_Retract_Count -O--CK   100   100   000    -    22
193 Load_Cycle_Count        -O--C-   001   001   000    -    1673246
194 Temperature_Celsius     -O----   200   200   000    -    30 (Min/Max 14/48)
195 Hardware_ECC_Recovered  -O-R--   100   100   000    -    0
196 Reallocated_Event_Count -O--CK   038   038   000    -    1614
197 Current_Pending_Sector  -O---K   100   100   000    -    152
198 Offline_Uncorrectable   ---R--   100   100   000    -    0
199 UDMA_CRC_Error_Count    -O-R--   200   200   000    -    0
223 Load_Retry_Count        -O-R--   100   100   000    -    0
254 Free_Fall_Sensor        -O--CK   100   100   000    -    3
                            ||||||_ K auto-keep
                            |||||__ C event count
                            ||||___ R error rate
                            |||____ S speed/performance
                            ||_____ O updated online
                            |______ P prefailure warning

Long story short, “Value” is a number for 1-100. The higher the number the better, 100 is perfect. “Worst” is the worst it’s ever been; maybe forever, maybe since SMART was enabled. “Thresh” is the threshold below which the drive is considered to be in “pre-fail” state.

So how’s my drive? A lot of values are 100, so it’s not a total loss. Reallocated_Sector_Ct is at 043 which is troubling but not the end of the world; drives are designed to map over the occasional bad sector.

Error log

The other thing I find useful is the error log.

Error 518 [1] occurred at disk power-on lifetime: 31377 hours (1307 days + 9 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER -- ST COUNT  LBA_48  LH LM LL DV DC
  -- -- -- == -- == == == -- -- -- -- --
  40 -- 51 00 08 00 00 31 41 12 30 01 00  Error: UNC at LBA = 0x31411230 = 826348080

  Commands leading to the command that caused the error were:
  CR FEATR COUNT  LBA_48  LH LM LL DV DC  Powered_Up_Time  Command/Feature_Name
  -- == -- == -- == == == -- -- -- -- --  ---------------  --------------------
  60 00 08 00 a8 00 00 31 41 12 30 40 00     00:07:11.085  READ FPDMA QUEUED
  60 00 40 00 a0 00 00 31 40 11 00 40 00     00:07:11.074  READ FPDMA QUEUED
  60 00 08 00 98 00 00 31 00 21 00 40 00     00:07:11.062  READ FPDMA QUEUED
  60 01 00 00 90 00 00 31 00 12 c0 40 00     00:07:11.061  READ FPDMA QUEUED
  60 01 00 00 88 00 00 31 00 11 c0 40 00     00:07:11.060  READ FPDMA QUEUED

The error details are not very useful. UNC means “Uncorrectable” and probably means some data was corrupted at that blog. But what’s super useful is the date stamp on the error along with the log. You can use that to estimate the rate of errors, whether it was a one time bad luck or something really wrong.

Running tests

SMART has a self-test built in.

smartctl --test=short /dev/sda

This runs for a couple of minutes asynchronously. Then you can see the result

smartctl -l selftest /dev/sda

=== START OF READ SMART DATA SECTION ===
SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Short offline       Completed: read failure       30%     31378         728636768
# 2  Short offline       Completed: read failure       30%     31378         728636768

I’ve run two short tests and both show a read failure. Yep, my disk is definitely not entirely healthy.

Monitoring

The clever thing to do is run smartd to track smart for you and send an email alert when the disk is failing. I’ll be honest; I do this and then don’t know how to act on the email. Replacing a disk the very first time anything goes wrong is not crazy, but it is expensive and sometimes you can accept that you might lose a file or two because it’s a backup disk or something.

 

Duplicati remote backup notes

Some notes on Duplicati for remote Linux backups. Primary opinion: seems reasonable, needs better docs.

I need a new remote backup solution for my home Linux box now that CrashPlan is truly closing up. In the past I hacked up a a remote rsnapshot option but I wanted something more user friendly. From the Hacker News discussion it seems Duplicati is the consensus choice. The other option I should explore is rsync.net.

I was backing up about 50GB of stuff on CrashPlan. At Amazon pricing that’d be about $1.30 / month. rsync.net would be $4.00/month. I can probably do this for free now on a server I have lying around in a datacenter. The fact the blocks are encrypted makes this all much more reassuring.

Installing

Duplicati runs as a systemd service. It has a web GUI listening on port 8200 and some sort of schedule thing where it runs every few hours. It stores backups in some Duplicati-specific database in encrypted 50MB chunks. The nice thing about Duplicati is it can store those data chunks on a variety of offsite backends, including any FTP, SSH, WebDAV, or S3-like service. Also support for specific services like AWS, Dropbox, etc.

Installing was kind of awkward: I followed the instructions for this headless install since the Debian/Ubuntu package they provide apparently requires an X environment. Even so I still had to install Mono, which is an awful lot of packages. Looks like the thing is written in C#.

Configuring seemed simple. I’m starting with just backing up my source code to local disk. I have a convention of putting some files in “nobackup” directories if they are huge downloads I don’t want to back up. I added a filter for that, “-*/nobackup/”. There’s also a default set of Linux filters which seems to be about not backing up any system files. Including stuff like /etc which honestly, you probably want backed up. But it seems reasonable for backing up home directories. Half-tempted to not back up my virtual environments for Python; I’ve got a bunch of 500MB monstrosities. But then it’s a PITA to rebuild them and it’s safer to just back up everything.

I made one config mistake which was to enable throttling of bandwidth. This applies even to local disk backups. I do want to throttle for network backups eventually.

Running

Anyway, set it all up and started it running. Seems to be doing something, judging by the 100% CPU usage of the mono-sgen process running Duplicati. The docs mention everything being compressed so I guess that’s where the CPU is going.

I tested this with about 19 gigabytes of files, 9 gig to be excluded by the nobackup filter. First run took 30 minutes. Duplicati said it was 9 gig to backup and 5 gig stored, which seems about right.

Second run with basically no changes took 1 minute. Backup directory expanded by about 5 MB.

A restore of a 770MB directory took less than a minute. It restored everything right, including timestamps and file permissions.

Remote backup

The local disk test went so well I went ahead and set up an ssh remote backup to a Linux server I own. I created a new user on that system, the configured Duplicati to back up to that host with a saved username / password. (There’s an option for ssh keys too). That’s about all I had to do, it’s just backing up as I speak. I did set up a network throttle at 400 KBytes/second. That seems to be consuming 3.46Mbits/ssecond, so there’s 260kbps in overhead. Probably TCP. CPU usage on the backup process is mostly about 3% when running throttled like this, with brief bursts of 100% activity. A second backup and a restore both worked fine.

Opinions

I like the product! It works well and simply. It could probably replace what I use rsnapshot for as well as my remote backups.

The documentation for the project is pretty poor, with stuff spread out over a few articles, wiki pages, and forum postings (!). Par for the course for free software. Also kind of a slow development process, it’s been 2 years+ for the 2.0 and it’s only sort of in beta now. OTOH it all seems to work, and is free, so I shouldn’t be complaining.

I’m a little nervous about my backups being in some unknown database format. OTOH the code is open source, absolute worst case presumably some nerd could figure out how to solve any problem.

 

Some ssh tricks

I’m making some ad-hoc solution for monitoring a security camera after my bad experience with Foscam. Here’s some ssh tricks I had to do to make it work.

Restricting ssh to rsync. A way to set up a passwordless SSH key for rsync that’s not a total security hole. I did something similar myself for backups awhile back.

Chaining ssh tunnels. I need to create an ssh tunnel to a second host, and from there to a third host. Tunnels more or less chain like you’d expect but you need to add the -t flag to ssh to get it to create a tty for some reason. The -A flag is handy too, of course.

 

Ubuntu 14.04 to 16.04 notes

I had a moment of foolish optimism and decided to upgrade my development machine from Ubuntu 14 (Trusty) to Ubuntu 16 (Xenial). “Just run do-release-upgrade”, the motd has been encouraging me for months now. So I did.

And it failed. And then I tried to fix it by hand and I thought I did. And then the machine didn’t reboot. So that’s discouraging. But then the second time I tried to reboot (after hauling the machine over to a monitor) it rebooted fine. And now the machine is fine. No idea what that was about, but yay for Ubuntu robustness! My reboot problem may have nothing to do with Ubuntu, but rather be a problem with my ethernet. Anyway, some notes.

On the upgrade scripts

  • do-release-upgrade runs in a screen session. Some of the upgrades prompt you to compare changes in config files, and will helpfully propose spawning a shell to let you inspect the situation. But your tty is occupied in some weird way with screen and/or scripts running in the background. I was getting all sorts of random crap on my screen and I panicked and aborted the upgrade script. Do not make this mistake.
  • You can’t run do-release-upgrade a second time. The system thinks it was already upgraded and it aborts.
  • Fortunately mostly do-release-upgrade does stuff up front, then relies on apt and dpkg to do the real work. Those tools are robust. I’m not really clear on what all do-release-upgrade does, but here’s a reference. I sure hope there wasn’t anything crucial that didn’t happen because I aborted.
  • I fixed things by running dpkg-configure by hand, then running apt-get upgrade a bunch of times. apt-get dist-upgrade is probably not a bad idea either.
  • I also improved things by removing a bunch of PPAs from /etc/apt/sources.list.d.
  • There are some install logs in /var/log/dist-upgrade, including a full screen recording.

On changes in Ubuntu 16

  • Welcome to systemd! Everything about how the machine boots is different. I mostly noticed this with warning messages printed at boot time about funky scripts in /etc/rc that weren’t up to snuff. These came from me or PPAs, not the core code.
  • “systemctl” seems like an important new command to learn. Useful commands: enable/disable, start/stop, status. Also “journalctl” to see systemd’s logs.
  • some init scripts were broken / old / weird. I have a bunch of old cruft! I fixed these by purging the packages and reinstalling them. Culprits included screen and mongodb.
  • My 2012 lm-sensors install included some kernel modules that no longer exist. Fixed by re-running detect-sensors and removing the old entries from /etc/modules
  • I’m getting an error about mount options in dmesg that I can’t understand. It doesn’t seem to be hurting anything though, so ignoring it.
  • grep thinks my syslog is a binary file, it has some nulls in it (which is terrifying!). So i have to use “grep -a” to see the whole thing.

On user programs

  • I run Crashplan which makes extensive use of inotify. The default Linux settings only allow 8192 files/directories to be watched, not enough. Here’s how to update the limit.
  • I had to manually install python3-venv with apt. Then my existing venv directories were broken and I had to rebuild them.
  • My plex server was broken. Difficulty level: systemd. I finally traced the problem down with help from here; “systemctl status” told me it was having a problem with the group. Turns out the server wants to run as group plex, not just user plex, but no one had set up a group plex. BTW hooray! The Plex team finally has an official apt repository
  • I somehow ended up with Postgres 9.1, 9.3, and 9.5 all on my system. With 9.3 and 9.5 daemons fully running. I don’t have any permanent data on the development machine so I went with a full wipe and reinstall of all Postgres. The stock Ubuntu 16 versions of GDAL and PostGIS seem to work nicely.

certbot bug and fix (NoInstallationError)

I’ve got a Let’s Encrypt SSL certificate on http://www.somebits.com. They expire every three months, so I set up certbot to renew the certificate. It wasn’t working though, the cron job got the error

NoInstallationError()

I think this bug is now fixed in certbot. But if you follow common instructions, the cron job runs certbot with “--no-self-upgrade” so you won’t get the update. Running certbot by hand will have it upgrade itself with the fix.

The underlying bug was that certbot couldn’t find the apache2 command in the PATH, because it’s in /usr/sbin and that’s not in root’s path. (:facepalm:). The committed fix has certbot checking a couple of extra directories in addition to PATH.

NFS vs Samba

My music stops playing when I write a large video file to my server.

More technically, when I write 10MB/sec via NFS to my Ubuntu 14.04 server, the Samba server on the same host (and same disk) stops serving files reliably to my Sonos system.

The server’s definitely not CPU bound, nfsd is taking 5% of one CPU. It’s probably IO bound though. The NFS client doing the writing is MacOS with the automounter, so I’m guessing it’s UDP. I wonder if I’m simply flooding my 100Mbps ethernet with NFS traffic and the TCP Samba packets can’t get through?

This happens rarely enough I’m not going to put more time into figuring it out. Sure is an interesting failure mode though.

 

Things I learned about systemd

systemd is the Linux startup system for Ubuntu 16.04, so I figured it’s time I learned about it. I’m very late to the party; systemd started some 6 years ago and became a real thing many Linux distributions used years ago. Ubuntu is the last big distro to include it by default except Gentoo, and even Ubuntu switched last year with 15.

There’s been a years-long debate in the Linux community about systemd. A younger me would have cared about that, maybe participated. These days I don’t care, I just want to use the consensus tech. The bummer is the flamewars dominate the conversation, it’s hard to learn just what systemd is. Here’s my effort to just understand it.

Disclaimer:  I’m not an expert and have undoubtedly made a mistake here somewhere. I reiterate my reminder that I really only write this blog as notes for myself. You’re welcome to comment, but please don’t waste my time with heated opinions.

References

I don’t have more links on actually using systemd in practice because I don’t yet have a system running it myself. That’s how out of date I am. The key pragmatic thing seems to be the unit files which configure how systemd launches services. systemd can also still launch stuff with old SysVInit-style scripts, including parsing the LSB headers.

Stuff I learned

systemd is init, the first user process on a Linux system, PID #1. Once the kernel is done it runs PID 1 whose job it is to then run all the other user stuff that makes a Unix system; mounting filesystems, configuring networking, starting daemons, etc.

The init most of us know is SysVInit, the shell scripts in /etc/rc.d. It hasn’t aged well in a modern era of multiple cores, dynamic devices, etc. Upstart is another Linux init system that Ubuntu has used for a long time, but no one seems to love it. Launchd is the MacOS init and deserves some respect for its speed and power; the systemd authors explicitly acknowledge launchd for inspiration.

systemd is a full rewrite of the idea of init. The primary goal seems to be mostly about efficiency. In the bad old days a Unix system could take 90 seconds to boot. With systemd (and MacOS launchd) < 1 second is possible and < 10 seconds is common. systemd is faster because it can do things in parallel. Also it avoids all the overhead of interpreting shell scripts. And supposedly it’s just modern and new and “better”, which I can’t really evaluate but can believe given the mess of stuff that preceded systemd.

systemd is Linux-only. It uses a bunch of non-POSIX APIs to do things like work with devices, configure security capabilities, etc.

I still haven’t used systemd hands-on so I haven’t learned much else. But my understanding is a whole bunch of Unix config gets consolidated into unit files in one place, which then tells systemd how to configure and launch user space programs.

I’m a little terrified of the Ubuntu 14 to 16 upgrade, it has to replace all the old stuff with the new. Will it work? Particularly reminded of an Ubuntu 12 to 14 upgrade I did where I manually installed something that changed the name of my ethernet device, making the machine unable to reboot with networking. Oops.

Opinions

I really don’t care about the history of the controversy; systemd’s a fait accompli. But it’s helpful to look at the debate to understand better what systemd is.

The big complaint about systemd everyone has is complexity. It does a lot of stuff in one big nest of 60+ interlocking binaries. It’s not just forking daemons. It’s got udev inside it to manage devices. It’s got its own logging system (in a binary format), a cron equivalent, an inetd equivalent, an atd equivalent, virtual terminals, a login daemon, watchdogs, etc. When you look at all the old Unix software that’s replaced it’s sort of astonishing and I can understand why believers in the “lots of little tools” philosophy don’t like it.

OTOH, the way the old components fit together in sysvinit was quite a hairball too. The shell hackery required to mount devices, then filesystems, then get networking up so you could access other filesystems and start other daemons in the right order and blah blah blah. Sure udev and mount might have been separate software, but they could only run correctly in one specific relationship to each other. That complex set of interdependencies had a lot of cost and somewhat made a lie of “lots of little tools”. Also there’s something to be said for unifying init and cron and inetd and login and the like; they’re all about launching programs in response to events, why not share the code?

There’s still a cultural concern that systemd, being a monolithic project, comes from one mindset only. Some of the choices seem odd to me; a binary log format for instance. That’s the part of the debate I can cheerfully withdraw from. For whatever reason most Linux distros have agreed on using systemd, and I trust that they all have the influence to shape it the way they need. That seems like a reasonable path to working software.

 

Sending SMTP email: a decade approach

I decided it’d be handy to be able to send SMTP email from my server in a datacenter. You know, like we’ve done since 1982? Only in modern times it really sucks to do this because of protections against spam, email spoofing, etc. Also I don’t want some giant network mail thing running and creating security headaches, I just want to be able to send mail off-host.

It turned out to be easy on Ubuntu 14.04. I followed this guide which boils down to “configure Postfix to be an Internet site, then make the daemon only listen on the loopback interface”. The other setup that’s important is a PTR record, so reverse DNS works. I think even without that mail should in theory work, but everyone might assume you’re a spammer.

With that setup mail to me @gmail.com worked and I’m sending email like we did back in the 1980s. But it also got classified as spam, and monkey.org was refusing to talk to me at all. The problem turned out to be that postfix was configured to use the hostname “ubuntu”. I fixed it by using the same FQDN as the PTR record (which also resolves to the same IP). Both Gmail and monkey.org will deliver my mail and it shows up as non-spam.

So now we’re up to 1990s email. Still, Gmail complained the mail it got was unencrypted. That was fixed by enabling “smtp_tls_security_level = may”. No idea why that’s not the default; the Postfix docs warn “You also turn on thousands and thousands of lines of OpenSSL library code. Assuming that OpenSSL is written as carefully as Wietse’s own code, every 1000 lines introduce one additional bug into Postfix.”. Which is a bit snide but fair enough given the OpenSSL history.

And now we’re up to 2000s email. Our modern era is much more complicated, with SPF and DKIM and other half-assed DNS based solutions to making email a bit more authenticated, but not really fixing it entirely. Those measures don’t yet seem mandatory, at least for low volume email, so I don’t yet have 2010s email configured.

One thing I left unsolved; the From: address. Mail is showing up as being from “nelson@wk.somebits.com”, which is an address you can’t deliver to. I’m OK with that, could fix it by spoofing the email, changing the Postfix from header, and/or adding MX records to enable mail for somebits.com.

(The other option to all this falderall is to give up on SMTP and mailer daemons entirely, just use a proprietary mail API. GMail has something for sending mail based on OAuth, and Amazon has SES.)

more cron fiddling

Update: this doesn’t work, see below.

I still need a better solution for running lolslackbot. Right now it’s a shell script that runs 7 Python programs that run sequentially and usually complete in about 25 seconds. I run it from cron once a minute. The problem is sometimes one script takes too long, typically because a remote API server is hung. Also it’s better (but maybe not essential?) if the script doesn’t run twice at once.

So I set up lockrun in the cron job so that only one instance of the job can run at once. This works pretty well, but lockrun has no solution for timing out a dead job. Despite my best efforts, twice now the script hung for hours (forever?) and my system stopped working.

(I can’t even figure out how to monitor lockrun’s lockfile. It creates the file once and then never touches or updates it ever again, so the file time never changes. I could monitor my underlying program’s logfile or something I guess.)

So now I’m wrapping some bailing wire around the duct tape and using timeout to add a timeout.

timeout 3 lockrun --lockfile=/tmp/lf1 -- sleep 10

Yeah, I know. But it seems to work. What could possibly go wrong?

I think the right solution is ensure my scripts are safe to run twice at once. I don’t think this is too hard semantically, and I do have a database with transactions to help mediate things. The trick is the occasional faux distributed transaction for stuff like “if I find a new row in the database, update some remote service and then mark the row as processed”. I guess I could add three phase locking for that? Ugh. While I’m at it I should make it so the 7 Python programs can run independently, at different frequencies. The very first one is the important one, the slow one, asking “is there any activity for any of these N users?” It’d be nice to run that script in parallel and somewhat out of lockstep sync.

While I’m here I wanted to give a shout-out to cronic, yet another wrapper for cron jobs that improves error reporting. cron mails you if there’s any stdout or stderr, but ignores exit status. cronic fixes it so it mails you if there’s stderr or if the exit code indicates an error. But it ignores stdout. Seems particularly useful in concert with timeout; if timeout kills a job the only way you know is exit status, which cron without cronic ignores.

Update: this timeout + lockrun thing doesn’t work. If the timeout fires then timeout kills the child process, lockrun in this instance. But that kill signal doesn’t propagate to the children. A potential solution would be to kill the whole process group but I don’t see an easy way to do that. I’m also wary of adding hacks on hacks because of the warning in the lockrun docs about how there’s no kill option in lockrun because killing things correctly is hard.

Update 2: after 9 months I think my current solution is stable. I use lockrun to be sure only one version of the cron job is running. It runs a Python program, not a shell script, that runs all my separate Python subprograms (by invoking the main() function on each.) It uses faulthandler.dump_traceback_later to implement a last resort global timeout on the whole Python program. It all feels wrong, but in practice it’s been quite robust.

letsencrypt renewal

I set up letsencrypt SSL for http://www.somebits.com awhile ago. When I installed it in early January, there was no way to renew the certs and they expired in 3 months. Happily they’ve added a simple renewal command which mostly worked. The first time I ran it I got an error “DNS problem: query timed out looking up CAA” but I just ran it a second time and it worked.

Happily the certificate renewal didn’t touch my Apache config at all, just updated the certificate.

I took the opportunity to fix some redirects in the SSL version of my site config so they redirected to https://, not http://. I’m further regretting the way I have two versions of my Apache config, some 90 lines of complicated redirects and crap now duplicated. And now edited a tiny bit, to preserve SSL. I should refactor all that but IIRC it’s complicated.

I’m a little scared to have enabled SSL without fully committing to it. I suspect Google will start preferentially serving the SSL links, so what happens if I forget to update the letsencrypt certs? So far Google isn’t serving the SSL links though, I wonder if my siteindex URLs (no https) overrides their preference for SSL.

Let’s Encrypt thoughts

I just set up Let’s Encrypt to enable SSL on my weblog server. I did this in the dumbest way possible, just running ./letsencrypt-auto --apache without understanding what it was doing. It went very smoothly and I really admire the turnkey installation that the project has come up with. Here’s a report on the result, and how it looks in Chrome:

Screen Shot 2016-01-06 at 10.46.37 AM

But of course I have some complaints valuable observations.

There’s one usability problem; the certificates expire every three months and they don’t have an automated renewal process yet. They promise one soon.

Also I lied a bit, it didn’t go smoothly, in fact it choked processing my Apache config file. I filed a bug, it’s related to a rewrite rule that is idiosyncratic to me, no big deal. But the bug reports are full of “it failed to parse my Apache file!” with the developers diligently fixing every parse problem. It feels like they’d benefit from a more sloppy parser, something that just extracts the part of the config file they really need and doesn’t try to validate / parse the whole thing. This config management stuff always sucks in software though.

As convenient as the turnkey magic is, it also made me nervous. I wish it printed a little summary of what it did to console. It seems to have installed some Ubuntu packages, munged some config files, generated a key, and reloaded Apache to enable SSL. I’m protective of my server; maybe I should have done a manual install or read the docs first.

Fortunately there are good docs, a little thin, but the basics. They store all the certs in /etc/letsencrypt/. Diffing against a backup I see they add SSL solely by creating new files in /etc/apache2; enable a couple of SSL mods, then create a somebits-le-ssl.conf for the SSL site. Unfortunately that file is a complete copy of the original somebits.conf file only on port 443 with SSL stuff added. I hate to see that duplication of configuration! I wonder if it’s partly my fault for having sloppy config files. Some ideas for doing it right: macros or include files. Of course Let’s Encrypt shouldn’t be doing that for me, but it may be best-practice to do it for myself.

Their logging config in /etc/letsencrypt/options-ssl-apache.conf was not a good match for my carefully managed logs. Their config seems to automatically write any SSL site logs to /var/log/apache2/access.log with a vhost attached. That seems like a reasonable default, but in my case I already have custom logs enabled in each site.conf file that go to different directories. Just a case of Let’s Encrypt’s defaults not being right for me.

autossh for a persistent ssh tunnel

My Internet in Grass Valley is newly fast, but my ISP’s NAT setup  means I have no way of initiating connections from outside into my home network. Nice for security, awkward for hackiness. (They do offer a DMZ configuration but when I had them enable it on the previous link it never worked and broke traceroute, so I’m not asking this time.)

Instead I’ve set up a persistent ssh tunnel so that a port on my Internet server is always forwarded through to the ssh port on my Linux server in the house. That way I can ssh in remotely through the tunnel.

The only novel part of this is autossh, which is a wrapper for ssh that takes care of restarting the ssh tunnel if something goes wrong. autossh logs to syslog and has some configuration environment variables, none of which I needed to alter. It monitors for the tunnel dying and also periodically sends traffic through to make sure the tunnel is still working. ssh also has a keepalive mechanism it’s probably wise to use.

I mostly followed this guide for setting it up. Except for the Upstart config; after spending 30 minutes tearing my hair out I remembered I hate upstart and a good ol’ BSD 4.2 rc.local script would do just fine. Also I set stuff up to run as a separate user, and made an ssh config, so really it ended up being quite different. Steps:

  1. create a new “autossh” user on both machines with a shell of /bin/false
  2. set up ssh keys without passwords for this user, so that my house computer can log into my Internet server without any passwords
  3. Set up an ssh config for the tunnel for the autossh user at home.
    Host tunnel
      ServerAliveInterval 60
      HostName example.com
  4. Test that a basic manual ssh tunnel works as user autossh, without a password. This is important; first time you have to accept the ssh key manually!
    home$ autossh -N -R 2200:localhost:22 server
  5. Put the command to launch the tunnel in /etc/rc.local on the home computer
    su autossh -s /bin/bash -c 'autossh -fN -R 2200:localhost:22 tunnel'

Note the “-s” flag to su in the init script. Without that it runs as the /bin/false shell the user has which not only doesn’t work, but doesn’t give any useful error output.

Installing openaddress-machine on a new EC2 system using Chef

No need to install stuff manually; Mike already wrapped up scripts to set up an EC2 system with Chef for us. Here’s how to use it on a brand new EC2 micro server

sudo bash
apt-get update
apt-get upgrade
apt-get install git
git clone https://github.com/openaddresses/machine.git
cd machine/chef
./run.sh

Done! The shell command openaddr-process-one now works and does stuff.

In brief, this:

  1. installs Chef and Ruby via apt
  2. runs a Python setup recipe. That installs a few Ubuntu Python packages with apt (including GDAL and Cairo), then does a “pip install” in the OpenAddress machine directory. This tells pip to install a bunch of other Python stuff we use.
  3. runs a recipe for OpenAddresses. This uses git to put the source JSON data files in /var/opt.

Update

But really, that’s so manual. If you just pip install openaddr-machine it makes a /usr/local/bin/openaddr-ec2-run script that will do the work for you. That in turn invokes a run.py script which you run on your local machine. It, among other things, runs a templated shell script to set up an EC2 instance and run the job on it.

The shell script that is run on EC2 is pretty basic. It:

  1. Updates apt (but does not upgrade)
  2. Installs git and apache2
  3. clones the openaddress-machine repo into /tmp/machine
  4. Runs scripts to setup swap on the machine, then invoke chef to set up the machine
  5. Runs openaddr-process to do the job
  6. Shuts the machine down.

The run.py script you use on your own machine is mostly about getting an EC2 instance.

  1. De-template the shell script and put it in user_data.
  2. Use boto.ec2 to bid on a spot instance
  3. Wait for up to 12 hours until we get our instance

The details of how the EC2 instance is bid for, created, and waited on are a bit funky but seem well contained.

Installing openaddresses-machine on a new EC2 instance

Just documenting some work I done. The pattern here follows my notes on making openaddresses work in virtualenv, although I didn’t use venv here. This is really how to get the minimal stuff installed on a new Ubuntu box to run our code. Just a bunch of shell commands.

Set up an Ubuntu 14.04 AMI. The smallest one will run it OK

Do the following as root:

# update  ubuntu
apt-get update
apt-get upgrade

# install pip
cd /tmp
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

# install gcc and python dev
apt-get install gcc g++ python-dev

# install openaddresses
pip install Openaddresses-Machine

# install Cairo
apt-get install libffi-dev libcairo2
pip install cairocffi

# install GDAL
apt-add-repository ppa:ubuntugis/ubuntugis-unstable
apt-get update
apt-get install python-gdal libgdal-dev
pip install GDAL

I haven’t run these commands a second time yet, but it should be close. The last line for “pip install GDAL” is probably not necessary, and it’d probably be better to install Openaddresses-Machine last although it may not matter.

Next step: automate this with Chef Solo.

After that: set up Honcho and a Procfile to run my queue service worker.

Ubuntu guest VM frustrations

I’m trying to set up Ubuntu in a virtual machine. My goal is to recreate locally an environment a little like I might get from Amazon EC2, so I can do rapid testing of deploy scripts. I don’t need an exact Amazon AMI, but a clean Ubuntu image is close enough I can get stuff working before dealing with a remote environment.

I’ve got a VM host running. It’s Ubuntu 14.04 running KVM. Seems to work.

I’ve previously gotten Ubuntu’s new Snappy working as a guest. It boots fine and I can access ports. Unfortunately this environment is a strange Ubuntu 15, which has replaced apt with the “snappy” tool. Not enough like an EC2 host to be useful.

I tried using an Ubuntu Cloud image as a guest. They ship 14.04. But it doesn’t boot cleanly:

2015-05-03 18:25:26,540 - url_helper.py[WARNING]: Calling 'http://169.254.169.254/2009-04-04/meta-data/instance-id' failed [119/120s]: request error [(&lt;urllib3.connectionpool.HTTPConnectionPool object at 0x7f0f325e58d0&gt;, 'Connection to 169.254.169.254 timed out. (connect timeout=17.0)')]
2015-05-03 18:25:27,542 - DataSourceEc2.py[CRITICAL]: Giving up on md from ['http://169.254.169.254/2009-04-04/meta-data/instance-id'] after 120 seconds
2015-05-03 18:25:27,550 - url_helper.py[WARNING]: Calling 'http://10.0.2.2//latest/meta-data/instance-id' failed [0/120s]: bad status code [404] [404]

The init scripts are waiting on some network resources to load. The IP addresses are on the local network, and I guess it’s some sort of Ubuntu cloud server configuration thing. I don’t want all that! I just want a basic Ubuntu unmanaged instance to boot. Unfortunately ssh is still refusing logins. It does finally give up but it takes about 4 minutes, way too long for the rapid iteration I have in mind. And then I can’t log in. Apparently there is no default password. This image is really not designed for the quick and dirty hackery I want.

I did learn something about how QEMU/KVM’s networking stuff works. The default IP is provided by slirp, which among other limitations does not support ICMP. So that’s why ping doesn’t work! Also it’s outbound connections only, although the “-redir” flag to kvm seems to offer some basic port forwarding.

I found this guide to using libvirt sort of interesting, it’s simple stuff for managing the virtual machine image. Although again way overkill for what I want.

At this point I think I’m going to give up on running my own KVM guests and hope that EC2 gives me a new machine fast enough that testing machine setup scripts using throwaway instances isn’t too annoying.

Update: my friend Jeff says that I should look at ubuntu-vm-builder. It will apparently make me an image. I sure would be glad to just download one someone made already though.

Ubuntu on a Mac Mini

I finally gave up on MacOS for a Mac mini server I have and wiped it and installed Ubuntu 14.04LTS. It mostly went pretty smoothly, Ubuntu makes bootable images for Mac hardware that work fine off of USB keys. And I just wiped the whole disk and removed any vestiges of the MacOS boot loader, I imagine it’s a bit trickier if you care to preserve MacOS.

The one real problem I ran into was the new system hung at boot right after adding swap. That error is a red herring though; really it’s hanging trying to change video modes. Dumb, particularly the lack of a useful console message. The solution is to add nomodeset to the kernel command line in GRUB.

Also a few minor problems. The WiFi adapter doesn’t work, of course, although maybe the non-free drivers I was advised I could install fix that. Ubuntu’s automagic partitioner doesn’t give you a way to resize the swap partition, you’re stuck with it being the size of system RAM. And it did enough other magic things on repartitioning I was afraid to try to roll my own.

I’m pretty unimpressed with how slow this Mini is, now that I have an OS I understand on it. The Plex server seems OK, and it can transcode 1080p video at 5x real time or better. But trying to rsync 300GB of files over gigabit ethernet to it basically pegged the machine; the poor SSH process with the network connection was using 50% CPU even after I told it to use arcfour encryption, supposedly the fastest available. And terminal responsiveness was like 10 seconds at a time, although maybe it’s partly the Linux scheduler to blame for that. Anyway the system has a i5-3210M CPU which apparently is pretty weak, despite having 2 honest cores in it. Will be fine for a file server but I’m glad I built a beefy compute server for real work.

What precisely is Linux load average?

I picked up some Unix wisdom years ago from a greybeard to ignore the Unix “load average”. It’s just not a very precise measure of how busy a system is. That was particularly true in the Ultrix 2.2 systems I first learned on. The stupid thing counted zombie processes for calculating the load, and zombies take essentially no resources.

You’re always better off looking more closely at contention for specific resources in your system: CPU, RAM, Disk IO, Network IO. But the load average is one handy little number, what does it mean? I’ll focus on the first number, the 1 minute average. (The time averages are weird exponential decay things, I don’t understand them.)

The official docs say load average is “the number of jobs in the run queue (state R) or waiting for disk I/O (state D)”. So it’s a measure of CPU and Disk contention. The kernel source has a remarkably clear comment, that it’s the number of CPUs that are either running or uninterruptible. That specifically implies it’s the number of CPUs actually tied up doing some CPU task. I don’t really understand uninterruptible in the kernel other than it happens when you wait for disk. Not really a measure of disk bandwidth as disk wait. I also think this description means that time spent in the kernel itself (sys) is counted towards the load average.

So load average is a good measure of whether your system doesn’t have enough CPUs to do the work at hand. Aiming to keep load_avg = num_cpus on a long term average should maximize CPU throughput.

However a lot of our real work is network-bound, either Internet downloads or local network waiting for something like a database to answer. So for many kinds of work we want to run more simultaneous jobs than num_cpus. But a job waiting on the network contributes close to 0 to load average, so the heuristic of aiming for load_avg = num_cpus is not a bad one.

It’s still useful to look more closely at detailed system resource usage metrics. htop and vmstat are great for inspecting memory usage. I like iftop for network. iostat is the traditional tool for disk IO.

I’m running an OpenAddresses run right now with 32 processes on an 8 CPU machine. There’s a lot of network waiting, but num_cpus * 4 is too much. Load Average has been about 20. In previous runs with 16 processes the load average has been about 8–10.

Some useful extra reading:

Monitoring CPU usage

Quick way to track how much CPU is being used on your system:

$ mpstat -P ALL 1 1
Linux 3.13.0-44-generic (ub) 	01/15/2015 	_x86_64_	(8 CPU)

04:23:47 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
04:23:48 PM  all   25.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   75.00
04:23:48 PM    0    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    1    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    2    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    3    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    4  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
04:23:48 PM    5  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
04:23:48 PM    6    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    7    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00

That’s a report with 2 processes spinning at 100% on an 8 CPU system. I usually use top and look at Munin graphs, but this is a bit more precise. Leave off the last “1” and it runs continuously, reporting once a second. Leave off both “1”s and it shows you the average since the system booted. Leave off the “-P ALL” and you get just the top line, an average over all CPUs.

New hard drive

I just bought a 2TB hard drive. I’m running low on disk space; a new 400GB of digitized 8mm video doesn’t help things. Picked up a Western Digital 2TB Black 7200RPM, WD2003FZEX.

My Linux server has two 1TB WD Blue drives in it which have been quite solid. But I’ve since learned Blue is the cheapo option. The Black drives are better and not much more expensive. There’s also Red (fancy firmware for RAID), Green (lower power, 5400RPM), and Purple (streaming video). According to this benchmark I should expect to get about 150 MB/s compared to 120 MB/s for the 1TB drives I have now.

Having seen the IO contention of my OpenAddresses work I’m tempted to try to set up the two 1TB drives in a RAID-0 stripe configuration. But that’s complicated and I’m deeply suspicious of RAID, so probably not. Historically I’ve bought drives in pairs and used rsnapshot to back up from one to the other, I’ve now broken that symmetry. Not sure what to do with the new one yet.

Hmmm, 256GB SSDs are only $120, that’d be a fun toy.

Update: new drive installed fine. With a brand new empty disk I’m getting writes of 189MB/s, which is sure nice. Gets slower on the inside of the disk I imagine. Modern components are relatively easy to plug in, but of course the power cables are all upside down so each one requires a 180° twist.

ssh root attacks

Just discovered my auth.log is spammed with folks trying to log in as root. Some 75% of the requests are coming from 103.41.124.0/24, which is about 20ms away from San Francisco and I’m guessing near Palo Alto. The whois record says it’s a firm in Hong Kong with the email address safestbusiness@gmail.com. Uh huh.

I tried installing fail2ban on Ubuntu 14.04 but it didn’t seem to work. The ugly thing works by scanning log files with scary Perl regexps, no way am I going to try to debug that. The whole premise of it makes me nervous too, I’d rather just ensure my services are secure. That’s adequate as long as you’re not worried about DOS-levels of traffic.

NFS: Ubuntu server, MacOS client

I’m finally fed up with Mavericks broken SMB implementation. It’s appalling how bad it is. For awhile I had it working by forcing SMB 1 via cifs:// share naming, but that stopped working. Suddenly SublimeText and TextEdit were creating files with mode 0764, god knows why. MacOS touch was creating 0644 as expected. Anyway, fed up, it’s broken, so I’m going back to NFS. (Apparently Yosemite is shipping a new SMB 3 stack, maybe that’s better? Yosemite is broken in so many other ways though...)

I used NFS 3 years ago and those notes still apply. However, some changes.

Ubuntu server: as simple as can be. The wrinkle is that unless you want to get all fancy with Kerberos or idmapd or something user IDs don’t get mapped. Last time I just changed my numeric IDs on my Mac to match the Linux server. This time I’m trying something new, this cheese in /etc/exports:

/home/nelson 192.168.0.0/24(rw,insecure,async,no_subtree_check,all_squash,anonuid=30193,anongid=30193)

I’m abusing NFS anonymous ID mapping to force all requests to look like user ID 30193 and group ID 30193, my personal IDs on my Ubuntu box. It looks wrong on the Mac client, and it’s not appropriate for a multiuser server. But it gets the basic job done.

Mac client: more confusing now. Mavericks removed the graphical NFS configuration tool that I used to use. However the default automounter setup is not so bad. The path /net/ub/home/nelson is magically the NFS share ub:/home/nelson and seems to automount usefully. I think it’s using NFSv3. Haven’t needed to tune any parameters yet.

It wasn’t my primary goal, but as a bonus I get better speed out of NFS. The SMB 1 implementation seemed limited to about 10 megabits / second when writing to the server. NFS is running at the full 100 megabit link speed.

kvm and Ubuntu snappy

I just launched my first Linux virtual machine ever, thanks to Ubuntu Snappy. Ubuntu 14.04 as the host and the stripped-down Snappy as the guest OS. The “locally with kvm” instructions worked fine except I had to add -nographic to the kvm command line to get it to launch headless.

The guest image has 512MB of RAM available, but the host qemu process has 940MB mapped. Wonder what that’s about? Presumably there’s ways to configure the resources availalbe on the guest machine.

I like the idea of Snappy, an Ubuntu distribution specially stripped down for VM guests, Docker, etc. I don’t know the market well enough to know if it’s competitive. I am much more inclined to use a guest OS if it feels like Ubuntu though. Confused about what snappy is doing as a package manager. apt-get is not enabled. dpkg is there and a bunch of stuff is installed, but I think you manage the Ubuntu core OS with snappy.

The guest reboots in about 11 seconds.

disk speed

2TB USB drives are now under $100. Which is awesome! But boy that’s a lot of disk to write. How long does it take?

Sadly my iMac is USB 2.0 only. In practice that gets about 21 MBytes/second with the disk. At that speed it takes about 27 hours to read or write all 2TB.

My Linux box has USB3 ports, so the data interface is no longer the limiting factor. In practice I’m getting about 110 MBytes/second, at least at the start of the disk. That’s 5 hours and is presumably gated by how fast the bits are spinning by the read head. Update: took nearly 7 hours, aggregate speed was about 82 MB/s.

(Side note:  how do you know you have a USB 3 connection? The plastic inside the port is colored blue, that’s the first tip-off. On Linux you can also inspect the interface speed with “lsusb -t”; 5000M means USB 3. Details on Stack Exchange.)

I’m not finding a reliable source for theoretical throughput on a 5400 RPM spinning platter. Numbers I’ve seen are in the realm of 50–150 MBytes/second. I’d forgotten it depends on the density of the disk. The little 2.5″ disks I prefer should be faster than bigger 3.5″ disks, all things being equal.

There are a few 7200 RPM 2.5″ portable drives out there now, but they’re unusual enough that they are expensive and I don’t fully trust them. Naively, at best that’s a 33% speedup for bulk throughput, not a huge difference. Faster seek times though.

Calistore 0.8 quickstart (Ubuntu) and thoughts

I’ve been curious about Camlistore for awhile, a project from a lot of smart people like Brad Fitzpatrick and Aaron Boodman and the like. It’s a content addressable filestore “for life”, a sort of Dropbox / Lifestreams kind of thing for storing all your personal data. Ambitious and necessary. My immediate use case is as a replacement for the horrible Unison and rsync tricks I do with a USB drive to keep two Macs sort of in sync.

They’re up at 0.8 now and have fewer dire warnings about how it’s not ready for users yet. I just asked Brad F and he said “I’d wait a bit for 0.9.”, which I good-naturedly take to mean “sure 0.8 is worth looking at” :-) Quick start on getting it going in Ubuntu, based on the Camlistore docs

  1. Install the Go Language. Don’t bother looking for an APT repository, the official one is out of date and the third party PPAs are all abandoned. Just install straight from the golang site.
  2. Download and build Camlistore from the github repo
  3. Run the camlistore daemon. It should advise there’s a UI on http://localhost:3179/ui/
  4. I had a problem with the UI requiring a basic auth HTTP login; maybe the “allow localhost” stuff was fooled by my ssh port forwarding. So I edited ~/.config/camlistore/server-config.json to add a username and password

I also watched Brad’s video from Feb 2014 to FOSDEM. Nice overview and some demos.

The main takeaway is the way Camlistore works is a blob server + a metadata indexing system. The blob server is a simple content addressable file system, keeps track of syncing raw data whose only name is the SHA1 hash of the data. Then there’s other metadata blobs which contain things like “blob with SHA1 f392... is actually IMG_0902.jpg, a 3000x2000 JPEG with this creation data”. The problem with content addressable file systems is that the moment you change the file it’s basically a brand new file. They have a concept of “permanode” that provides permanent identity for things independent of their content. It sounds like a lot of work is put into the indexer system to make it a usable filesystem.

Speaking of usable, the main UI they show off is a Web UI. Fancy real time updating searches. Demo was managing a bag of phonecam images. There’s also a FUSE filesystem that in the demo seemed very slow because it was syncing to a remote server. (Slow, like “touch foo” took 5+ seconds.) Not sure if there’s a faster way to sync to a local server, then have it sync those updates to the remote server. Seems like you’d have a consistency problem for the metadata on permanodes. Maybe they rely on timestamps to sort out a merge?

There was also a quick demo of “thirdleg”, a sync from one store to another through a third thing, like a portable drive you’d carry from A to B. That’s exactly what I need for my use-case above, but I’m not sure if I’d want to rely on FUSE to be my filesystem for actually using my synced files.

My main takeaway is that they have a pretty good take at a low level distributed data store suitable as a sort of synced remote filesystem. I was a little less convinced about the applications demoed, like that Camlistore will end up being most useful as an underlying layer for something and we haven’t quite seen the apps that use it yet. For near term usefulness the key thing is probably how responsive that FUSE file system is. Need to try it out.

ubuntu 14.04, udev, ethernet

After 10 years of fiddling with remote servers, I finally killed one so I couldn’t access it on reboot. The system came up fine but not the network. The nice remote admin logged in and found that the Ethernet device was now named /dev/p4p1 and the config files were expecting /dev/eth0. He updated the config and it works, for now. I’m scared to reboot again since I don’t understand what caused it to change in the first place.

tl;dr: installing biosdevname causes devices to be renamed at boot.

Summary: I installed biosdevname and I think that caused my ethernet device to get a different name after reboot. A fresh Ubuntu 14.04 system uses biosdevname to give Ethernet devices names like /dev/p4p1. These names are based on the physical location of the adapter on the PCI bus. An old Ubuntu system upgraded to 14.04 may not install biosdevname and instead use older working names like /dev/eth0 that are configured by MAC address in /etc/udev/rules.d/70-persistent-net.rules.

Some detailed notes on what may have broken it:

  • The system started as Ubuntu 10.10, I did two do-release-upgrades to bring it to 14.04. After installing 14.04 it booted correctly at least once, configured as /dev/eth0 for ethernet. Now it wants /dev/p4p1
  • After the working boot I installed a few packages that I regret installing. Specifically biosdevname libsystemd-daemon0 systemd-shim systemd-services discover linux-image-3.13.0-36-generic.
  • I removed the 3-13.0-36 kernel and then had to do some awkward stuff to fix grub to use the linux-image-3.13.0-37-generic I already had. I think I got that right.
  • I don’t think the systemd packages would cause any problems, but I don’t know for sure. I don’t think I’m running systemd as a whole.
  • I’m not sure what discover does. My hope is it’s an install-time thing only.
  • biosdevname’s whole job is to give names to devices, so it seems a likely troublemaker. One theory is that the mere presence of it being installed alters the boot methods of Ubuntu in some way. But that’s a total guess. This forum post gives some credence to things.
  • /proc/cmdline says
    BOOT_IMAGE=/vmlinuz-3.13.0-37-generic root=UUID=e7833d2a-17a4-4598-95e2-65d354589db9 ro quiet splash

Some notes on how it’s supposed to work:

  • /etc/udev/rules.d/70-persistent-net.rules is supposed to give a persistent name to the device. Mine seems to be saying “call this eth0”. That may be a legacy from the 10.10 or 12.04 history of the system, and was apparently working until yesterday
  • I have another system that began life as ubuntu 14.04. Its ethernet is /dev/p2p1. It has no files in /etc/udev/rules.d
  • My system appears to be booting with Upstart, not systemd. (PID 1 is init, not systemd). Details on systemd and Ubuntu
  • These Arch Linux notes on the upgrade to the new persistent naming scheme are interesting. Also these systemd docs. But since I’m not using systemd, they are probably not relevant.
  • This GenToo doc on udev upgrades is also useful.
  • Here’s an Ubuntu bug saying the 14.04 docs have not been updated to reflect that 70-persistent-net.rules is no longer used. Also here
  • biosdevname installs /lib/udev/rules.d/71-biosdevname.rules which may override that 70-persistent-net.rules thing.
  • Apparently the kernel has a command line parameter biosdevname=0 to disable renaming. (net.ifnames=0 in Fedora). 71-biosdevname.rules also can be edited to do that.

After 2+ hours of reading I convinced myself it was safe to reboot. It was! I removed the /etc/udev/rules.d/70-persistent-net.rules file that was effectively being ignored after biosdevname was installed.

I filed a bug: https://bugs.launchpad.net/ubuntu/+source/biosdevname/+bug/1382600

Related: bless Arch Linux. I’ve never run it, but their incredibly detailed Wiki documentation on how Linux systems work is so useful. Sometimes you have to go to the low level tools manufacturers to understand how something works.

Notes on setting up a new Ubuntu 14.04 box

I’ve now recovered from my server hardware failure on Saturday. I can’t say enough good things about my remote rsnapshot setup. I’d kind of forgotten that backup even was running and it totally saved my ass. The hard drive had failed, the system wouldn’t reboot, would have been a nightmare getting it back. And while I don’t have any essential data on the remote server I do have a bunch of logsoflag logs I’d hate to have lost. Not to mention the server setup at all.

I ordered a new machine and set up Ubuntu 14.04 on it. I have no automation for building these servers, the overhead is hard. Couldn’t even easily import crap over from my backup of the Ubuntu 12.04 box, too much has changed like the shift to Apache 2.4.

Here’s a dump of the journal I kept as I set up the new server, the steps I took. Nowhere near complete.

Change root password and reboot
Set hostname, reboot
Edit /etc/network/interfaces to use Google DNS. “ifdown p2p1; ifup p2p1” and hold breath.
Edit /etc/default/rcS to set FSCKFIX=yes
Partition the extra disk, make file system, add to fstab
Create user nelson, add nelson to sudoers, also to group sudo.
Restore /home files from backup, put /home/nelson in order

Install unattended-upgrades
Install mg git gcc make munin nmap rtorrent screen mtr traceroute zip unzip curl optipng graphicsmagick gawk libimage-size-perl ntp
Install munin munin-node sensors
Install postfix bsd-mailx

Set up remote rsnapshot

Install apache2
enable a lot of mods
reconfigure deflate to not be stupid

http://nelsonslog.wordpress.com/2011/03/13/gzip-encoding-chrome-dev-tools-bug/

apache2 2.4 auth changes http://httpd.apache.org/docs/2.4/upgrading.html
set up backups

Set up web sites

Restore /var/www/* from backups
Reinstall sites in /etc/sites-available/* and enable
/etc/logrotate.d/apache2

Restore user contrabs from /var/spool/cron

Some notes from old setups:

http://nelsonslog.wordpress.com/2012/01/07/ubuntu-server-notes-from-an-old-debian-user/

http://www.somebits.com/weblog/tech/blosxom/server-migration.html

Apache 2.4 security stuff

My new server setup has mostly gone well, but I got tripped up by an error
authz_core client denied by server configuration

Turns out this is a change made between Apache 2.2 and 2.4. It’s reasonably well documented by Apache itself and this Stack Overflow post goes into more detail.

Long story short, for directories outside /var/www where I had some stuff stashed to load (namely CGI scripts), I had to Require all granted in Directory blocks for those oddball directories. I guess Apache moved to a “not allowed by default” model, which makes a lot of sense from a safety point of view.

Note that Munin in Ubuntu 14.04 has Apache 2.2 style config files, despite Apache 2.4 now being the default Ubuntu server. They have a bug tracking this.

Apache optimization still too hard

Setting up my new server, I’m struck by a few things.

  • Ubuntu doesn’t install mod_deflate at all by default
  • The default mod_deflate configuration is very conservative, effectively only compressing HTML. I replace it with a config which says “compress everything but GIF, JPG, MP3, that kind of thing”. Apparently it breaks IE6 or something to compress Javascript or JSON or the like. Who gives a shit?
  • I have no idea what, if any caching Ubuntu HTTPD does by default
  • I don’t even know how to test it any more. Chrome’s developer tool audit suggests stuff is being marked cacheable for 3600 seconds, which it complaints is “too short” but actually as default policies go, isn’t terrible

Hitting reload or Cmd-R on http://logsoflag.com/#8guI7GZ2OhU causes Chrome to reload everything. Hitting return in the location bar or pasting it in causes Chrome to load most things from cache, only loading the page itself and the JSON blob in the AJAX from cache. I don’t know if Chrome is being strictly standards-compliant or is a bit extra aggressive in trying to load things from cache.

I feel like I used to understand HTTP caching a lot better, but it’s been a couple of years since I looked closely at what was being cached and how. I also seem to remember there were more tools online that would load a page and give you advice on how to better optimize performance. Like there used to be a server hosted variant of YSlow, right? All I know to use now is Chrome’s developer tools in the browser.

Services I host, setting up a new server

I have a server in a datacenter in Kansas. Or rather, did: the hardware went boom. Fortunately I have backups, unfortunately I have to set up again a bunch of hand-crafted services and crap I put there. I greatly simplified things when I set this server up, back in March 2012, but I still have to install and tweak a bunch of stuff by hand.I think all the services I run publicly come via port 80 and Apache. Best as I can tell here’s what I care about:

  • logsoflag.com: Apache virtual host with some CGI writing to local directories.
  • windhistory.com: Apache virtual host, nothing but static files.
  • somebits weblog: Blosxom CGI
  • somebits web server: random stuff, mostly (all?) static files.
  • rivers map: nginx, Tilestache, GUnicorn, Postgres, oh god so many things.

It may be a few days before the replacement is online. I’m trying to move logsoflag and windhistory to my home DSL system as a stopgap for the weekend. I’ll wait for the new server to set up the somebits blog, etc. I may not bother with the river and airport maps at all. They’re neat, and somewhat easy to get running again, but it’s a lot of extra servers to manage for not a lot of benefit.

I sure wish system automation tools were better; I’d love to script all this setup so I can migrate more easily. But Chef, Puppet, and Docker are all a fair amount of work to set up. The other option is a virtual image snapshot I can just clone, either a Linux VM based thing or Vagrant or something. But that’s wonky. It would not be inappropriate for the river project though.

Update: I’ve gotten two recommendations for Ansible as a lightweight system configuration tool. It looks basically like a sane wrapper around scripts that ssh to a machine and install packages, copy files, etc. YAML declarative “playbooks” define how to set up services. (Very simple example of running it.). I’d definitely look to use this if I were setting up machines regularly. May not bother for one single system.

I managed to get all the web stuff except the river map working on my home server on cable modem. It only took a couple of hours. So maybe I don’t need to sweat over the server setup too much. I’ve got the Apache virtual host stuff configured well enough now that it’s pretty painless.

netconsole

I have a headless Linux box and every time I reboot it there’s a several minute anxiety where I don’t know if it’s working or not. (I reboot only every year or so, I think fsck’s timer kicks in and it takes awhile.)

I want to see the console while its booting, without a monitor. I don’t want to fuss with serial cables. Netconsole looks like an option; kernel module that sends UDP log messages via a pre-arranged MAC address. Before the TCP/IP stack is initialized. Docs: Ubuntu, Arch, kernel.

SMART errors: living dangerously

My once-yearly look through root’s mail on my home server reveals errors from smartd

Device: /dev/sdb [SAT], 17 Offline uncorrectable sectors
Device: /dev/sdb [SAT], 17 Currently unreadable (pending) sectors

The error started 14 May 2014 10:57:07 +0000 at 5 errors, then jumped to 17 two hours later and has stayed at 17. It’s just a backup disk, so I’m going to live dangerously and see what happens. The disk is 2.5 years old and has a three year warranty.

Possibly related, rsnapshot hasn’t run cleanly in weeks and I didn’t notice because errors go to a local mail spool I never check. I should rethink that.

 

Unison is slow

I like Unison for synchronizing files, but it is slow. I finally have a little insight into why; it’s calculating fingerprints for file contents. rsync seldom cares about file contents, it generally gets by with just metadata like file size and mtime. Unison’s approach seems to be fingerprint every file. At least it caches the fingerprints, it used to not!

The problem is the fingerprint algorithm is slow, slow, slow. Like it takes many seconds to fingerprint a 2 gigabyte file. I can’t find a paper that describes the algorithm and my OCaml is rusty, but the code makes mention of MD5 and the paper references “cryptographic checksum”. Using crypto hashes as generic hashes used to be a fad, I’m guilty of it myself, but unless you’re worried about cryptographic adversaries it’s always better to use a fast CRC or the like instead of a crypto hash. Crypto hashes are slow.

While I’m complaining I can’t help but think being written in OCaml is part of why Unison doesn’t get more attention and development now. Not many folks know ML, you know? It also doesn’t help with the speed. I can’t tell if there’s an ML version of whatever fingerprint hash it’s calculating or if it’s using a native optimized library. Also the whole thing is single threaded, which for an app doing slow CPU work on many independent files is a mess. OCaml apparently doesn’t support concurrency :-(

It’s 2013 and remote filesystems still suck

About once a month my AFS mounted file systems fail on my Mac. This is from one Mac to another, both running 10.8

[nelson:~] $ mount
/dev/disk2 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)
//media@gvmini/media on /Volumes/media (afpfs, nodev, nosuid, mounted by nelson)
[nelson:~] $ sudo bash
Password:
[root:~] # umount /Volumes/media
^C^Z^C^Z^C^C^C^C^C^C^Z^C^C

Every process that’s touched that filesystem is marked uninterruptible. There’s a -f flag for forcing umount but it doesn’t work either, just hangs.

Hilariously, the man page for umount on the Mac says “Due to the complex and interwoven nature of Mac OS X, umount may fail often. It is recommended that diskutil(1) (as in, ``diskutil unmount /mnt’‘) be used instead.” No, diskutil unmount doesn’t work either, even with a force.

At least the Finder doesn’t hang when you click the little eject arrow.

Update: naturally you can’t shut the machine down in this state either. Power switch for you!

Small boot partition considered harmful

df-year

 

Ubuntu happily installs new kernels automatically into /boot. It never prunes them automatically though. So every few months I have to notice /boot is nearly full and clean it up. There are theoretical arguments why having a separate small boot partition is a good idea, but here’s a practical reason it isn’t.

 

Cloning a gist via ssh

For some reason GitHub really wants you to clone gists via https. But I’m all set up with ssh keys and would prefer to check out that way. Here’s how:

git clone git@github.com:5624141.git

Replace the number with your gist id, of course. Your username is not part of the URL.

nginx proxy buffering

It took a lot of head scratching, but I think I figured out nginx and how to configure buffering of proxies. Long story short, here’s where I ended up:

location /rivers {
  proxy_pass http://localhost:8000;
  proxy_buffering on;
  proxy_buffers 32 16k;
}

If I did that right, it means “proxy to this other HTTP server and buffer 512kb of data from it”. The default configuration is to buffer only 32k, which in the modern world seems awfully small. But nginx allocates this memory per request, so if I were expecting a lot of requests that would be a bad idea. nginx will also buffer to disk if it runs out of memory buffer, up to 1G or so, but I wanted to avoid that. Note that nginx is buffering uncompressed data.

With this setup I can have 9 clients slowly loading the big tile 4/3/6.json even though I only have four Gunicorn workers. And I verified via sudo inotifywait -m -r /var/lib/nginx/ that it wasn’t using the file cache. Good enough for me.

Here’s a quicky slow client I used to test the buffering:

#!/usr/bin/env python

import socket, time, sys

req = [
'GET /rivers/4/3/6.json HTTP/1.1',
'Host: www.somebits.com',
'Accept-Encoding: gzip',
'Connection: close',
'', '']
readSize = 1600

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('somebits.com', 8001))
s.sendall('\r\n'.join(req))
l = 0
while True:
    time.sleep(1)
    d = s.recv(readSize)
    l += len(d)
    if len(d) == 0:
        break
    sys.stdout.write("%s" % "*" if len(d) == readSize else ".")

s.close()
print '\nReceived', l, "bytes"

faking out remote syslog via netcat

Here’s how to create UDP syslog messages via nc, netcat:

echo ‘<14>sourcehost message text’ | nc -v -u -w 0 localhost 514

Replace localhost with the syslog server, of course. “sourcehost” is a string identifying the source; can be anything. The 14 is a combination of the severity (low 3 bits) and the service (high N bits). 14 = 8 + 6 which means “user message, informational”. RFC 3164 has the relevant detail. The syslog protocol is remarkably ad hoc; you can leave out the priority and it should still work. And there’s a provision for adding timestamps to the source message too. Note that syslog may suppress duplicate messages, so that may be why subsequent tests don’t show up. Unfortunately the BusyBox version of nc bundled in to Tomato doesn’t have the -u flag.

I’m doing all this to try to debug Apple’s disastrous syslog server. It has some insane binary config file to enable remote logging, and then they couldn’t leave well enough alone with syslog so they had to rewrite the whole thing with aslmanager, a daemon so awesome that most of the Google search results for it are “why is this process taking 99% of my CPU?”. It is open source at least. Anyway, asl.conf has its own different format. And then it doesn’t fix the #1 problem with syslog, which is there’s no way to log the IP address of the originator of the message. Argh!

This annoyance may be the last straw for me trying to use MacOS as a Unix server. There’s just no good reason to leave the warm embrace of Linux / Ubuntu. A quick look suggests Ubuntu 12.04 will work fine on a late 2012 Mac Mini, albeit with some required hackery for the ethernet driver.

Copying a giant file with resume on error

General rule: any computer task that takes more than an hour must be done in a way that allows resuming if aborted. So, how to copy a giant file?

rsync --partial --append --progress --bwlimit=300\
nelson@wi:~/nobackup/geodata/planet-130327.osm.pbf .

Both the --partial and --append are necessary; the --partial tells rsync not to delete when aborted, and --append tells it to pick up where it left off the next time. There’s more subtle options available too.

Raspberry Pi notes

Raffi gave me a Raspberry Pi, the $35 ARM based Linux system. Capable little beast: 256MB RAM, 700MHz ARM processor, a GPU that can drive 1080p and decode video, it’s an interesting device. Some notes:

Hardware

Batteries not included. In addition to the board itself, I needed:

Hilariously the whole machine reboots when I plug in the WiFi adapter; my guess is a power problem. It boots fine once it’s plugged in though.

RAM is shared with the GPU. The split is (now) configurable, so I have 192MB system RAM and 64MB GPU RAM. Newer boards have 512MB on board.

Software

The primary software distribution people use is Raspbian, a giant 1.5 gig full Debian system. It’s cool that you get a full normal Unix system but boy are we a long way from an embedded OS. The architecture is “armhf” with a change, using hardware floating point in the ABI. Apparently there’s several incompatible Debian ARM versions running around; armel, armhf (soft float), armhf (hard float), etc.

There is no BIOS on the board and no LILO or GRUB bootloader has been ported to the Pi yet. The bootstrap expects a FAT filesystem that it can execute a kernel off of. Raspbian has a small FAT partition with a kernel and then a big ext4 partition for the rest. There is an effort for a bootloader called Berryboot but it boots off of SquashFS filesystems which AFAIK are read only. Haven’t tried it.

Raspbian out of the box works well. Username: pi, password: raspberry. You’ll want to use rsapi-config to set the keyboard if you have a US keyboard.

The main thing I had to do was set up wifi, which uses wpa_supplicant. I found this example config file helpful. End of the day, all I needed to do to get wifi working was add the following little block to /etc/wpa_supplicant/wpa_supplicant.conf. (Note, both my SSID and password are wrapped in quotes for the config file.)

network={
  ssid="mySsid"
  psk="my password in quotes"
}

Voila! With all that set up I now have a working underpowered Linux box. So what is this thing actually good for? To me what’s most exciting is the HDMI output; it can drive a TV! To that end I found two possible end uses. OpenELEC, for viewing videos via XBMC. Or MAME/MESS for playing games.

MAME

So what about MAME? My first try was PiMAME 0.3, a full distribution that boots right into AdvanceMAME for a chooser. Looking at it, it’s basically Raspbian with some extra software installed and a login script to launch MAME. (An annoying one, I might add; it’s awkward to get a shell and virtual consoles don’t seem to work). Also the setup isn’t usable with just a USB joystick now, you really need a keyboard to drive both AdvanceMENU and AdvanceMAME itself. Full props to the PiMAME author for working on a convenient turnkey distro, but it’s not there yet. I think I’d rather use a plain Raspbian distribution and build up my own MAME environment, using his packages.

So how to install by hand? I followed notes from this blog post, skipping over the “how to use Unix” parts and getting right to MAME. In a nutshell:

  • Install the AdvanceMAME .deb by hand, downloading from http://sheasilverman.com/rpi/raspbian/debs/
  • Create a MAME user strictly for running MAME. Put it in group video
  • Launch “mame mspacman” from a local console to play a totally legitimately acquired copy of the Ms. Pac-Man ROM.

It works! It’s very slow compared to PiMAME 0.3; I imagine I’m running into the same problem the PiMAME guy is having with the most recent raspbian distributions. Also I haven’t tried sound yet. And AdvanceMAME is some 7 years old; in theory the mainline MAME 0.147 should work on Raspberry Pi but the details of getting SDL and Sound working in this environment are rumored to be difficult.

Thoughts

The Raspberry Pi is an impressive little device. For the size, power (3W), and price it’s amazing to have a full real Unix distribution. I’m not sure what it’s actually for though. Its creators talk about education, about giving kids an affordable hackable platform. I think that’s awesome but is this really it? Maybe so, but I’d think a discarded PC would be just as good. Or something with a portable screen and input method.

As a general purpose hack thing it’s a lot of fun. What’s missing though is some sort of hardware bridge, say Arduinio.

As an embedded device it’s impressively capable. It’s nice to imagine building a whole Internet TV device on it, for instance, with a full real Unix behind it and not having to fart around with an embedded OS or iOS or something. I’m sure there’s drawbacks, but..

I’m trying to get my head around having a full Debian system on this. I’ve been conditioned to think of embedded devices as black boxes; you flash the firmware every six months and then run what’s there, no upgrading or changing. Raspbian feels more like a persistent OS to me, something I’m going to add and upgrade and change rather than wipe and start over regularly.

File corruption on my web server

Got a bug report for windhistory.com that I traced back to the main JSON database I’m serving being corrupted. The file hasn’t been touched since September 2011 and I know it was working correctly as of December 1. Needless to say this is very disturbing. Files shouldn’t go bad like this. The pattern of corruption doesn’t suggest malice, just a bug. It makes me wonder what else is corrupted. None of the other datafiles for that project have changed but I can’t easily audit the entire system.

My backups didn’t capture the corruption. But I got clever and realized I could pinpoint when the file changed by looking at the compressed size that Apache was serving; even though the file itself wasn’t truncated, the data changed so the compressed size changed too. It’s typically 369275 or 369276 bytes (why the inconsistency?) but starting at 11/Dec/2012 18:25:58 (UTC) the length 370464 or 370465 started showing up. At first it was really inconsistent, it didn’t stabilize on this new length until 12/Dec/2012 01:05:25.

Nothing obvious in the syslog around that time. Munin graphs show some other weirdness; Munin processing time went up to timeout levels for awhile, HTTP loadtime stopped being reported, NTP briefly went from a 40ms delay to a 90ms delay from true time. A disturbance in the force. But no temperature or voltage spikes, no heavy load, nothing major.

I flushed my filesystem caches via echo 3 >| /proc/sys/vm/drop_caches and now the file is correct. So at least the disk didn’t get corrupted, just the cached copy in memory. Still disturbing, this is way more than a single cosmic ray bit flip. But it does look like a systemic modification of the old bits, not completely overwritten with  new ones. Very weird.

Here’s the output of cmp -b -l; index, then good data on the left, corrupted data on the right. There’s some mild pattern to it, it looks in general like bits are being flipped to 0. But not entirely. And why is the corruption scattered around the file? Very weird.

 188486  71 9     41 !
 188494  54 ,     44 $
 188502  63 3     41 !
 188510  54 ,     44 $
 188518 135 ]      5 ^E
 188526  62 2     40
 188534  54 ,     44 $
 188542  62 2     40
 188614 133 [      1 ^A
 188622  62 2     40
 188630  62 2     40
 188638  54 ,     44 $
 188646 133 [      1 ^A
 188654  61 1     41 !
 188662  54 ,     44 $
 188670  60 0     40
 188742  61 1     41 !
 188750  54 ,     44 $
 188758  61 1     41 !
 188766  54 ,     44 $
 188774  54 ,    144 d
 188782  60 0     40
 188790  64 4     44 $
 188798 135 ]      5 ^E
 188870  54 ,     44 $
 188878  54 ,     44 $
 188886  63 3     41 !
 188894  63 3     41 !
 188902  62 2     40
 188910  54 ,     44 $
 188926  63 3     41 !
 188998  54 ,     44 $
 189006  54 ,     44 $
 189014  65 5     45 %
 189022  60 0     40
 189030  66 6     44 $
 189038  70 8     40
 189046  54 ,     44 $
 189054  71 9     41 !
 189126  54 ,     44 $
 189134  54 ,     44 $
 189142  63 3     41 !
 189150  63 3     41 !
 189158  61 1     41 !
 189166  62 2     40
 189174  54 ,     44 $
 189182  54 ,     44 $
 189254  66 6     44 $
 189262 120 P      0 ^@
 189270 122 R      0 ^@
 189278 105 E      5 ^E
 189286 122 R      0 ^@
 189294  60 0     40
 189302  66 6    144 d
 189310  61 1     41 !
 189382  54 ,     44 $
 189390  54 ,     44 $
 189398  54 ,     44 $
 189406  54 ,     44 $
 189414  54 ,     44 $
 189422  54 ,     44 $
 189430  54 ,     44 $
 189438  63 3     41 !
 189510  64 4     44 $
 189518  54 ,     44 $
 189526  61 1     41 !
 189534  66 6     44 $
 189542  54 ,     44 $
 189550  54 ,     44 $
 189558  54 ,     44 $
 189566  63 3     41 !
 189638  54 ,     44 $
 189646  54 ,     44 $
 189654  54 ,     44 $
 189662  54 ,     44 $
 189670  54 ,     44 $
 189678 113 K      1 ^A
 189686  61 1     41 !
 189694  54 ,     44 $
 189766  71 9     41 !
 189774  63 3     41 !
 189782  54 ,     44 $
 189790  54 ,     44 $
 189798  66 6     44 $
 189806  64 4     44 $
 189814  61 1     41 !
 189822  54 ,     44 $
 189894  70 8     40
 189902  67 7     45 %
 189910  61 1     41 !
 189918  54 ,     44 $
 189926  54 ,     44 $
 189934  54 ,     44 $
 189942  67 7     45 %
 189950  64 4     44 $
 190022  63 3     41 !
 190030  61 1     41 !
 190038  67 7     45 %
 190046  60 0     40
 190054  62 2     40
 190062  61 1     41 !
 190070  54 ,     44 $
 190078  54 ,     44 $
 190150 117 O      5 ^E
 190158 125 U      5 ^E
 190166 101 A      1 ^A
 190174  54 ,     44 $
 190182  60 0     40
 190190  54 ,     44 $
 190198  63 3     41 !
 190206  54 ,     44 $
 190278  64 4     44 $
 190286  63 3     41 !
 190294  66 6     44 $
 190302  54 ,     44 $
 190310  54 ,     44 $
 190318  54 ,     44 $
 190326 135 ]      5 ^E
 190334  62 2     40
 190406  60 0     40
 190414  62 2     40
 190422  64 4     44 $
 190430  54 ,     44 $
 190438  54 ,     44 $
 190446  61 1     41 !
 190454  67 7     45 %
 190462  64 4     44 $
 190534  63 3     41 !
 190542 135 ]      5 ^E
 190550  42 "     40
 190558  65 5     45 %
 190566  67 7     45 %
 190574 141 a     41 !
 190582 145 e     45 %
 190590  54 ,     44 $
 190662  54 ,     44 $
 190670  54 ,     44 $
 190678  65 5     45 %
 190686 133 [      1 ^A
 190694  61 1     41 !
 190702  61 1     41 !
 190710  64 4     44 $
 190718  63 3     41 !
 190790  63 3     41 !
 190798  54 ,     44 $
 190806 135 ]      5 ^E
 190814  54 ,     44 $
 190822  54 ,     44 $
 190830  64 4     44 $
 190838  54 ,     44 $
 190846  61 1     41 !
 190918  67 7     45 %
 190926  67 7     45 %
 190934  54 ,     44 $
 190942  54 ,     44 $
 190950  54 ,     44 $
 190958 135 ]      5 ^E
 190966  42 "     40
 190974  65 5     45 %
 191046  60 0     40
 191054  60 0     40
 191062  60 0     40
 191070  60 0     40
 191078  60 0     40
 191086  60 0     40
 191094  60 0     40
 191102  60 0     40
 191174  54 ,     44 $
 191182  54 ,     44 $
 191190  54 ,     44 $
 191198  63 3     41 !
 191206  54 ,     44 $
 191214  54 ,     44 $
 191222  54 ,     44 $
 191230  64 4     44 $
 191302  61 1     41 !
 191310  61 1     41 !
 191318  54 ,     44 $
 191326  62 2     40
 191334  54 ,     44 $
 191342  54 ,     44 $
 191350  54 ,     44 $
 191358  62 2     40
 191430 101 A      1 ^A
 191438  42 "     40
 191446  64 4     44 $
 191454  61 1     41 !
 191462  65 5     45 %
 191470 135 ]      5 ^E
 191478  54 ,     44 $
 191486  54 ,     44 $
 191558  61 1     41 !
 191566  61 1     41 !
 191574  54 ,     44 $
 191582  70 8     40
 191590  67 7     45 %
 191598  54 ,     44 $
 191606  54 ,     44 $
 191614  54 ,     44 $
 191686  54 ,     44 $
 191694  54 ,     44 $
 191702  60 0     40
 191710  70 8     40
 191718  61 1     41 !
 191726  54 ,     44 $
 191734  70 8     40
 191742  66 6     44 $
 191814 130 X      0 ^@
 191822  71 9     41 !
 191830  64 4     44 $
 191838 117 O      5 ^E
 191846 111 I      1 ^A
 191854 133 [      1 ^A
 191862  62 2     40
 191870  63 3     41 !
 191942  61 1     41 !
 191950 135 ]      5 ^E
 191958  71 9     41 !
 191966  63 3     41 !
 191974  54 ,     44 $
 191982  54 ,     44 $
 191990  54 ,     44 $
 191998  54 ,     44 $
 192070  61 1     41 !
 192078 133 [      1 ^A
 192086  61 1     41 !
 192094  62 2     40
 192102  60 0     40
 192110  63 3     41 !
 192118  54 ,     44 $
 192126  54 ,     44 $
 192198  61 1     41 !
 192206  62 2     40
 192214  54 ,     44 $
 192222  54 ,     44 $
 192230  71 9     41 !
 192238  54 ,     44 $
 192246 133 [      1 ^A
 192254  64 4     44 $
 192326  54 ,     44 $
 192334  54 ,     44 $
 192342  64 4     44 $
 192350  54 ,     44 $
 192358  61 1     41 !
 192366 135 ]      5 ^E
 192374  54 ,     44 $
 192382  60 0     40
 192454  54 ,     44 $
 192462 133 [      1 ^A
 192470  60 0     40
 192478  71 9     41 !
 192486  62 2     40
 192494  62 2     40
 192502  54 ,     44 $
 192510  54 ,     44 $
 356422  54 ,     44 $
 356430  61 1     43 #
 356438  54 ,     44 $
 356446  54 ,    144 d
 356454  60 0     40
 356462  71 9    141 a
 356470  54 ,     44 $
 356478  54 ,     44 $
 356550  54 ,     44 $
 356558 135 ]      5 ^E
 356566  61 1     41 !
 356574  61 1     41 !
 356582  54 ,     44 $
 356590 133 [      3 ^C
 356598  61 1     41 !
 356606  54 ,     44 $
 356678 135 ]      5 ^E
 356686  61 1     41 !
 356694  61 1     41 !
 356702  54 ,     44 $
 356710 133 [      1 ^A
 356718  60 0     40
 356726  54 ,     44 $
 356734  54 ,     44 $
 356806  54 ,     44 $
 356814  54 ,     44 $
 356822  62 2     40
 356830  54 ,     44 $
 356838  54 ,     44 $
 356846  64 4     44 $
 356854  64 4     44 $
 356862  65 5     45 %
 356934 105 E      5 ^E
 356942 116 N      4 ^D
 356958  54 ,     44 $
 356966  54 ,     44 $
 356974  54 ,     44 $
 356982  54 ,     44 $
 356990  54 ,     44 $
 357062  54 ,     44 $
 357070  54 ,     44 $
 357078 133 [      1 ^A
 357086  64 4     44 $
 357094  61 1     41 !
 357102  54 ,     44 $
 357110  54 ,     44 $
 357118  54 ,     44 $
 357190  66 6     44 $
 357198  61 1     41 !
 357206 135 ]      5 ^E
 357214  65 5     45 %
 357222  66 6     44 $
 357230  61 1     41 !
 357238 135 ]      5 ^E
 357246  63 3     41 !
 357318  54 ,     44 $
 357326  63 3     41 !
 357334 135 ]      5 ^E
 357342 117 O      5 ^E
 357350  60 0     40
 357358  64 4     44 $
 357366 105 E      5 ^E
 357374 114 L      4 ^D
 357446  54 ,     44 $
 357454 135 ]      5 ^E
 357462  66 6     44 $
 357470  61 1     41 !
 357478  54 ,     44 $
 357486 133 [      1 ^A
 357494  64 4     44 $
 357502  54 ,     44 $
 357574  64 4     44 $
 357582  54 ,     44 $
 357590  54 ,     44 $
 357598  54 ,     44 $
 357606  54 ,     44 $
 357614  70 8     40
 357622  65 5     45 %
 357630  54 ,     44 $
 357702  54 ,     44 $
 357710  54 ,     44 $
 357718  63 3     41 !
 357726  70 8     40
 357734  54 ,     44 $
 357742  62 2     40
 357750  54 ,     44 $
 357758  60 0     40
 357830  67 7     45 %
 357838  62 2     40
 357846  54 ,     44 $
 357854  71 9     41 !
 357862  65 5     45 %
 357870  61 1     41 !
 357878  63 3     41 !
 357886  54 ,     44 $
 357958  54 ,     44 $
 357966 135 ]      5 ^E
 357974  62 2     40
 357982  62 2     40
 357990  63 3     41 !
 357998  67 7     45 %
 358006  54 ,     44 $
 358014  54 ,     44 $
 358086  70 8     40
 358094  62 2     40
 358102  61 1     41 !
 358110  63 3     41 !
 358118  54 ,     44 $
 358126  54 ,     44 $
 358134  54 ,     44 $
 358142 133 [      1 ^A
 358214 154 l     44 $
 358222 164 t     44 $
 358230  54 ,     44 $
 358238  54 ,     44 $
 358246  54 ,     44 $
 358254 133 [      1 ^A
 358262  54 ,     44 $
 358270  54 ,     44 $
 358342  54 ,     44 $
 358350  54 ,     44 $
 358358  54 ,     44 $
 358366 133 [      1 ^A
 358374  54 ,     44 $
 358382  54 ,     44 $
 358390  54 ,     44 $
 358398  54 ,     44 $
 358470  54 ,     44 $
 358478 133 [      1 ^A
 358486  54 ,     44 $
 358494  54 ,     44 $
 358502  54 ,     44 $
 358510  54 ,     44 $
 358518  67 7     45 %
 358526  71 9     41 !
 358598 163 s     41 !
 358606 141 a     41 !
 358614  61 1     41 !
 358622  54 ,     44 $
 358630  61 1     41 !
 358638  54 ,     44 $
 358646 133 [      1 ^A
 358654  62 2     40
 358726  54 ,     44 $
 358734  54 ,     44 $
 358742 133 [      1 ^A
 358750  62 2     40
 358758  61 1     41 !
 358766  54 ,     44 $
 358774 133 [      1 ^A
 358782  63 3     41 !
 358854  60 0     40
 358862  64 4     44 $
 358870  54 ,     44 $
 358878  65 5     45 %
 358886  54 ,     44 $
 358894  54 ,     44 $
 358902  64 4     44 $
 358910  62 2     40
 358982  54 ,     44 $
 358990  64 4     44 $
 358998 125 U      5 ^E
 359006  56 .     44 $
 359014  54 ,     44 $
 359030 164 t     44 $
 359038 156 n     44 $
 359110  54 ,     44 $
 359118  54 ,     44 $
 359126  54 ,     44 $
 359134  54 ,     44 $
 359142 135 ]      5 ^E
 359150  60 0     40
 359158  54 ,     44 $
 359166  54 ,     44 $
 359238  54 ,     44 $
 359246  54 ,     44 $
 359254  60 0     40
 359262  60 0     40
 359270  54 ,     44 $
 359278  54 ,     44 $
 359286  54 ,     44 $
 359294  54 ,     44 $
 359366  63 3     41 !
 359374  60 0     40
 359382  54 ,     44 $
 359390  54 ,     44 $
 359398  54 ,     44 $
 359406  54 ,     44 $
 359414  60 0     40
 359422  61 1     41 !
 359494  54 ,     44 $
 359502  54 ,     44 $
 359510  67 7     45 %
 359518  62 2     40
 359526  54 ,     44 $
 359534  63 3     41 !
 359542  66 6     44 $
 359550  54 ,     44 $
 359622  54 ,     44 $
 359630  62 2     40
 359638  64 4     44 $
 359646  54 ,     44 $
 359654  60 0     40
 359662  64 4     44 $
 359670  54 ,     44 $
 359678  54 ,     44 $
 359750  54 ,     44 $
 359758  67 7     45 %
 359766  54 ,     44 $
 359774  54 ,     44 $
 359782  54 ,     44 $
 359790  61 1     41 !
 359798  54 ,     44 $
 359806  54 ,     44 $
 359878 164 t     44 $
 359886 101 A      1 ^A
 359894 106 F      4 ^D
 359902 162 r     60 0
 359910 133 [      1 ^A
 359918  54 ,     44 $
 359926  54 ,     44 $
 359934  63 3     41 !
 360006  66 6     44 $
 360014  62 2     40
 360022  66 6     44 $
 360030  66 6     44 $
 360038  67 7     45 %
 360046  65 5     45 %
 360054  54 ,     64 4
 360062 135 ]      5 ^E
 360142  62 2     40
 360158 133 [      1 ^A
 360166  54 ,     44 $
 360174  66 6     44 $
 360182  62 2     40
 360190  66 6     44 $
 360262  54 ,     44 $
 360270  71 9     41 !
 360278  65 5     45 %
 360286 113 K      1 ^A
 360294  67 7     45 %
 360302  56 .     44 $
 360310 165 u     47 '
 360318 122 R      0 ^@
 360390  54 ,     44 $
 360398  63 3     41 !
 360406  54 ,     44 $
 360414  54 ,     44 $
 360422  54 ,     44 $
 360430  54 ,     44 $
 360438  60 0     40
 360446  54 ,     44 $
 548934  61 1    163 s
 548942  61 1    163 s
 548950 133 [      1 ^A
 548958  65 5     45 %
 548966  54 ,    166 v
 548974  54 ,    166 v
 548982  54 ,     64 4
 548990  54 ,    144 d
 549062  60 0    172 z
 549070 135 ]    127 W
 549078  54 ,     44 $
 549086  61 1     41 !
 549094  65 5    167 w
 549102 135 ]    127 W
 549110 124 T      4 ^D
 549118  61 1     41 !
 549190  61 1    163 s
 549198  54 ,    166 v
 549206  60 0     40
 549214  63 3     41 !
 549222  54 ,    166 v
 549230  54 ,    166 v
 549238  60 0    140 `
 549246  54 ,     44 $
 549318  54 ,    166 v
 549326  66 6    166 v
 549334  54 ,     44 $
 549342  54 ,     44 $
 549350  54 ,    166 v
 549358  61 1    163 s
 549366  54 ,     46 &
 549374  54 ,     44 $
 549446  54 ,    166 v
 549454  61 1    163 s
 549462  71 9     43 #
 549470  63 3     43 #
 549478  62 2    172 z
 549486  61 1    163 s
 549494  61 1     41 !
 549502  64 4     44 $
 549574  62 2    162 r
 549582  40      162 r
 549590  54 ,     44 $
 549598 124 T      4 ^D
 549606  70 8    162 r
 549614  62 2    162 r
 549622  63 3     43 #
 549630  63 3     43 #
 549702  67 7    167 w
 549710  54 ,    166 v
 549718  54 ,     44 $
 549726 135 ]      7 ^G
 549734  61 1    163 s
 549742  54 ,    166 v
 549750  54 ,     66 6
 549758  63 3     41 !
 549830  54 ,    166 v
 549838  54 ,    166 v
 549846  54 ,     44 $
 549854 135 ]      5 ^E
 549862  54 ,    166 v
 549870  54 ,    166 v
 549878  62 2     40
 549886  54 ,     44 $
 549958  65 5    167 w
 549966  62 2    162 r
 549974  63 3     41 !
 549982  54 ,     44 $
 549990 133 [    123 S
 549998  67 7    167 w
 550006  67 7     45 %
 550014 156 n     44 $
 550086  54 ,    166 v
 550094  54 ,    166 v
 550102  54 ,     44 $
 550110  54 ,     44 $
 550118  62 2    162 r
 550126 133 [    123 S
 550134  66 6     44 $
 550142  65 5     45 %
 550214  54 ,    166 v
 550222  61 1    163 s
 550230  62 2     40
 550238  71 9     41 !
 550246 135 ]    127 W
 550254  62 2    162 r
 550262  61 1     43 #
 550270  61 1     41 !
 550342  61 1    163 s
 550350  61 1    163 s
 550358  61 1     41 !
 550366  61 1     41 !
 550374  54 ,    166 v
 550382  54 ,    166 v
 550390  65 5     45 %
 550398 135 ]      5 ^E
 550470  54 ,    166 v
 550478  61 1    163 s
 550486  54 ,     44 $
 550494 135 ]      5 ^E
 550502  65 5    167 w
 550510  54 ,    176 ~
 550518  62 2     40
 550526  60 0     40
 550598  54 ,     66 6
 550606  61 1    163 s
 550614  54 ,     44 $
 550622 133 [      1 ^A
 550630  64 4    166 v
 550638  71 9    163 s
 550646  61 1     41 !
 550654  63 3     41 !
 550726  65 5    167 w
 550734  54 ,    166 v
 550742  54 ,     44 $
 550750  64 4     44 $
 550758  54 ,    166 v
 550766  64 4    166 v
 550774  65 5     45 %
 550782  54 ,     44 $
 550854  67 7    167 w
 550862  64 4    166 v
 550870 162 r     40
 550886 133 [    123 S
 550894  62 2    162 r
 550902  62 2     42 "
 550910  61 1     41 !
 550982  62 2    162 r
 550990  61 1    163 s
 550998  54 ,     44 $
 551006  54 ,     44 $
 551014  54 ,    166 v
 551022  54 ,    166 v
 551030  60 0     40
 551038  61 1     63 3
 551110  54 ,    166 v
 551118  70 8    162 r
 551126  54 ,     64 4
 551134  54 ,     44 $
 551142  54 ,    176 ~
 551150  60 0    162 r
 551158  61 1     41 !
 551166  64 4     44 $
 551238  54 ,    166 v
 551246  61 1    163 s
 551254  70 8     42 "
 551262  66 6     44 $
 551270 103 C    123 S
 551278  62 2    162 r
 551286  67 7     45 %
 551294 102 B      0 ^@
 551366  54 ,    166 v
 551374  61 1    163 s
 551382 133 [      1 ^A
 551390  61 1     41 !
 551398  54 ,    166 v
 551406  54 ,    166 v
 551414  54 ,     44 $
 551422  54 ,     46 &
 551494  66 6    166 v
 551502  63 3    163 s
 551510 135 ]      5 ^E
 551518  63 3     41 !
 551526  63 3    163 s
 551534  65 5    167 w
 551542 135 ]      5 ^E
 551622  65 5    167 w
 551630  54 ,    166 v
 551638  54 ,     44 $
 551646  54 ,     44 $
 551654  63 3    163 s
 551662  71 9    163 s
 551670 135 ]      5 ^E
 551678  61 1     41 !
 551750 151 i    163 s
 551758 141 a    163 s
 551774  63 3     41 !
 551782  66 6    166 v
 551790  54 ,    166 v
 551798  62 2     40
 551806  64 4     44 $
 551878  54 ,    166 v
 551886  63 3    173 {
 551894  65 5     45 %
 551902  67 7     45 %
 551910  63 3    173 {
 551918  54 ,    166 v
 551926  54 ,    144 d
 551934  54 ,     44 $
 552006  61 1    173 {
 552014  65 5    167 w
 552022  63 3     43 #
 552030  54 ,     46 &
 552038  61 1    163 s
 552046  63 3    163 s
 552054  70 8     40
 552062  64 4     44 $
 552134  65 5    167 w
 552142  71 9    173 {
 552150 154 l     66 6
 552158  40       60 0
 552166 154 l    166 v
 552174 151 i    163 s
 552182 160 p     40
 552190  61 1     43 #
 552262  54 ,    166 v
 552270  54 ,    166 v
 552278  54 ,     44 $
 552286  63 3     61 1
 552294  54 ,    166 v
 552302  54 ,    166 v
 552310  64 4     44 $
 552318  54 ,     44 $
 552390  61 1    163 s
 552398  54 ,    166 v
 552406 133 [      1 ^A
 552414  65 5     45 %
 552422  70 8    162 r
 552430  66 6    166 v
 552438  54 ,     44 $
 552446  54 ,     44 $
 552518  61 1    163 s
 552526 135 ]    137 _
 552534  62 2     42 "
 552542  61 1     41 !
 552550  61 1    163 s
 552558 135 ]    127 W
 552566 117 O      5 ^E
 552574  65 5     45 %
 552646  61 1    163 s
 552654  67 7    167 w
 552662  54 ,     44 $
 552670 135 ]      5 ^E
 552678  62 2    162 r
 552686  61 1    163 s
 552694  54 ,     46 &
 552702 135 ]      5 ^E
 552774  61 1    163 s
 552782  67 7    167 w
 552790  54 ,     46 &
 552798  63 3     61 1
 552806  54 ,    166 v
 552814  70 8    172 z
 552822  54 ,     44 $
 552830  60 0     40
 552902  71 9    163 s
 552910  61 1    163 s
 552918 133 [      1 ^A
 552926  61 1     41 !
 552934  62 2    162 r
 552942  54 ,    166 v
 552950 133 [      3 ^C
 552958  62 2     40

xxxtreeeem power savings

Following on my last playing around with Intel power stats, I tried Powertop to further reduce my lightly loaded server’s power usage. Powertop watches the kernel to see when interrupts wake the system from idle, then gives you hints on how to turn those power drains off. I turned on a bunch of their power saving tips to see what would happen. Honestly, not much, < 5 watts or 10% of my server’s power usage. And some of what I did was pretty aggressive, like disabling system backups and databases and email that I can’t do for real. Other things were more benign, tuning various parameters (like a 15 second disk flush instead of 5 second) but given how little benefit it has I’m not making changes permanent.

The changes I made are easiest to see in the INdividual interrupts graph, around Sun 16:00. You can see we go from 150 interrupts / second to about 50. Fewer interrupts = more idle time. It’s also sort of visible in the CPU scaling graph. But it’s not meaningfully visible in the UPS power graph.

There’s a bigger change in these graphs, around Sat 20:00. That’s when I shut down mongodb. Mongo seems to constantly be doing something even when sitting idle. I wasn’t seeing the 15% CPU some users report, but it’s a lot more than zero. Still has no meaningful impact on power consumption so it’s probably not relevant.

Intel power state measurements

While reading Etsy’s excellent performance tuning blog post I learned about i7z, a nifty little tool for showing you Intel CPU states. It gives details on clock speed, turbo mode, and just how deep an idle power saving mode it might be in. Fun stuff, but I like graphs in Munin! How to do it?

The i7z author was very kind to give me some suggestions and before too long I had a hacky Munin plugin to display the data. Image below. Unfortunately it requires running i7z in the background and writing to a logfile, not a great match for Munin. I think it’d be better to go back to the source for the data and craft a Munin plugin from the low level CPU info. That being said, i7z does a fair amount of nice work in interpreting things. It knows about different states in different CPU models, can interpret turbo frequencies, etc. It may be a lot of work to do a good general purpose Munin plugin.

Another program that gives similar info is Intel’s PowerTop, part of their awesomely successful effort to bring better power management to Linux. They’re responsible for a lot of savings, I’d guess 20-50% power (and heat!) for a server since the Linux-2.2 era. While looking through its code I learned there’s a lot of detailed info in /sys/devices/system/cpu/cpu*, including power states! Lots of files there, only a little documentation, here’s some of the fun stuff

cpufreq/time_in_state: histogram of clock speeds over the system’s life

cpuidle/: info on power saving. My CPUs have 4 states, the “name” file tells us they are POLL, C1-SNB, C3-SNB, and C6-SNB. cpuidle/usage and cpuidle/time seem to be counters for how often they’ve been in those states. Quicky monitoring

while :; do
  for f in state?; do
    cat $f/usage | tr '\n' ' ';
    echo;
  done;
  sleep 1; echo;
done

For posterity, here’s the hacky plugin I wrote to read the logfile that “i7z -w l” writes. Graph, then code. The graph here is spiky because I’m only sampling every 5 minutes, not taking the 5 minute average. Not sure it’s very interesting info anyway.

#!/usr/bin/env python

"""
i7z - Wildcard plugin to monitor CPU states

by Nelson Minar <nelson@monkey.org>, placed into the public domain

This plugin relies on i7z running in the background and writing
data to a file.

Valid names: c0 c1 c3 c6 c7
"""

# Sample input
# 1344980274.830075945 [1.000000,3.628642,1.000000,95.207611,0.000000]   [1.000000,-0.456208,1.000000,99.314697,0.000000]    [1.000000,-0.737858,1.000000,99.645119,0.000000]    [1.000000,0.956179,0.000000,98.813507,0.000000]
# timestamp [c0, c1, c3, c6, c7] x4 (for 4 CPUs)

import sys, subprocess, os

# Figure out the mode from the name the program was invoked with
mode = os.path.basename(sys.argv[0])[4:]
# figure out which array index of data we want
modeMap = { "c0": 0, "c1": 1, "c3": 2, "c6": 3, "c7": 4 }
dataSlot = modeMap[mode]

# config
if len(sys.argv) > 1:
    if sys.argv[1] == "config":
        print """
graph_title i7z status mode %(mode)s
graph_category system
graph_vlabel percent
graph_scale no
graph_args --upper-limit 100 -l 0

cpu1-%(mode)s.label CPU1
cpu1-%(mode)s.min 0
cpu1-%(mode)s.max 100

cpu2-%(mode)s.label CPU2
cpu2-%(mode)s.min 0
cpu2-%(mode)s.max 100

cpu3-%(mode)s.label CPU3
cpu3-%(mode)s.min 0
cpu3-%(mode)s.max 100

cpu4-%(mode)s.label CPU4
cpu4-%(mode)s.min 0
cpu4-%(mode)s.max 100
""" % { "mode": mode }
        sys.exit(0)
    else:
        sys.stderr.write("Unknown argument %s\n" % sys.argv[1])
        sys.exit(0)

# fetch data for munin

fp = file("/home/nelson/src/munin-i7z/cpu_cstate_log.txt")
data = fp.readline()
cpus = [1,2,3,4]
(ts, cpus[0], cpus[1], cpus[2], cpus[3]) = data.split()
for i, cpu in enumerate(cpus):
    cpus[i] = [float(n) for n in (cpu[1:-1].split(','))]
    print "cpu%d-%s.value %.2f" % (i+1, mode, cpus[i][dataSlot])

sys.exit(0)

sources.list.d

I love apt, the binary package manager for Debian and Ubuntu. It is fantastic. The only drawback is it’s always a bit scary to add extra repositories to the sources that it draws from. In particular I don’t care for editing the single global file /etc/apt/sources.list.

There’s a better way! In addition to /etc/apt/sources.list, apt will also read files in /etc/apt/sources.list.d. It only loads files named *.list for some reason, but it will append all those files to its group of sources. So you can keep the main sources.list file pristine from the distro and then add your custom repositories as separate files. Yay!

There’s also an extra tool for managing apt repositories from the command line, add-apt-repositories (aka addrepo). It has shortcuts for adding PPAs, also seems smart about getting signing keys.

visitors apache log analyzer

It’s irritating but there’s still no great solution for analyzing Apache log files. webalizer and analog both suck. One nice lightweight tool is visitors; it’s simple, fast, and mostly stateless. sample output, sample usage:

grep tweetchive /var/log/apache2/access.log{,-20120715} |
visitors -A -r 100 /dev/stdin
>| tweetchive.html

(cat /var/log/apache2/access.log{,-20120715};
  zcat /var/log/apache2/access.log*gz) |
visitors -A -r 100 -p 100 --prefix http://www.somebits.com --prefix http://somebits.com /dev/stdin
>| vis.html

# 4432363 lines processed in 41 seconds

Here’s some six years of weblog traffic. The breakdown reports are surprisingly uninteresting. I did learn my top Google search phrases: [chiller], [python xpath], [bash read], [spidermangame], [nelson minar], [bash read command]. I could make an SEO fortune!

CrashPlan on Linux

It’s taken me six months since my last server failure, but I’m finally implementing an offsite backup for my home Linux server. I use rsnapshot for local backups which is great for recovering from mistakes. But it does no good if your server box dies in a fire, need offsite backups for that. I like CrashPlan on my Mac, so I thought I’d try it on Linux.

The first hurdle is installation. The default install location is /usr/local/crashplan. The supplied shell script is quite nice and they even gave thought to letting you run the backups as some user other than root! I think if you don’t install it as root the /etc/init scripts don’t get linked in. Worse, those scripts don’t seem to have any provision for non-root users.

The second hurdle is setting it up. CrashPlan is only configurable via a GUI tool that assumes it’s running on the computer that’s being backed up. Weak! Fortunately there’s a workaround; the GUI client really just talks over a socket to the backup daemon and you can fake it out with to talk to a remote host via an ssh tunnel. The Mac client stores the port number in an awkward place, but then I found that instead of editing the .app config file I could edit /Users/nelson/Library/Application Support/CrashPlan/ui.properties and add the line servicePort=4200. Still, shame the GUI client doesn’t allow this setting.

One extra Linux challenge is that the real time backups feature uses the inotify kernel module which by default only allows watching 8192 files. The docs cheerfully suggest just upping this number, but then I read this post that suggests it costs 200 bytes per file monitored (or maybe it’s only 40). Either way I don’t want to bump this up to 100,000+ or whatever it’d take (one per directory?) so I simply disabled real time backups in the Advanced settings. I’d actually prefer it just ran a nightly backup anyway, to manage bandwidth.

The backup daemon is reasonably well behaved. It’s a java process (!) that’s using less than 5% of one CPU. The bandwidth throttle actually works.

I’m annoyed CrashPlan is listening on port 4243 on the LAN port, not just localhost. You can’t actually use this for remote administration, at least setting serverHost instead of serverPort in the client didn’t work out for me. I wonder how secure the daemon really is; the security FAQ only addresses file encryption. Update: if you disable listening for remote backups, then it only listens on localhost:4243, much more secure.

interactive fsck on Ubuntu

My headless server in Kansas didn’t reboot properly. The nice guys at the datacenter plugged in a console and found fsck waiting for them to press “Y”, which they did, and the system came back. Interactive fsck is pretty much always a terrible idea, particularly for a headless server, why was it waiting?

I can’t find good docs on this for Ubuntu. I’ve asked a question on StackExchange and started digging through code. I think the important setting is FSCKFIX /etc/default/rcS:

When the root and all other file systems are checked, fsck is invoked with the -a option which means “autorepair”. If there are major inconsistencies then the fsck process will bail out. The system will print a message asking the administrator to repair the file system manually and will present a root shell prompt (actually a sulogin prompt) on the console. Setting this option to yes causes the fsck commands to be run with the -y option instead of the -a option. This will tell fsck always to repair the file systems without asking for permission.

So Ubuntu already partially runs fsck in non-interactive mode; the -a flag (aka -p) “This option will cause e2fsck to automatically fix any filesystem problems that can be safely fixed without human intervention.” I guess something was wrong enough with the filesystem on reboot that -p was afraid to fix it. But in my case I don’t care; I have a backup, I need the server up under any circumstance, and I never knew how to answer fsck’s questions anyway.

I found this by reading through code. Ubuntu mounts filesystems via a program called mountall. Init invokes mountall and uses a shell script to set options. Here’s relevant bits of code:

/etc/init/mountall.conf:

[ "$FSCKFIX" = "yes" ] && fsck_fix="--fsck-fix"

mountall.c:

if (fsck_fix || mnt->fsck_fix) {
  NIH_MUST (nih_str_array_add (&amp;args, NULL, &amp;args_len, "-y"));
} else {
  NIH_MUST (nih_str_array_add (&amp;args, NULL, &amp;args_len, "-a"));
}

So there we have it, I think setting FSCKFIX=yes in /etc/default/rcS is my solution. And I’m glad to see even with that not set Ubuntu mostly runs fsck non-interactively.

Ubuntu 12.04 power savings

This is kind of neat; Ubuntu 12.04 is saving me 10-15 watts or about 25% of my server’s power consumption. I upgraded from Ubuntu 11.10 and my UPS is telling me my server uses 45W now instead of 58W, or thereabouts. The system is a few degrees cooler, too.

I suspect the important change is from the 3.0 Linux kernel to the 3.2 kernel, and the subsequent Power Saving Tweak where the Intel chipset is told to shut down the built in GPU. That’s a win for a lot of folks; headless servers (without weird code using the GPU) and desktop computers with “real” graphics cards. I’m surprised it’s so much an improvement though.

A second possibility is CPU affinity; there’s been some work on multicore systems trying to keep some cores shut down more often if the workload is light. Details on Less Watts tips. I enabled sched_smt_power_savings a few hours after upgrading Ubuntu, but I didn’t see any difference, so maybe not. The CPU frequency scaling graph suggests that maybe something’s changed.

The one alarming thing is that the IO Service Time went way up, from .00001s to .05s. Huh? I’m not doing much IO, so maybe this is a bogus measurement, and I can’t really understand what Munin is measuring anyway. This may be an artifact of the disks being put to sleep more often, or maybe the measurement changed scale, or who knows what. Simple disk benchmarks suggest nothing’s really wrong.

Update: turns out this was a change in the Munin scripts, a fix for an eight year old bug. The Ubuntu 11.10 version was reporting bogus numbers that were backwards and too small. Supposedly the new numbers are correct, and also report no data correctly now. Just reading the numbers off the graph, my system now says writes take about 20ms when before it was saying 0.1ms. Disk seeks are roughly 10ms, so I’m inclined to believe the new numbers are more correct. The bug comments also note that the various disk stats graphs contain similar information but are better.

Fixing a slow Samba server on Ubuntu 12.04

I recently upgraded my Ubuntu from 11.10 to 12.04. Mostly worked fine, the usual little config mishaps. But then one really bad problem: my SMB server on the Ubuntu box was terribly slow with my Mac client. Like reading a file would get 100kbytes/second. This on a gigabit ethernet where I used to be able to do SMB at the disk speed of 30Mbytes/second.

I ruled out some basic stuff: local disk access was fine, and copying the file via nc was super fast so it wasn’t the network. I started at guessing things. The final fix was to remove this line I’d previously put in my smb.conf

socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

Not sure why those settings would be harmful, nor which specific setting is the problem. The smb.conf man page suggests TCP_NODELAY is the default so I’m guessing it’s the buffers. Anyway, SMB is fast again.

secure remote backups with rsnapshot

I’m trying to back up my machine in a datacenter to my home server, using rsnapshot. The home machine is behind a firewall and pretty secure but I don’t want to be stupid about it. The remote machine should be secure, but is not firewalled. (OTOH both run ssh and http, so the attack surface is about the same). I found two useful guides for doing remote backups securely: one, two.

My final config is a pastiche of the two. Here’s the concept behind what I did. Backups run as root on the backup server and as a special-purpose user on the client being backed up (who can sudo to root to run rsync).

  • On the backup server, tell rsnapshot to backup a remote host via rsync.
  • On the backup client, create a new user who has no special privileges
  • Set up ssh keys (with no passphrase) so that root on the backup server can login as the backup user on the client. Restrict that ssh key to only be allowed to run an rsync frontend.
  • On the client, give the backup user the right to sudo to root but only to run /usr/bin/rsync.

I feel pretty good about the security; the user would have to steal my private key from the backup server to access the client, and even then they’re only restricted to run rsync. However that rsync is run as root and I’m sure could pretty easily escalate by, say, overwriting /etc/sudoers.

It’d be more secure to run backups on the remote client as some user other than root. But I want to back up files only root can read, so I’m kind of stuck.

 

Linux options for faster disk access

All these new computers have me interested in improving throughput. I’ve suddenly got gigabit ethernet, a huge amount of RAM, fast CPUs with many cores.. What’s missing is fast I/O. The hard drive’s 30 megabyte/second throughput is often a limiting factor for me. What are my options?

  • Put my data on an SSD. Appealing, but I don’t trust consumer SSDs not to fail. Also I hate having multiple disks with different capacity; I can never decide what to put on the SSD, what to put on platters. IE: right now I’m doing a lot of work with 300 gigs of music files and would like that to be fast, but it’d be stupid and expensive to leave those on an SSD forever (at 2012 prices).
  • Use an SSD as a writeback cache for hard drive. Very appealing option, and there’s three options. My Z68 motherboard includes support for Intel Smart Response Technology but sadly there’s no Linux support. There are two Linux projects that do something similar: Flashcache and Bcache. But both seem pretty bleeding edge and require lots of manual setup. The Bcache release notes a few months ago included a comment about “slow silent data corruption” that put me right off.
  • Hardware RAID. This Z68 motherboard has Intel RAID right on the motherboard, perfect! Only it turns out this kind of RAID is what’s known as fakeRAID; the operating system does most of the work. Linux can support fake RAID but if you’re going that route most people suggest just using Linux software RAID. (The advantage of motherboard RAID is the BIOS can help boot your OS).
  • Software RAID. It’s been awhile since I checked in on the state of Linux RAID and sadly, it’s in disarray. Docs on the net are all randomly out of date, talking about 2.6 kernels or 3 year old versions of Ubuntu. I think the systems are pretty stable, being based on md, just poorly documentd. These 9.10 docs are the best I’ve found. The Ubuntu installer will create a RAID array for you or you can go low level with mdadm. Apparently GRUB 2 understands Linux software RAID so you can boot right off the RAID disk.

Of course there are many flavors of RAID. I’m mostly interested in speed, not reliability, so RAID 0 seems like the obvious choice except everyone says that’s nuts because you double your chance of a disk failure destroying everything. Fun!

New kernel fail

I decided to build a custom Linux kernel on my Ubuntu 10.10 Oneiric box. 3.0.0 feels awfully old, and I’ve been having trouble with a couple of things (well documented here). I was hoping a modern 3.2 kernel from Ubuntu precise would fix both my ethernet driver problem and, by building specifically for a modern Intel CPU, enable sched_mc_power_savings. No such luck.

Building a Linux kernel has gotten remarkably complex. I mostly quit trying myself back in 2.2 or so; once loadable kernel modules got reliable there was little reason for a top end developer like me to muck with the kernel. These Ubuntu-specific instructions got me there, although it’s a long winded and complex thing involving a lot of configuration management.

Then I got it built and installed and rebooted and miracle! It worked. Only with the same old bugs. 10+ seconds to initialize the ethernet, and that power savings sysctl still missing. I gave up and removed my custom kernel. I’ll wait for the Ubuntu release to upgrade.

 

New server power consumption

Power consumption of various computers, as measured with the handy Kill-o-Watt
  • 2012 Linux server. 50W - 120W
  • 2011 iMac. 50W - 210W
  • 2010 Windows PC. 120W (always!)
  • 2003 Linux server. 50W

I like how the iMac numbers line up. The iMac has a GPU and a large LCD, so it maxes out higher, but when idle it’s about the same as the Linux server. It’s a very similar motherboard and the same CPU, so that all makes sense.

I don’t quite understand why the idle Linux box is using 50W and not, say, 10W. I don’t think the Intel CPUs will completely shut down a core when idle, that’s part of it.

Update: some useful notes from Intel and on SuperUser. Taking cpus offline via /sys/devices/system/cpu/cpu3/online didn’t save me any power. Either idle CPUs take very little power (unlikely) or the comment on SuperUser is right that this doesn’t halt the processor. The /sys/devices/system/cpu/sched_smt_power_savings also didn’t save me any power. I think sched_mc_power_savings would be useful, but it’s missing on my system. Apparently I need to rebuild the kernel with my processor family to enable it.

Update2: according to this article at low power an i7-2600 uses about 5W. Their measured idle system power (whole computer) is about 70W, so my 50W is in line. Where does it all go?!

At $0.33276/Kwh, every extra watt costs me $0.25 a month.

Realtek ethernet drivers: r8169 vs r8168

Update Jan 2013: this driver issue was fixed in Ubuntu 12.04 / kernel 3.2.0-14 or so.

Ubuntu doesn’t work out of the box with my ethernet adapter. The ethernet interface is very slow to come up after boot, taking 10-120 seconds. The problem is the Realtek 8111 or 8168, a very common motherboard ethernet adapter. The motherboard docs say it’s a Realtek 81111E. The Linux drivers are broken. Apparently this is a common problem across many Linux variants and people report other problems, too, packet loss and dropped packets. It’s a four year old bug in Ubuntu! How to fix it? (Other than buying a new NIC; Realtek NICs are not well loved.)

I did a lot of research. One proposed fix is to get a different device driver, from Realtek, not the Linux kernel sources. (More notes). Another suggestion is to enable Wake-on-LAN (via Windows), but I don’t really believe that will work. A third option is to upgrade kernels, there’s some possibility that the mainline Linux driver is better. (Most recent Ubuntu bug is 864196).

I decided to try Realtek’s driver. r8168-8.027.00. md5sum:
98155ce1ad5c248eeb7a93c9954d8344  /tmp/r8168-8.027.00.tar.bz2

Sadly, it doesn’t fix my problem. The NIC still takes 10-200 seconds to come up after boot. I also tried enabling wake-on-lan (via Linux, ethtool) and that didn’t fix it either. No surprise but I thought I’d give it a shot. I’m left with the conclusion there is no fix for this bug right now, despite the superstitions about Wake-on-LAN, or r8168 drivers, or whatever.

BTW, the autorun.sh script that comes with the r8168 driver from Realtek is pure evil. First, it unloads your ethernet driver. Completely killing your machine if you’re logged in via ssh and don’t have physical access! Then it goes and rewrites a bunch of stuff in /lib/modules and rebuilds your initram disk. It seems to get this right, but it’s awfully intrusive. I finally removed r8168.ko by hand and did an “apt-get install --reinstall  linux-image-3.0.0-15-server” to set things back.

I’m going to try living with this bug; I never reboot the box anyway. The first time I experience massive packet loss, or the ethernet doesn’t come up after boot, I’m getting a real NIC and putting it in a PCI slot. And never again buying a motherboard with a Realtek NIC for Linux use.

Details from lspci -v from stock Ubuntu, before I tried adding the r8168 driver:

03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 06)
 Subsystem: ASUSTeK Computer Inc. P8P67 and other motherboards
 Flags: bus master, fast devsel, latency 0, IRQ 45
 I/O ports at e000 [size=256]
 Memory at d0004000 (64-bit, prefetchable) [size=4K]
 Memory at d0000000 (64-bit, prefetchable) [size=16K]
 Capabilities: <access denied>
 Kernel driver in use: r8169
 Kernel modules: r8169

Configuring lm-sensors for Asus P8Z68-M-Pro

The temperature, fan, and voltage sensors in my fancy new Asus P8Z68-M-Pro motherboard weren’t recognized right out of the box. I fixed it by installing a custom kernel module and then telling the sensors(8) program to ignore some bogus readings.

The motherboard has two sets of sensors. coretemp-isa-0000, from the Intel chip, and nct-6776-isa-0290, from the motherboard. That second chip requires a custom kernel modules which I got from Guenter Roeck: w83627ehf. Easy to build and install, and afterwards sensors(8) shows lots of data.

Some of the data is bogus (see  this github issue), so I fixed it by dropping the following file in /etc/sensors.d:

# Configs by nelson to hide bogus values on my ASUS P8Z68-M PRO motherboard,
# which uses an nct6776-isa-0290 chip.

chip "nct6776-*"
 # These are not configured in sensors3.conf
 ignore in1
 ignore in4
 ignore in5

# Fans I don't have plugged in
 ignore fan1
 ignore fan3
 ignore fan4
 ignore fan5

# ignore CPUTIN and AUXTIN; bogus values
 ignore temp2
 ignore temp3

Those in and temp sensors are returning meaningful data, but they’re not configured correctly in the default /etc/sensors3.conf and I’m too lazy to track down exactly what they might mean. One of those fan sensors probably is for the chassis fan, but mine isn’t plugged in to my motherboard.

Disk and data transfer rates

All these disks and stuff have me confused about what fast transfer rates are. Here’s some numbers, mostly practical rates, not theoretical. All numbers are Megabits / second. See also the Wikipedia List of device bit rates.

  • 168,000: RAM for an i7-2600 (theoretical) (ref)
  • 10,000: HDMI v1.3
  • 6400: PCI (64 bit, 100MHz)
  • 5000: USB 3.0 (theoretical)
  • 4800: 6.0Gbit SATA
  • 2400: 3.0Gbit SATA
  • 800-4000: SSD drives (ref)
  • 1000: 7200 rpm hard drive disk-to-buffer (ref)
  • 1000: gigabit ethernet
  • 800: IDE, UDMA 5 aka Ultra ATA/100 (ref)
  • 250-480: USB 2.0 hard drive (ref)
  • 100: 100M ethernet
  • 30: fast US home Internet
  • 20: 802.11g wifi (ref)
  • 12: USB 1.0
  • 6: my crappy home DSL
  • 1: AT&T 3G downloads (ref)
  • 0.05: old acoustic modems
Bottom line: USB 2.0 is a little slower than a desktop hard drive. And SATA is significantly faster than a hard drive. I wish I could narrow the SSDs down, I think performance on those things varies quite a bit. My friend Lars just built a RAID 5 array of SSDs that’s showing about 10,000 Mbit/sec.
Some practical tests on my brand new Sandy Bridge server with 7200 RPM disks plugged into SATA/6 and formatted ext4fs. All numbers are Megabits/second
  • 1000: hdparm -t, testing disk read throughput from the platter
  • 110,000: hdparm -T, testing read from RAM cache (ie: never touching SATA or disk)
  • 1088: writing 16 gigs of zeroes
    dd if=/dev/zero of=zeros bs=1M count=16384
  • 440: copying 16 gigs of zeroes on a single drive
    dd if=zeros of=zeros3 bs=1M
  • 872: copying 16 gigs of zeroes from one drive to another. Parallelism!
    dd if=zeros2 of=/tmp/zeros bs=1M
  • 570: rsyncing 300 gigs of files from a FAT32 drive over USB-3 to an SATA/6 drive.
  • 20,000: writing 1 gig of zeroes. ext4fs must fully cache this before commit
    dd if=/dev/zero of=zeros5 bs=1M count=1024
  • 88: creating a file of random bits from /dev/urandom. I had no idea that driver was that slow.
These tests are all for big files. Linux gets a lot slower when dealing with lots of little files. Running rsync from a USB 2 disk copying to an SATA disk I’d see a factor of 10 difference in disk throughput between giant files and lots of tiny files.

The new Linux server

Here’s the parts I’m getting for my new server. Many thanks to Adam for sharing his system build of a few months ago. This system’s remarkably similar to a new iMac, albeit without the SSD. By all accounts this Sandy Bridge stuff is terrific.

1 of: Antec 380 Watt Power Supply Mid Tower Case NSK4482B (Black) $89.99
2 of: Western Digital 1 TB Caviar Blue SATA III 7200 RPM 32 MB Cache Bulk/OEM Desktop Hard Drive - WD10EALX $129.08
1 of: Intel Core i7-2600 Processor 3.4GHz 8 MB Cache Socket LGA1155 $295.00
1 of: ASUS SATA 6 Gb/s DisplayPort Intel Z68 Micro ATX DDR3 2200 Intel LGA 1155 Motherboards P8Z68-M Pro $119.99
1 of: Corsair 16 GB (4x4GB) Vengeance Blue Low Profile 1600mhz PC3-12800 240-pin Dual Channel DDR3 Memory Kit 16 Dual Channel Kit - CML16GX3M4A1600C9B $89.99

Junky case and very simple disk system. I won’t even run RAID, don’t trust it. No SSDs either, don’t trust those consumer parts. Just simple spinning platters. Some of the details matter. The i7-2600K is more popular because it’s overclockable. But I never overclock, and it turns out the i7-2600 has some virtualization capabilities that the i7-2600K doesn’t. It’s clear the Z68 chipset is the best motherboard, and I went with ASUS just because I always have. But they make like 6 Z68 motherboards and I can’t really tell one from the next. (After building this I learned the Realtek ethernet chip in the P8Z68 M Pro doesn’t work well in Linux. The P8Z68-V boards have Intel ethernet chips, may be a better choice.)

I told myself years ago I’d never build another computer from parts. Yet here I am. The local screwdriver shops are charging too high a premium, and then it’s a struggle to get them to understand you really want no graphics card, no OS, really just the simple server. “Oh, a server? How about this $4000 2U rackmount?”

At least I already know all about Ubuntu server.

Ubuntu server cron jobs

Here’s all the cron jobs on my relatively vanilla Ubuntu Server setup. I’ve added Apache and a few other minor things to the default install.

Daily:

  • htcacheclean, for Apache’s mod_cache disk cache
  • apport, cleans up old reports in /var/crash
  • apt, cache management
  • aptitude, making logs of what’s installed
  • dpkg, also making logs of what’s installed
  • popularity-contest, telling Ubuntu what people installed
  • bsdmainutils, managing user’s ~/calendar files
  • logrotate
  • man-db, managing the man page database
  • mlocate, an efficient implementation of good ol’ locate for fast finds
  • ntp, managing ntpstats (which aren’t enabled by default)
  • passwd, making backups of /etc/passwd and friends. (wtf?)
  • standard, the “standard daily maintenance script”. backs up /etc/passwd (again?) and looks for lost+found files. Dumb script, and redundant
Weekly:
Logrotate is configured to back up weekly and keep 4 weeks worth of logs and, surprisingly, not compress old logs. Apache overrides this to keep 52 weeks of logs and to compress them. I’m pleased to see the Ubuntu logrotate has a dateext and dateformat option to name logfiles like “access.log-20120108” rather than “access.log.3” and then renaming that to “access.log.4” the next week. That should be the default behavior but apparently that option isn’t available in older versions of logrotate.

Ubuntu and FQDNs

Setting the fully qualified domain name on an Ubuntu host is way too hard. The Internet is full of confusing advice. Most people first seem to notice the FQDN isn’t right when setting up Apache, but it’s a broader problem than that. (You can fix Apache just by giving an explicit ServerName directive.) “hostname -f” should return the right thing.

My solution:

  • /etc/hostname contains just the system name, “wi”
  • /etc/hosts contains an entry like this:
    208.110.64.210  wi.nelson.monkey.org wi
  • /etc/resolv.conf contains an entry like this:
    domain nelson.monkey.org

And now “hostname” returns “wi”, “hostname -f” returns “wi.nelson.monkey.org”. Note I don’t have a reverse DNS entry for that IP address. (I do have forward DNS so wi.nelson.monkey.org resolves, but I don’t think it’s used.)

Part of the confusion is a lot of people (and Ubuntu by default) want you to do something like

127.0.1.1 wi.nelson.monkey.org wi

This kind of works, despite the odd loopback address number. But it’s not really correct: your FQDN should resolve to a routeable IP address, not a loopback.

 

 

Ubuntu server notes from an old Debian user

I’m setting up a new Linux server and using Ubuntu for it for the first time. I’ve been a Debian guy for a long time now (and before then, Red Hat), so Ubuntu is both new and old. I switched to it because it’s got a faster upgrade cycle than Debian, but I like all the extra tools they’ve added, too.

Here’s some of the new things in Ubuntu I’ve learned about. The Ubuntu server docs are an excellent place to start.

  • upstart, a replacement for SysV init scripts that runs things in parallel. The configuration files live in /etc/init. There’s still old SysV stuff in /etc/rc2.d and /etc/init.d being run. The new service command is nice, ie “service --status-all”. There’s plans for upstart to replace cron and at, too. Docs: UbuntuBootupHowto, original rationale, upstart tutorial, and cookbook. (Ubuntu does not use systemd, another modern init replacement).
  • plymouth, the graphic splash boot screen. For some reason this is complicated and intertwined with upstart.
  • ureadahead (aka Über-readahead), a clever system to improve boot times by reading all necessary user files off of disk in one big transfer at the beginning of boot. The boot image is kept in /var/lib/ureadahead and there’s clever stuff to invalidate and re-write the files when new things are installed. It seems to save a few seconds on boot for me, not positive. More info here.
  • ext4fs is the default filesystem. It has various incremental improvements to ext3fs, many of them aimed at efficiently handling big files and disks.
  • AppArmor, a security mechanism. It lets the kernel restrict what access various programs have. For instance, ntpd is only allowed to write to certain log files so if there’s ever an exploit against ntpd it won’t go writing random files as root. It seems like a fairly limited security mechanism given how big the attack surface of Linux is, but also harmless and potentially useful.
  • ufw, Uncomplicated Firewall, is a friendlier interface for firewall rules than iptables.
  • Automatic software updates. The setup process is embarrassingly manual, but you can have Ubuntu install security updates (or all updates) automatically.
  • pam_motd, the absurd thing that makes /etc/motd show current system stats. It seems to update on login. If it ever breaks I will be very angry if I can’t log into my system.
  • JeOS is a stripped down Ubuntu server for running as a guest in a virtualization environment. I have no need for this now, but it’s a good idea.
  • Bacula, a fancy backup system. I will probably stick with rsnapshot and rsync.
  • Launchpad, a website where many Ubuntu projects are hosted. Bug tracking, etc.

One thing they haven’t improved is libresolv; it still queries nameservices serially, one at a time. Worse, the first entry in /etc/resolv.conf for me named 192.168.1.100 as the nameserver, a bogus entry from the initial setup in a different DHCP environment. So every DNS query was waiting 5 seconds for that to time out. I fixed it by putting Google’s 8.8.8.8 as the first nameserver.

My next project is to automate all my deployment of my own stuff to the server using Puppet or maybe Chef Solo. I’m trying to avoid the thing where my servers become an irreproducible rat’s nest of random crap I’ve collected over time. OTOH, I can tell already it’s going to be a lot of work for one little personal projects server.

 

NFS notes

I set up some NFS mounts from my Linux (Debian) box to my Mac. Some notes.

Servers: install nfs-kernel-server. Configure it along these lines. NFSv4 seems to want to serve all its fileshares from a single directory, which seems weird, so you do this “mount --bind” thing to collect them on the server. Options on the server are ro,nohide,insecure,no_subtree_check,async

Client: Use MacOS Disk Utility (File / NFS Mounts..) to add static mount points. They seem to mount automatically once you exit the tool, but I’m not sure. I set the following advanced options: ro,intr,soft,nfsvers=4. Here’s some Mac docs.

NFSv4 is the new hotness. You can verify you’re using it with “nfsstat -4 -s” on the server and count the numbers.

These notes are all for a read-only export of world readable data. Next step is to export read-write, which requires synchronizing users. Unless you go some authenticated route (ie: Kerberos) the best bet is to be sure numeric user IDs are the same on the client and the server. On MacOS you can change your uid by right clicking on your name in the Users & Groups preferences pane. I’m guessing you’ll have to manually chown the files afterwards.

Samba: get rid of stupid executable files

Editing files on Windows has an annoying habit of making them show up +x on Unix. Windows doesn’t have an idea of an execute bit, so some ambiguity is expected, but still. Turns out the real culprit is the map archive configuration option. It’s on by default, which means the Archive bit in Windows is mapped 1:1 with the U+X bit on Unix. That’s really stupid; Windows apps set the Archive bit willy-nilly (hello, Notepad++) and it gets annoying, particularly with git tracking file modes. So configure Samba with “map archive = no” for your fileshare and life gets better.