Some Bits: Nelson's log

21 posts in August 2022

California electricity grid; resource adequacy

California has its own electricity grid, roughly independent from other states. The California ISO that runs it has an excellent dashboard (and mobile app) showing grid status, predicted demand, the march towards renewable energy, etc. It’s very well done, I think a response to the chaos around the year 2000 when we didn’t have enough electricity for the state.

We’re about to have a very hot week so I looked in detail at the 7 day resource adequacy graph. What this means is documented mostly here.

There’s two datasets: graphed in teal and purple respectively. Teal is more or less actual power. Dashed line is forecast capacity; it fluctuates mostly with solar. The faint dotted line is forecast demand; it fluctuates mostly with air conditioning need and evening home demand. What this is showing us is that towards late afternoon on 9/4, 9/5, and 9/6 we’re going to have a little more demand than supply. That’s not a catastrophe; CAISO can buy power from other states, at least assuming any is available.

The purple graph is the same data but excludes wind and solar from production, that’s why it’s so steady. (It also excludes something from demand but I’m not sure what). An added complication are “credits”; I’m not sure what those are, but if you visualize them they’re only about 2GW out of 55GW.

It’s worth noting that these are predictions, promises of what the electricity providers are telling CAISO they can generate. I believe they’re obligated to actually supply all this promise, the shortages in 2000 and 2001 was partly because some of the generators were playing games with supply to manipulate the market.

There’s a lot of other neat data on the CAISO site, particularly the supply pages that highlight renewables. May 8 2022 was a banner day: we had enough solar and wind to cover all demand, so fossil fuels dipped very low. (Not zero, but we exported more power than we generated in fossil fuels. I assume that was a choice made for financial reasons.) Alas this is only possible in late spring when solar is high and demand is low.

Another interesting dataset are the curtailment reports, times CAISO tells solar or wind providers to stop providing power because they have no place to put it. It’s not a huge amount of power and seems mostly to do with local bottlenecks, not pure overcapacity. Exta power first goes to batteries and pumped hydro.

One thing CAISO doesn’t provide much is graphs of trends over year; they’re very focussed on intraday reporting. They do publish monthly reports with data in PDF format.

Linux system call numbers

Since I’m in the guts of assembly programming I’m curious about system call numbers in Linux. What’s weird is they differ depending on system architecture; exit is 93 on aarch 64 but 60 on x86_64. How does this work?

The usual source for getting system call numbers is /usr/include/sys/syscall.h. But trying to read that stuff is a twisty maze of nested includes and CPP magic (that path doesn’t even exist!) If you find your way to /usr/include/x86_64-linux-gnu/asm/unistd_64.h you’ll finally find a list but even then it’s not exactly authoritative. Those are the numbers C programs using the system calls are using.

The Linux kernel itself defines the system calls in the kernel in files named syscall*.tbl. There’s 20 right now. These are also extracted in handy table form on this web page which makes for a nice (if possibly outdated) reference. exit is 1, or 60, or 93, or 9437185, or... why are these all different?

This Stack Overflow question has a partial answer; the x86_64 numbers were rewritten in 2001 by aa to “optimize it at the cacheline usage level”. Talk about baking in implementation details for ancient hardware! But the numbers are arbitrary anyway and I doubt it’s harmful.

To complicate things further not every system call is implemented on every architecture. nice, for instance, is system call 34 on i386 but isn’t in x86_64; instead the more modern setpriority system call (141 or 154) is used. Presumably libc is papering over these differences for most programs.

I think system call numbers tend to be assigned in ascending order, so sorting by number gives you a little history of additions to the Linux kernel ABI.

Lightweight ARM64 build & run on x86

qemu-user-static is some serious magic.

So the reason I’m playing with Raspberry Pi stuff is I have a mind to learn ARM64 assembly, aarch64. And figured it’d be fun to do that with a native hardware experience. There’s no practical reason for this, just felt a desire to get back to my roots. (My first real programming was all 6502 assembly as a kid.)

So far I’ve been doing my little exercises in an aarch64 shell, either directly or using VS.Code remote development to ssh in. I like the idea of actual ARM hardware being in the mix. But cross compiling and emulating is reasonable too. And so easy!

To cross-assemble on an x86_64 host, all you need to do is

$ apt install binutils-aarch64-linux-gnu
$ PATH=/usr/aarch64-linux-gnu/bin/:$PATH

That will install as and ld and related tools for assembling and linking object code. There’s lots more packages for cross-compilers for C++, Go, Modula 2... apt search aarch64 gives you a list. (I once spent a month trying to get a gcc cross-compiler working.)

But here’s the real magic:

$ make hello
$ file hello
hello: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, not stripped
$ arch
x86_64
$ ./hello
-bash: ./hello: cannot execute binary file: Exec format error
$ apt install qemu-user-static
$ ./hello
Hello World!

WTF? I’m running an aarch64 executable on my x86_64 system. That is some serious magic. For extra credit the x86_64 system is actually WSL, a virtualized Linux. Which probably doesn’t really matter but is kinda neat.

Half the magic is done with the binfmt-support package. That is a kernel module that tells Linux how to execute various binaries it doesn’t know about. It’s the same trick that makes .jar files directly executable. So that’s the part that’s intercepting the aarch64 binary to run it somehow.

QEMU is doing the actual running of the foreign binary. It’s a software emulator, not hardware emulation, so it is pretty straightforward to have it support a bunch of architectures. qemu-user-static just packages it up nicely. It looks to support 29 different architectures including s390, riscv64, even the good ol’ mipsel I cut my teeth on in college. The emulator binaries are pretty big, 3-4MB each and statically linked.

I didn’t read up much on the environment QEMU is providing; there’s lots to read. It’s definitely not a whole operating system in a persistent VM. It seems to translate syscall numbers though; my aarch64 program works even though it calls exit as syscall 93 when on x86_64 it’s 60. The docs says it translates signals and maps threads too.

Advanced topics: running dynamically linked binaries, getting a debugger working.

Update: WSL isn’t completely seamless; after a reboot the QEMU stuff stops working because it relies on systemd to install stuff. You can run sudo update-binfmts --enable to fix it. There’s also a related problem where after installing the emulator WSL complains /proc/sys/fs/binfmt_misc/WSLInterop: No such file or directory; that is fixed on reboot.

Electron bloat vs RPi 4

Running a Linux desktop on a slowish RPi 4 with 4GB of RAM sure makes you appreciate just how bloated and slow Electron apps are. Should it really take 300MB to run a fancy IRC client or 150MB to grep a password file? Some example memory sizes, as reported by conky’s summary of free system memory and then ps_mem. Bolded numbers are what I think is the fairest measurement.

  • 1password: 181MB, 152MB, 196+124=320MB
  • webcord: 355MB, 308MB, 277+115=391MB
  • chromium (1 blank tab): 265MB, 250MB, 196+136=332MB
  • VS.Code (1 .py file): ?, 550MB, 439+122=561

(For each process I first tested what corky said was memory in use when I ran just that app and no other Chrome stuff. Then launching it with other Chrome stuff in memory. The third set of numbers is what ps_mem.py reports. These measurements are complicated by how you account for sharable memory and the details of that are inscrutable).

Memory aside these things also take enormous amounts of CPU. And are very slow, latency when typing in them is quite apparent in some part of every app. I’ve known Electron was bloated but stopped noticing on high powered desktops. We lose a lot when we give up on optimized native apps.

Raspberry Pi 4 as a Ubuntu desktop

Update this whole post was written using Ubuntu 64 bit with Gnome on an RPi 4. I’m trying a second time now with Raspberry Pi OS (LXDE) and it’s going much better, new post coming.

I decided to give a Raspberry Pi 4 a go as a Ubuntu desktop. It did not go very well. I think the hardware is just too underpowered. Which is a little ridiculous given how much more capable this hardware is than the systems of 10 years ago. I’m using this on a stock RPi4 with 4GB of RAM and the basic boost overclocking enabled. The system is installed to a SSD connected with USB3 that gets 250MB/s in benchmarks. (Which itself is odd; it should be 500MB/s. RPi4 I/O is limited I guess). My screen is 3440x1440.

Installation is remarkably easy and clean. The Raspberry Pi people have a GUI app that installs bootable operating system images. Basically plug and play. Newer RPi4 can boot directly off USB, no need for an SD card at all. Which is good; SD card I/O is slow. Graphics and sound basically worked out of the box. Even Bluetooth audio.

Performance is very rough though. There’s regularly 5 second delays between typing something and it showing up on my screen; here in the Wordpress editor, in the URL bar of a browser, pretty much in any GUI. Sometims keystrokes get lost. It’s much better in a Gnome terminal but even then there’s sometimes a perceptible subsecond delay. I really don’t understand the terrible latency on user inputs, even when several CPUs are idle and I have 1.0GB RAM available (currently allocated to buffers and cache). I wonder if something more serious is wrong?

I’m using the default Ubuntu 22.04 Gnome desktop. I might have luck with lighter GUIs - Lubuntu and Xfce are both recommended. I briefly tried them and they did seem faster but they were also uglier.

Update: I tried LXDE on Ubuntu, the desktop environment Raspberry PI Desktop uses, and it’s much better. The ubuntu install I did is pretty janky but that’s probably my fault, I bet the integrated Raspberry Pi Desktop experience is nicer. Responsiveness is much better and memory usage is much lower although this Wordpress editor still drags. LightDM is a big improvement too; the Gnome Display Manager is a huge hog for something that’s just a freakin’ login box.

Update 2: Raspberry Pi Desktop is indeed better. It’s much lighter weight than Ubuntu Gnome and it’s coherent in the RPi build, much better than my janky LXDE. Bluetooth config works! Youtube audio playback is mostly fine but pauses every once in awhile when something else is happening. The wordpress editor is worse than ever though. Beginning to suspect a bug in their Javascript code exacerbated by the relatively low system.

I started with Firefox which was a mistake; the aarch64 build of that is really slow and memory hungry. Chromium is a little better, apparently someone put some real effort into optimizing it for the RPi. It’s still not good though. Super sluggish, regularly pins all 4 CPUs at 100%, and uses a lot of memory per tab. I can’t watch a single Youtube video at 240p even with nothing else going on and the window minimized (sound, no picture). CPUs aren’t overtaxed but the sound playback is choppy and awful. Again, maybe a symptom of something more serious being wrong than just system load.

Update: the fix for Youtube is apparently the h264ify Chrome extension, which forces Youtube videos to H.264 instead of VP9. Which allows for hardware decoding. Shame YouTube isn’t smart enough to do that for you.

Gnome on Ubuntu 22.04 looks fairly good. But the moment you start pushing on stuff it breaks down. There’s two separate programs called “Software Updater” but what you really want is a third program “Ubuntu Software” which installs Snap apps. 1Password requires a manual install; they haven’t built aarch64 packages (But do have a tarball). Lots of weird off-brand Linux choices for ordinary user apps. I never could get the Gnome system monitor to show up in my task bar.

I had a much better experience using this environment on my fast desktop PC. Ubuntu Gnome does at least work on RPi 4 but it’s so slow that it is a miserable experience. Maybe next time I try this I’ll use the Raspberry Pi OS build instead.

PG&E solar billing; two channels

Did you know PG&E smart meters have multiple channels? “Channel A represents energy pulled from the grid” while “Channel C represents energy exported back to the grid”. Weird! Details below.

PG&E screwed up during my solar period and for 6 months even though their records showed I was sending them more power than I was receiving, they were billing me for $200 worth of electricity a month. I eventually got a refund but I made a CPUC complaint about what looked like abusive and fictitious billing.

To PG&E’s credit they got in touch with me to resolve my complaint and I had a chat with a knowledgable customer agent who gave me a clear answer. Here’s how CPUC summarized it:

PG&E advised that NEM customers are billed with interval data using 2 channels on the SmartMeter: Channel A registers consumption, while Channel C registers exported generation.

The PG&E docs show pictures of bills with breakouts by channel, but I can’t find that in my bill. But the docs I’ve found online are 15 year old, many for NEM1 (I’m on NEM2) so maybe it’s not available now, or I won’t see it until my yearly true up.

I can’t make any sense of how this would work electrically. AFAIK my solar feed was installed with vampire taps between the meter and the circuit breakers; there’s no separate wire coming in from my solar directly to the meter to record. Maybe the two channels are more of a synthetic thing, with A being the sum of watts used during intervals that are positive and C being the sum of the negatives. Or maybe there’s some magic in the energy grid that can detect flow? I doubt it.

The funny thing about all these attempts to verify what PG&E is saying is they come to nothing; you’d never prevail in a dispute over how they bill. My Sunpower monitoring regularly shows me about 1kWh a day better off than PG&E bills me. Flaky meters? PG&E skimming? Who knows. The PG&E data looks roughly accurate though and they are effectively the law, so not much point second guessing it.

ffmpeg and hevc_qsv Intel Quick Sync settings

I’m revisiting my experiments using Intel Quick Sync to transcode video into H.265 using the hevc_qsv transcoder. I’m using jellyfin’s build of ffmpeg. Here’s where I ended up:

function to65 {
  /usr/lib/jellyfin-ffmpeg/ffmpeg \
    -c:v h264_qsv \
    -i "$1" \
    -map 0 -c copy \
    -c:v hevc_qsv -preset slow -global_quality 22 -look_ahead 1 \
    $2 \
    "${1%.*} x265.mkv";
}

Doing this results in an H.265 video file about 1/4th the size of the H.264 file and takes about 1/8th the show length to transcode. (ie: 5-6 minutes for a typical 42 minute tv show). Quality looks about the same to me but I’m using fairly unexciting video sources to test.

ffmpeg options

The challenge is this is all very poorly documented, particularly quality settings. Keep in mind that hardware H.265 encoding is generally considered lower quality than the CPU based x265 encoder. NVenc is said to be better than QSV. Also be aware Google search is treating hevc_qsv as a synonym for h264_qsv, so searches will often find irrelevant information if you’re not careful.

ffmpeg -h encoder=hevc_qsv is supposed to give you a list of all the codec specific options. You can see that list here. But there’s no real basic quality or bitrate setting, just a lot of mysterious technical-seeming options. Some of this might be documented in the Intel Media SDK docs or this white paper on how it all works.

Instead you want these ffmpeg docs and the QSV encoder help page. The key option here is global_quality. I think this works like crf (which is not an option and seems to be silently ignored if provided). The number is not documented but can be 1 (highest) to 51 (lowest), folks online recommending about 21. With global_quality set you still have 3 algorithm options: -look_ahead 1 seems to be the fanciest. I’m not sure but that might be the default. -preset is another option to consider; slow seems the right tradeoff to me. I did not consider the -profile option.

I still feel like I’m missing one clear set of docs for how this encoder works. I cobbled some of it together also using this cookbook page.

Testing

I did a very casual test of these settings using a 720p web rip (AMZN) of a TV cooking show. The original file is about 6000kbps; the video stream itself is 5800kbps H.264. I have a tin eye; I’m OK with fairly mediocre video encoding for most things like this. I’m just trying to keep some old TV shows around without taking up too much space.

For visual quality, -global_quality had an enormous impact; it’s the most important setting. Using the default settings instead or was unacceptably bad, particularly on scene transitions. Honestly anything from -global_quality 18 to 26 looked about the same to me. The preset option didn’t have nearly as clear an impact on visual quality.

Preset does have an impact on encoding speed. medium: 9.5x. slow: 7.5x. slower: 3.7x. Quality settings didn’t have much impact on encoding speed.

Here’s bitrates at different settings of -slow -global-quality N

-global_qualityFile bitrate (kbps)
182911
202309
221777
241395
261114
original6075
default hevc_qsv1222

Running ffmpeg this way uses 1 CPU core and the GPU at 100%.

Screenshots

Sorry for the lack of labels on the images. The first is the original, the second two are without global_quality (and unacceptable). The rest are progessively lower global_quality although honestly they all look about the same to me. This was a frame with a lot of detail right after a scene transition. It’s not crystal sharp in the original so it’s not a big surprise many of the transcoded versions are roughly the blurry same.

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.

Grub, recordfail, 30 seconds

My new Ubuntu 22.04 system was pausing for 30 seconds every boot in the GRUB menu. Despite GRUB_TIMEOUT=0 being set in /etc/default/grub. The fix is to also set GRUB_RECORDFAIL_TIMEOUT=5 in the same file. (Or set it to 0 if you’re feeling sporty.) Read below for the ugly details or see Ubuntu bug 1918736.

GRUB has a nice thing where if a boot fails then on the next try it gives the sysadmin extra time to figure out what’s wrong. It’s common to have no menu or delay if the last boot worked. But if it fails then you get 30 seconds in a menu to press buttons.

The problem is Ubuntu has been broken for a very long time and every single boot GRUB uses this failure timeout. Check out this charming code from /etc/grub.d/00-header/

if [ \$grub_platform = efi ]; then
  set timeout=${GRUB_RECORDFAIL_TIMEOUT:-30}

What this says is “if your system boots with EFI then ignore the configured timeout and wait for 30 seconds”. They’ve been doing this for 3 years. EFI is the common case for PC hardware and I think every installed Ubuntu system every single time it boots waits for 30 seconds for no reason except someone hacked around some other problem in a clumsy way, then never cleaned it up. I’m not sure but the underlying problem may have something to do with detecting whether a boot failed or not. A similar problem shows up with LVM systems.

Update: I misunderstood; this code only runs when recordfail_broken is set, which happens if GRUB determines the boot media is not writable. The check_writable function says diskfilter, lvm, btrfs, cpiofs, newc, odc, romfs, squash4, tarfs, and zfs are all not writable. I guess that’s for a good reason; GRUB’s not able to record that the boot worked so it assumes it failed. Sure is a kludge though.

I set the timeout to 5 seconds because in the case of a real failure I need that time in the menu. It’s still 5 seconds longer than it should be but at least it’s not 30.

I am sure cranky about this. I’ve been encountering a lot of bugs like this setting up my new Linux system, probably because I’m paying such close attention. Part of being a successful tech worker is ignoring all the broken stuff that’s not a big deal because you’re doing something more important. But I have time to get into the details of GRUB, or fstabs, or whatever and what I find is alarming. I always wonder “why doesn’t the engineer working on this give a shit?”

In the Old Days nerds who installed Linux were very proud of one thing: their system uptime. Later on we started accepting reboots were part of life and so the focus shifted to making fast boots (the primary reason for systemd!). Now apparently Ubuntu developers care so little about EFI boot that no one minds that for three years it’s been wasting 30 seconds every single boot. I suspect that’s because of the shift in focus to cloud computing; the serious work is now all on systems that probably aren’t using GRUB at all, just booting in a VM.

I do wonder what this means for folks on laptops though; Ubuntu still seems serious about desktop Linux Maybe I misunderstand and somehow this bug is avoided in common installs? Update: see above, it only affects some types of boot volume.

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.

Sonos server alternatives

I’m pulling my hair out trying to get Sonos to connect to my new SMB server. The various dark arts needed to enable SMB1 for Sonos’ ancient file sharing implementation aren’t working and there’s no debugs. Is there some way to share my local music files other than SMB? There’s no way to plug a USB drive into a Sonos directly :-(

One alternative is Plex. It has music capabilities. I’m finding it a little flaky and until I fiddle further it’s only finding files that it has metadata for, not the weird MP3 files that fell off the back of a truck.

Another alternative is Airsonic, another Plex-like media server. It has explicit Sonos support via the Sonic Music API (SMAPI), a new-to-me thing.

A third alternative is Bonob. I know nothing about it, just found it as a SMAPI server. I’ve seen it mentioned in concert with Navidrome.

SMAPI is an interesting back door into Sonos serving! A whole documented API. You can add a service of your own via bare bones HTML interface at http://192.168.0.50:1400/customsd.htm (IP address is of a Sonos player on my LAN). I wonder what the API schema is like; I suspect it is oriented to music with tidy metadata and not “giant pile of MP3 files in carefully curated directories”.

There’s some small or abandoned GitHub projects that are SMAPI servers: YouTube, a NodeJS server, a C# server. This NPR One service looks active.

You know what would be really nice? A stripped down SMB1 anonymous server solely for Sonos clients. Samba is so complicated, something that works with Sonos’ ancient client might work better. Alternately some folks use a Raspberry PI as a NAS/SMB gateway.

Ubuntu 22.04: apt keys

New version of Ubuntu has a massive usability regression in adding third party package repositories. There’s a legitimate security reason for the change but they’ve made no affordance for making it easy for users to migrate or understand the new way. I can’t even find docs on the official help. This is bad usability even by Unix standards; I suspect Canonical doesn’t care because they’re pushing their Snap package store so hard.

There’s good information here. Bottom line; the old way meant that the new key you were adding was trusted for all repositories. Rather than fix that design flaw in some sensible way they’ve just deprecated the feature entirely and left users to run gpg -dearmor or some such nonsense to manage keyfiles themselves. Really. It’s 2022 and Ubuntu thinks “just use PGP from the command line!” is a reasonable thing to tell someone. Some tool to do this file management for me would sure be a better choice.

The change seems for the better but they sure didn’t do anything to build tools for the new way or explain the transition. Pretty sure the Ubuntu devs just told me to go fuck myself.

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.

Ubuntu, ffmpeg, and Intel GPU acceleration

My fancy new Linux box has an Intel 12th gen CPU (Alder Lake) with a GPU in it. I wanted to try using ffmpeg to transcode video from H.264 to H.265. Here’s how I got it working, it was not easy.

Transcoding commands

First, my old way of transcoding without GPU acceleration

ffmpeg -i "$1" -map 0 -c copy -c:v libx265 -crf 25 $2 "${1%.*} x265.mkv"

I get about 4x encoding speed on an i5-12600K (compare about 1.1x on a ten year old i7-2600). However all 16 cores are pegged at 80% ish and the machine is drawing 165 watts. Note we’re using the libx265 encoder, all CPU. It’s not bad.

The new hardware accelerated way (some of these arguments need tweaking)

sudo /usr/lib/jellyfin-ffmpeg/ffmpeg \
  -c:v h264_qsv \
  -i input.mkv
  -c:v hevc_qsv
  -c:a copy out.mkv

This runs much nicer! I get 7.5x encoding speed. But now I’m only using 1-2 cores and the machine is drawing only 55 watts. I haven’t looked closely at encoding options or video quality but a quick preview looks plausible.

The primary change here is different codecs; h264_qsv and hevc_qsv. These are Intel Quick Sync codecs that are hardware accelerated using the GPU. The h264_qsv decoder uses about 10 watts less than the default CPU decoder (and 1-2 cores). The hevc_qsv is where the big savings are, some 90 watts.

The other change is I’m using jellyfin’s build of ffmpeg. Installing all this was a bit of a trick. Note also I had to be root to run this; I think there’s a way to change permissions so you can open the video device without root. Update: the devices are in /dev/dri which are usable by group “render”.

Installing prerequisites

I’m starting with an Ubuntu 22.04 server install running the 3.19 mainline kernel. Probably any kernel is fine.

I installed these packages from the default Ubuntu repository:

$ apt install onevpl-tools vainfo intel-media-va-driver-non-free
$ sudo vainfo
vainfo: Driver version: Intel iHD driver for Intel(R) Gen Graphics - 22.3.1 ()

OneVPL is Intel’s userspace for Quick Sync, the GPU accelerator. The non-free driver is recommended. vainfo is probably not necessary but is a handy tool for verifying the graphics driver.

With this I thought the stock ffmpeg would work. But it did not. I finally gave up and installed the jellyfin-ffmpeg package with the Ubuntu Repository instructions. Jellyfin is an open source media server, sort of like Plex. Its hardware acceleration docs are a lot clearer than ffmpeg’s wiki docs and apparently their build of ffmpeg has something important that Ubuntu’s does not.

Updates

intel_gpu_top (from intel-gpu-tools) is handy for seeing what’s running on the GPU

UEFI, ESP, secure boot, and GRUB

I haven’t really thought about how a Linux system booted in years, back in the old MBR days. (“Load the first block and run the code”, more or less). Modern PCs are much more complicated with secure boot and UEFI. Some notes on what I learned reading about it. I’m cranky about all of this complexity; particularly the idea there’s some security layer in my firmware that prevents me from booting disk images I installed on purpose. I realize this is to protect against malware that installs itself in the boot chain, but I’m not honestly that worried about that risk.

Summary: modern motherboards boot with UEFI. The BIOS looks to mount a drive with an EFI System Partition (ESP) on it. The ESP is a fat32 filesystem with signed .efi blobs that are executed. GRUB’s update tool (run in user space when installing itself or new kernels) creates an ESP with GRUB EFIs on it. When loaded, GRUB in turn loads the Linux kernel and runs it. The rest of these notes are more confused because I took them while I was learning all this.

First off, can you just turn all this UEFI stuff off? Maybe. ASUS motherboards have ways to turn off “safe boot” (which I think means ignore keys) and enable “compatibility support module” which disables UEFI. However CSM mode does not work with Intel integrated graphics. The option to do that is greyed out. I also have no option to just turn off safe boot. I think no CSM means I can’t boot from an MBR, I must have GPT partitioned disks. And no way to turn off safe boot means whatever I want to boot via GPT/UEFI must be a signed binary blessed by the spirit of Ballmer himself. I did see some references that if you deleted all the secure keys in ASUS BIOS that would enable booting anything unsigned, but I was too scared to try.

But I got ahead of myself. What are MBR and GPT? Those are two ways to create partition tables on a PC hard drive. MBR is the old way and partitions are marked with very sparse data (like a single byte for type); see BIOS boot partition for more info. (I can swear in the very olden days you didn’t need a boot partition at all; LILO’s bootstrap was tiny but enough to load the kernel off the root partition). GPT is the modern way. It’s the GUID Partition Table, so everything has verbose GUID names. There’s no reason to use MBR any more on PCs. GPT is some 20 years old, ubiquitous, cleaner, has no weird size limits, and is now required for complicated things. In Linux you can see what kind of partition table you have with parted -l.

I just set up Ubuntu on a new hard drive (USB, spinning) and let it install. It created two partitions. /dev/sdb2 is what I expected, a big disk formatted with ext4 with my Linux root filesystem. /dev/sdb1 is a boot partition; 537MB, FAT32, named “EFI System Partition” with the flags “boot, ESP”. That’s the EFI System Partition.

What’s on the ESP? You can mount it just like any fat32 file system. Inside are directories EFI/BOOT and EFI/ubuntu. Apparently this is all UEFI boot stuff, various .EFI files have signatures checked and then are loaded and run. Some details here. The Ubuntu directory has a couple of small GRUB config files and what I think must be a copy of the GRUB executable itself.

So now we get to UEFI itself. Useful resources for that: Ubuntu docs, Arch Wiki, Arch Wiki: GRUB, Wikipedia, Windows Boot and UEFI, this Stack answer. For something more complex see this proposal for a new secure boot.

Greatly simplified, my understanding is UEFI’s job is to find boot code someone installed and run it. The UEFI BIOS finds a boot manager (perhaps chosen from the BIOS boot menu or set up via a command line tool like efibootmgr), which then finds a boot loader like GRUB, which then loads the operating system kernel. In theory all this stuff works on both MBR and GPT file systems but in practice you usually see UEFI used with GPT. Note that UEFI is basically a whole operating system with its own shell. One fancy thing you’ll see is the BIOS logo on the screen along with the Ubuntu screen and a loading spinner as various parts of the boot process are all drawing on the screen.

One Linux I installed ended up telling the existing Windows Boot Manager on my SSD about the GRUB boot loader for my new Ubuntu install on a USB drive. I think Ubuntu chose that because I already had Windows on the system. The BIOS menu let me choose which of the two OSes to launch but the Windows Boot Manager was in the path of the process. In another case I had no OS at all and Ubuntu just put GRUB directly on the USB drive; I guess it was acting both as boot manager and boot loader? “Manager” vs “Loader” is not used consistently in the stuff I’ve read, so I may have the details wrong.

From Linux’ point of view, all this UEFI rigamarole is to boot GRUB. GRUB is basically a mini operating system whose job it is to launch the Linux kernel. (There was an older GRUB v1; all modern systems are using GRUB 2.) I don’t really understand GRUB very well, it has menus you can configure to do complicated things and behind the scenes has enough code to find and load the kernel from a bunch of different device types. So it loads that kernel and hands off control to it.

If this all sounds overly complicated it is. BIOS picks a boot loader which runs GRUB which picks a Linux kernel to load? It’s possible to bypass GRUB entirely and have Linux load directly with EFISTUB. I find GRUB sort of comforting though and see no reason to remove it. It’s the way Ubuntu prefers to let you choose between kernels when booting.

First practical question; is your Linux system booting via UEFI? These docs have a nice hint; look for the presence of a /sys/firmware/efi directory. Another way to tell is use parted and look at flags; my UEFI boot partition is flagged boot, esp whereas my MPT style boot partition is flagged bios_grub.

Second practical question: how do I update / install UEFI booting? There are procedures for converting a system to boot via UEFI, see the Ubuntu docs. They sound scary. They reference a tool called Boot Repair which is a handy rescue disc. It has a sort of wizard which is basically “fix my boot”. It’s also 4 years old but is apparently still the recommended tool? The Ubuntu Server install ISO also has a repair mode.

Third practical question: is secure boot really an obstacle? I don’t think so. Modern Linux distributions have some signed shim that allows the Linux boot code to pass the security checks. I have no idea how this works or why it’s considered acceptable in the face of malware. But I think in practice if a Linux tool installs an ESP at all, it will have the needed signatures.

Update: an August 2022 update has revoked a bunch of signing keys, rendering some systems signed with older keys unbootable. Including Ubuntu 20.04 (reportedly).

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.

Renaming git’s default branch

Here’s how to change git’s default branch for new projects to the name “main” to avoid unpleasant language. This will eventually become the default.

Run this code once in a shell. This will persist a change in your .gitconfig file.

git config --global init.defaultBranch main

To rename existing branches on a local repo it’s as simple as

git branch -m master main

Updating a remote branch name is a little more complicated.

Desktop feed readers

While working on my Atom feed for the linkblog I was frustrated I had no way to preview a feed. The only reader I knew about was Feedly, the hosted app, and they don’t have a way to say “reload this feed” to easily see changes. I couldn’t find a modern desktop client feed reader at all. Turns out there’s a few, here’s three I tried.

  • QuiteRSS: simple, no nonsense. Last release was April 2020. There’s a fork with a little more tinkering but it’s not a lively project.
  • SeaMonkey: the continuation of the old Mozilla hairball of Internet apps. It has a decent feed reader. And active development.
  • LifeRea: a Linux app. Works in WSLg. Actively developed.

I used this to diagnose a formatting issue with my atom feed. My summaries are now HTML but I wasn’t really formatting them as HTML with <p> tags and the like so the images were being inlined in an ugly way. Fixed now.

Python and Ubuntu versions

I’m upgrading from Ubuntu 20.04 to 22.04 which means Python versions are changing. Ubuntu 20.04’s last version they distribute is Python 3.9. Ubuntu 22.04 starts with Python 3.10. My own code isn’t particularly version sensitive but venv makes it a mess. I’ve chosen to go ahead and move to Python 3.10 for everything.

My main problem is when you create a virtual environment it’s locked to a specific verison of Python. All venv is doing is installing stuff to venv/lib/python3.9 or whatever. If you created the venv in python3.9 and try to use it with python3.10, it will not work. So you have two choices: either rebuild the venv for the Python version you have, or install the Python version the venv was set up for.

Installing Python versions is very easy thanks to the deadsnakes PPA. They port older and newer versions of Python to older and newer Ubuntu. Their 3.10 build works just fine in Ubuntu 20.04.

The other problem is the venv needs to have been set up to invoke the right Python binary. If you create a venv with python -m venv venv, then the important symlink in venv/bin/ will be to /usr/bin/python. No version number. But the rest of the venv is version specific, so that’s really the wrong thing. The solution is to create the venv with python3.10 -m venv venv. That way the symlink for the binary is to /usr/bin/python3.10 which will work whatever a system’s default Python version is. Also pays to be careful with pip; I now invoke pip as python3.10 -m pip instead of relying on /usr/bin/pip or whatever.

Here’s my “create venv” bash function now

python3.10 -m venv venv;
source venv/bin/activate;
python3.10 -m pip install -U setuptools pip wheel

Setting up a second WSL distribution

I want to switch from Ubuntu 20.04 to 22.04 on my WSL system. But I’m cautious, so my plan is to install a second WSL image and move my stuff over. Maybe there’s an easier way, but here’s what I did. Installing a first distribution is easy btw, the trick is getting a second without clobbering the first.

Step 1: install second distribution. I followed the procedure here. It boils down to downloading an Ubuntu cloud tarball and using wsl.exe to install it. WSL’s installer puts distributions in C:\Users\Nelson\AppData\Local\Packages so I put the new one there too.

Step 2: set up a user. The distro from step 1 works fine but you’re root. I followed the procedure here. It boils down to using adduser to create the user, then editing /etc/wsl.conf to make that user the default. Note that WSL configuration changes apparently take 8 seconds to apply.

Step 3: copy over your home directory files. There’s no easy and efficient way to access files from one WSL distro in another. So I went way old school and used tar over netcat for /home/nelson. Sometimes the old ways are the best ways.

Step 4: change default distribution. wsl.exe --default sets this for WSL as a whole; I also had to configure which distribution to launch in Windows Terminal.

It’d be nice if my home directory were a separate virtual disk instead of buried inside the WSL image. Some quick Googling suggests it might be possible but it involves an extra mount process and I worry it might not be 100% reliable. There are ways to access other WSL distributions or files from a Windows folder but they seem to involve localhost network mounts (via 9p) or other inefficient things.

Given WSL2 is just a fancy wrapper around virtual machines it seems like this whole process could be a lot simpler and more explicit. But the WSL team came at this from a different direction; “make a Linux program work just like a Windows program on Windows” instead of “manage a library of virtual machines”.