Some Bits: Nelson's log

86 posts in 2022

Nest is a bad product

A few years ago I bought the hype and installed a Nest thermostat. Bad choice; it’s a terrible product. I finally made it vaguely acceptable by disabling all the “smart” learning features and using it as a simple programmable thermostat. It works OK except all the times it fails, like when the Nest website is down or the time they shipped bad firmware that drained the battery necessitating you pull the thing off the wall to recharge it with a USB cable before your heater worked.

Anyway, I thought I had it fixed. Now I looked at the dumb message inbox I haven’t looked at in a year+ and see this:

Those top two messages are telling me they changed something. (The other messages are spam). Notice the lack of any notification on what changed. No idea; did they edit my schedule? What did they do? The times look the same as I’ve always had but I think I used to have it programmed to 68? I’m not sure, I stopped remembering because I had set it correctly and was comfortable.

Nest’s big claim is it saves you money and saves the environment. It does this by making you colder. I’m all for saving money and the environment. I wear a Jimmy Carter sweater. I programmed my thermostat for the right temperature for me. And now apparently Nest has decided it knows better. By making me colder. Maybe? There’s no way even know what change it made.

Update: I’m cold

A month later and I’m pretty sure Google changed my schedule on me. I’ve been cold every day. I finally reprogrammed my temperature to 68. (Which took about 30 clicks; the web UI is very awkward.)

Looking at the notifications I got I see now this is Seasonal Savings. To be fair, the docs are pretty good and claim that the feature is opt-in. I don’t recall opting in but, eh, maybe? Anyway I think this was enabled and changed the temperatures on me, both the daytime from 68 to 67 and night time from.. 62? I don’t remember .. to 59.

I think this may even be a good feature: it both saves individuals’ money and helps mitigate CO2 pollution globally. My real complaint is more about the notification. The messages only show up in some notification queue I long since disabled because it’s full of marketing spam. And the messages don’t tell me what changes it made, just that it changed something. Both problems are fixable if someone had the right product idea.

(PS: I tried asking support for help and it was a frustratingly useless experience. He kept pasting in canned replies about resetting my entire schedule and reprogramming it. The agent never once suggested it might be “seasonal savings”.)

Starlink’s bad hours

Starlink performance continues to degrade. They’ve gone from promising 100 Mbps to 50 Mbps to now 20 Mbps. And they can’t even deliver that.

I run a speed test every hour. Graphing the average for the day is misleading because the service runs very well at 3am, often 200 Mbps! What I care about is the bad hours which are pretty much every evening. To that end I have a new graph, a count of the number of hours where the download speed measured is under 20 Mbps.

Those two bad days around 11/19 are an anomaly; my router had failed over to my slower backup connection and didn’t switch back (a router bug). The rest of the data is good. For comparison, here are graphs of minimum daily bandwidth (ie: the worst hour) and average.

This is what an overloaded ISP looks like.

I have data going back almost two years. Not confident this is correct; I used to do more speedtests a day so my naive count means that numbers are overreported a year+ ago, particularly last December. Here’s a graph of 10 months which shows an increasing trend of bad hours. (I suspect 4 or 5 of the worst days here are during failover to backup.)

Starlink dishes reorienting

Starlink seems to be re-orienting dishes on the US coasts to point somewhat over the ocean.

Starlink’s dish has motors for self-orienting. Typically it’s pretty static; mine oriented once at startup and I don’t think moved for over a year. Due north or south seemed optimal.

But recently on Reddit a lot of people are reporting that their dishes are now pointing somewhat to the west or east. No reliable reports on how much. But the pattern looks like it’s US folks, and Dishy is now trying to get a view over the oceans. Presumably as a congestion avoidance mechanism; there should be more unused capacity out there. I can’t imagine it makes a huge difference but I don’t really know.

The problem is Dishy seems to be choosing a new orientation without regard to obstructions. Many reports that their install used to work fine and now is pointing at a tree and has outages. Some very annoyed folks who spent real money mounting the thing or removing trees. There’s no way to override where it points, either, short of breaking the motors. What’s weird is Dishy has a map of obstructions; it knows there’s a tree there. Maybe they’ll eventually get to optimizing with that data too.

I thought my own dish moved to point to the west. But now I’m not sure; I just measured with a compass and it may be pointing at 355 degrees instead of 0, but not much. Unfortunately I can’t access the Dishy diagnostic data at 192.168.100.100 because I can’t get my stupid Ubiquiti router to add the static route. There’s been a bug for years where static routes don’t work with WAN failover. But that static route used to at least work for a few hours, now it’s entirely broken.

zstandard as gzip replacement for files

Some notes on how to use the zstandard compression system for files as a replacement for gzip. I spent a lot of time looking for subtle but important differences but really zstadnard is quite easy. zstandard files are named “.zst” instead of “.gz” and there are command line tools that are mostly equivalents for gzip.

  • gzip -> zstd --rm
  • gunzip -> unzstd
  • zcat -> zstdcat
  • tar czf -> tar --zstd -cf
  • tar xzf -> tar xaf
  • pigz -> zstdmt

Why use zstandard? Because it is much faster and smaller. I’ve used gzip for years and years to compress files. (I am old enough to have used BSD compress and have the .Z files to prove it.) I briefly used bzip2 but it just took way too long to compress to be worth it. I also use pigz when I remember too, the parallel gzip, and that is a lot better. But, eh, what about the new hotness?

zstandard seems mostly to be an algorithm product. the zstd(1) command line tool is pretty good though and is thoughtfully documented. It mostly does the things you want with files, preserving timestamps and permissions and such. he one important difference is that zstd does not remove the original uncompressed source file, unlike gzip. There’s a --rm option to zstd if you want that behavior.

The default compression level of 3 is fine. I assume it’s the default for a reason. Higher levels get slower very rapidly for not a huge advantage. Using the 100MB Wikipedia corpus from this benchmark the highest normal level 19 makes a file that’s 25% smaller but takes 100 times as long. Some quickie data:

AlgorithmCompression ratioCompression speed
source10
zstd -32.809201 MB/s
zstd -93.7101.92 MB/s
gzip2.73925 MB/s
gzip -92.74419 MB/s
bzip23.44716 M B/s

zstdmt or pzstd for parallelism. Much like pigz, it’s possible to compress with zstandard in parallel. pigz compresses my test data in 9% of the time of single threaded gzip; 11x speedup for a 16 thread Ryzon 3700. Both pzstd and zstdmt take 20% of the time of single thread zstandard. Not sure why it’s not better than that, didn’t dive deep. zstdmt produces a file that’s identical to single threaded zstd. pzstd makes a very slightly bigger file; I’m guessing it’s doing a block approach like pigz does.

Recovery from corruption may be a weak point for zstandard. One nice thing about gzip is that it compresses in chunks. If one byte is corrupted in a gzip you don’t lose the whole file, you can use gzrecover or gzrt and maybe get most of your data back. (This chunking is also how pigz parallelizes). I’ve actually done this for real once and was grateful to get most of my tarball back. I don’t think zstd(1) has any equivalent behavior by default, and this GitHub issue suggests the zstd team thinks it’s out of scope. There is block chunking via the -B flag (and probably pzstd) but in the absence of an open source recovery program I wouldn’t count on it.

I see no reason to not use zstandard everywhere instead of gzip. Except habit, and I suspect in reality I won’t change my behavior unless it’s something where it really matters.

Fixing Samba for Sonos v1 (Ubuntu 22.04, 22.10)

To make Samba in Ubuntu 22.04 jammy and 22.10 kinetic work with Sonos v1, add these lines to the global config:

server min protocol = NT1
unix extensions = no

On Sonos the login works fine with a blank username and blank password (assuming your music volume is a guest volume). I think username guest, password blank also works.

That first line has been necessary for awhile because Sonos v1 has an ancient SMBv1 client baked into it and the company won’t update it. The second line about unix extensions is new; it wasn’t necessary in the Samba included in Ubuntu 20.04. I don’t know what changed. Ubuntu 20.04 uses 2:4.13.17~dfsg-0ubuntu1.20.04.1; Ubuntu 22.04 installs 2:4.15.9+dfsg-0ubuntu0.3.

I think the “unix extensions = no” setting is reasonably safe. The docs suggest it does something to make Unix SMB clients happier; I don’t have any of those.

I’ve been low-key chasing a problem for months. It’s been super frustrating. So much so I even considered creating an alternate server. I don’t know if the problem is a change in Samba itself or if it’s specific to the Ubuntu build. I build Samba 4.17.3 from source on Ubuntu 22.10 and had this problem, so that suggests a change of behavior in the sources.

The unix extensions config options seems to have to be in [global]; it didn’t work to put it in the share definition. Here’s the full share definition I am using:

[musicshare]
follow symlinks = yes
wide links = yes
path = /home/nelson/Music
read only = yes
printable = no
guest ok = yes

The stuff in there about symlinks and wide links might not work with unix extensions turned off.

Starlink terrible customer communications

I realized at some point my primary gripe with Starlink is how bad they are at communicating with customers. I actually like my service. It’s not delivering to the level they promise but it’s still pretty good and better than my other options. It’s a freakin’ technical marvel, too. I’d be a lot more understanding if they just communicated. But they are terrible at that; no proactive communication with customers, no information on the website, and famously no press department. It’s very hard to know what’s going on.

The latest snafu is the data caps. After announcing they’d go into effect in December, the rumor on Reddit is that they’ve changed the plan and now it’s February 2023. Several folks have reported emails saying as much. I never got one. I got an email Nov 4 saying the caps would go into effect in December. That’s it.

The cap announcement was botched. After a year+ of promising 100 Mbps service and no caps, suddenly they quietly updated the TOS on the site to indicate only 20 Mbps and a 1TB cap. No proactive communication. A week or two later they emailed The New Arrangement to us. Lower service promise, same price, take it or leave it. Then they had to email a bunch of people a second time to say “oh we made a mistake and we were wrong about your previous usage”. Oops.

Starlink’s website says literally nothing about IPv6 support. It doesn’t support it. Or at least, it hasn’t; but recently there’s evidence that a good chunk of Starlink customers now have IPv6 enabled. But absolutely not a whisper about it to the customers.

Customer support is notoriously awful. There’s no phone number or email address. You used to be able to submit a request in the mobile app reasonably easily. Now it’s apparently hidden behind you having to read a bunch of FAQ entries and then pressing a thumbs down “this doesn’t help me” before you’re allowed to make a request. Customers report very mixed results. Sometimes great instant service. Sometimes a week + before any reply and then the reply is low quality. Not for complicated questions, basic things like “why did you not ship my order?” or “my dish arrived dead on arrival”.

All this is basic “tell your customers what their service is” stuff. It’s remarkable how bad they’re failing at it. Not to mention anything forward-looking like plans for improved service in the future.

PS: I should add that I helped start a community list of firmware versions because there was zero info on software versions. Honestly all we can track is version IDs and dates released but at least it’s something.

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.

A Sonos v1 SMB server

Summary: do you need a SMB server to serve your local library of music files to your v1 Sonos? Barry de Graaff has a solution, sonossmb. It’s a small Node implementation of SMB that works with Sonos. It works! It does take a bit of hacking to install though.

About sonossmb

I used Samba for years to serve music to the Sonos. The problem is the v1 systems are unsupported and have an ancient insecure SMBv1 client baked into them. And starting with Ubuntu 22 (which has Samba 4.17) it no longer works with Sonos, even with the special v1 config directives. No idea what’s wrong. That got me speculating that a simple stripped down anonymous-only SMBv1 server for Sonos might be a nice product. Which is what de Graaff created!

His server is based on Adobe’s Node SMB server, a project I never heard of and looks abandoned. He tells me it mostly works with Sonos just fine. He just made one tiny change to upcase the share’s name. The packaging and installation is a little trickier. He’s got some good docs and a script but it’s still something you might need to understand Linux pretty well to get running. More on that in a bit.

One problem I ran into; Ubuntu 22 ships Node 18. And that gives an error related to SSL ciphers I think because Node dropped support for old insecure SSL clients. The workaround of export NODE_OPTIONS=--openssl-legacy-provider worked for me.

Note that the share has a name like \\192.168.0.2\PUBLIC and you must log in with the username “guest”, no password. Empty username doesn’t work.

It’d be nice if Samba could be fixed. That SSL thing makes me wonder if that’s what broke on Ubuntu 22, that they too dropped some old SSL stuff that the Sonos ancient client needs. There’s some discussion on the Samba list. One happy thing is one of the Samba developers himself has a Sonos so someone in the know may work on the problem.

Packaging, Snap.

Barry’s server works but I can’t quite use it as-is on my LAN. I really need a full Samba server too. But I only have a single Linux box. And SMB doesn’t work well other than on a single port, 445. Some clients do work on other ports but I haven’t tested it with Sonos and am pessimistic. Maybe I need to just add a second IP address to my server and bind the special Sonos server there, but yuck.

All the drama of getting the thing installed makes me think a Snap container / image is the perfect way to run this server. There’s a snap for the web server Caddy so a daemon that accesses local files and serves them on the network is possible in Snap. But I’ve never built a Snap and have no idea how hard it’d be. I guess Docker would work too but Snap seems to be the choice for consumers on Ubuntu systems so I think starting there makes sense. I may give a go at building a Snap, we’ll see.

adobe/node-smb-server patch

Here’s the patch Barry sent me to upcase filenames:

diff -Naur node-smb-server-master/lib/smb/cmd/tree_connect_andx.js sonos-smb/lib/smb/cmd/tree_connect_andx.js
--- node-smb-server-master/lib/smb/cmd/tree_connect_andx.js	2021-06-22 17:20:12.000000000 +0200
+++ sonos-smb/lib/smb/cmd/tree_connect_andx.js	2022-12-09 08:21:10.674527000 +0100
@@ -10,6 +10,10 @@
  *  governing permissions and limitations under the License.
  */
 
+/* As required by original License I hereby notify you that I have made changes to this file.
+ * Copyright (C) 2022 Barry de Graaff
+ * */
+
 'use strict';
 
 var put = require('put');
@@ -76,7 +80,7 @@
 
   logger.debug('[%s] flags: %s, password: %s, service: %s, path: %s', SMB.COMMAND_TO_STRING[commandId].toUpperCase(), msg.flags.toString(2), msg.password.toString('hex'), msg.service, msg.path);
 
-  var shareName = msg.path.substring(msg.path.lastIndexOf('\\') + 1);
+  var shareName = msg.path.substring(msg.path.lastIndexOf('\\') + 1).toUpperCase();
   var shareLevelPassword = utils.bufferEquals(msg.password, Buffer.from([ 0x00 ])) ? null : msg.password;
   if (_.indexOf(server.getShareNames(), shareName) === -1) {
     result = {

Ubuntu vs NodeJS versions

Node seems to have some serious stability problems; various apps are sensitive to which version of Node you run. Here’s some recent versions:

  • Ubuntu 22.10 / kinetic: 18.7.0
  • 22.04 / jammy: 12.22.9
  • 20.04 / focal: 10.19.0

Nodesource packages different versions of NodeJS for Ubuntu. It’s basically a PPA but they want you to use their shell script to install them.

I ran into a problem with Nodesource where “apt install” really wanted to keep installing Ubuntu’s 18.7 despite having a PPA. I fixed that with apt install nodejs=14.21.1-deb-1nodesource1 to select a specific version.

Starlink performance last week: 5mbps

Just making a note of a recent performance graph.

Nothing new here, this congestion pattern has been happening for months. But it gets worse and worse. There’s some tiny hope that the new throttling system will help free up some bandwidth for me, at least until I myself am throttled. That was supposed to launch early December but now apparently is pushed back to February.

ActivityPub servers

I want an ActivityPub server so I can do Fediverse experiments and see them in Mastodon. What I really want is something like CGI; I don’t care about the protocol server, I just want to write little scripts that easily federate. I don’t want a consumer product with a web UI, I want a little platform for which I can create experimental scripted accounts for people to subscribe to. I’m not sure that exists.

I asked on Mastodon about servers and got some suggestions. Here they are. Lines of code are rough estimated calculated with scc.

takahe. 9,000 lines of Python. Active, seems very new (2 months old), not yet at a 1.0 release. Seems web UI centric.

gotosocial. 58,000 lines of Go. Active, six months old, labelled “alpha”. Also focussed on a web UI and consumer product.

epicyon. 103,000 lines of Python. Active, 3.5 years old. Also web based but an emphasis on being simple. OTOH runs as a proxy server and needs nginx in front.

honk. 10,000 lines of Go, 3.5 years old. Not entirely active, but has had some recent updates. Seems.. idiosyncratic. But also nicely minimalist. Someone mentioned it has lots of forks.

minipub. 7200 lines of Typescript+Javascript. A year old, but no edits in 6 months, maybe one developer. “for posting federated podcast comments”.

minimal-activitypub, 650 lines of Python, 4 months old, one author. Found this one myself and as the name says, it’s minimal. May be a suitable start for the platform I want? I note from the docs that it’s all client to server stuff, not server to server, and I don’t even understand enough about ActivityPub to know exactly what that might mean. There’s a couple of the author’s projects built on top of it.

express-activitypub. 440 lines of Javascript, 4 years old, one author and seems largely moribund. OTOH it’s by the great Darius Kazemi, ActivityPubber extraordinaire, so it’s worth a look. Darius says his projects are live, just stable.

rss-to-activitypub. 700 lines of Javascript, 4 years old, also Darius and mostly moribund? But this specific RSS product is very close to what I want to tinker with, also worth revisiting.

snac2, 6000 lines of C. Two months old, active but maybe just one developer. Has a simple web interface. Mostly runs like an old school Unix daemon, this post talks about setup. The earlier snac was a prototype in 3800 lines of Python written in six weeks.

microblog.pub. 13,000 lines of Python. 5 months old (v2), active. Simple web UI. Single user, minimalist, blog-oriented. This looks promising as a starting point for me.

notes. Ruby, new, experimental.

6 static files. 0 lines of code, just some static JSON. Not a real server but a nice demonstration of a very very simple ActivityPub participant. The writeup notes that you have to accept POST requests to handle people following you, so that takes a little code.

Playing with ActivityPub, tmcw’s article about writing his own very simple ActivityPub instance. Describes the complexity required.

How to implement a basic ActivityPub server: notes from 2018.

Adding ActivityPub to your static site.

None of these are an obvious thing for me to Just Use.

Battery backups: UPS, battery generators, etc

I’ve learned a surprising amount about how to have battery power for when the AC power goes out. Some summary notes.

One important stat: “transfer time”. That’s how long it takes for the backup power to kick in. You need this to be fast if you don’t want the device to turn off and on again. For reference, 60Hz power cycles every 16ms. UPS units are the only ones I know of fast enough that a computer won’t be interrupted when the power goes out. You can use a UPS along with one of the bigger and slower backups.

Many of us have good ol’ UPS units to keep our computers up in momentary power outages. My favorite consumer brand is Cyberpower. These are typically sold by max power + runtime and it’s hard to find how many watt-hours are actually in the battery. There’s a surprising variety of types of UPS units. I now buy PFC Sinewave units that condition the AC power and produce a nice clean wave. As a side effect this makes the UPS work better when on dirty power like a generator; with a cheaper UPS on generator it would switch to battery backup every few minutes. Transfer time on a UPS is < 10ms and consumer devices shouldn’t even notice.

Gas or propane generators. I have a Generac Guardian 22kW for when PG&E takes our power out for hours or days. These are expensive and terribly inefficient, particularly when running at low power. They also put out pretty uneven power; when they get loaded the 60Hz briefly slows down to 58Hz or whatever. But if you need to be off-grid for days at a time they are the most practical choice. I paid $15,000 for mine. It’s rated for 3000 hours, so that’s $5 / hour! Although presumably it can be refurbished? Transfer time is ~15 seconds, everything will turn off before it switches on.

Battery generators. These are a new class of product that replace portable gas generators, basically a very fancy lithium battery with an inverter. I have an EcoFlow Delta 1300 that PG&E gave me to avoid liability for my power going out. These are really capable devices, absolutely excellent for being off-grid for a few hours. They charge via AC and also come with the circuitry to charge via solar panels or electric car chargers. I’m impressed with mine as a product. One drawback; you need to drain the battery occasionally to avoid it wearing out. Also the transfer time is 30 ms; fast, but not fast enough to keep your computer on. It’s not a UPS.

Whole house batteries. These are the fancy things like the Tesla Powerwall. I don’t have one but wish I did. They’re expensive as backup power, a gas generator is a lot cheaper. I’d particularly like to have a small battery, just like 4000Wh of capacity or something. Enough to bridge an hour long power gap and let me keep my solar running; during the day I can charge it faster than I’d use the power. Last I looked no one made a small product like this. Not sure about transfer time; I think the Tesla Powerwall is slow enough everything is turned off briefly.

One extra note: all these systems I use are focussed on providing AC power. But 90% of what I care about plugged into it runs off DC power, it’s dumb to have a battery, an inverter to produce AC, and then a transformer to swap back to DC. The EcoFlow Delta has serious USB charging circuits. I suspect it’d be possible to get adapters to power things like network routers off those USB ports and that might be more efficient.

Verizon’s terrible systems

No surprise, a mobile phone company’s service sucks. Still worth documenting. I took a trip to Austria. I paid Verizon $100 for an international calling plan with more minutes and data than I could use. It mostly worked fine, but one day I made a phone call and got a message about it being billed at $1.99/minute as an international call. Weird, it should have been included in my plan. The slight wrinkle here is I was using WiFi calling from my hotel in Austria (and no VPN). But surely that shouldn’t matter?

I guess it did. This showed up on my bill:

It’s not in the bill, but the website and the customer support agent see a note that it’s for activity in January. On my October bill. I made the call in October.

I decided to waste my time to get a refund for that $1.99. It went as well as you might expect. But what really kills me is how bad Verizon’s product is.

I submitted a ticket and asked for email response. I’m getting text message response instead. My attempts to reply to the text message are silently dropped. I can’t submit responses on the website either; the submit button does nothing. (I do see an event fired in the Javascript console, but the message is dropped.) I tried two browsers. I tried editing my ticket to use a different contact method, that also failed.

I tried logging in again in a new browser. I had to verify, some 2FAish thing. I get a text message saying “click here to verify”, which I do. Meanwhile the login website is asking for a code, one never given to me by the 2FA side path. I submit a blank code and am logged in.

The website creating the ticket had numerous typos. The subject for the email they sent me is “, we received your support request.” I guess my name was supposed to be before the comma? The first message from the agent said “your concern with the INternational call. nI know how important this is for you.” Presumably they’re using canned responses; do they have typos in them?

The second message from the agent was about someone else’s bill entirely. 5 minutes later they told me to disregard it.

I have another Austrian call itemized on my bill that is attributed to Canada. It seems to be confusing the 431 area code with +43 1, phone numbers in Vienna. Are they using regex to decide which country I called? At least I did not get billed for this one.

I finally gave up and got someone on the phone. They looked and quickly agreed to refund the charge. As they should; $1.99 is not worth their time. Or mine, but it’s the principle of the thing.

I realize how boring this rant is, my apologies. It’s just astonishing to me that I have a fairly ordinary interaction with a consumer product used by millions of people. And in every single point along the way I see signs of the company just not giving a shit. Typos in canned messages, failed database merges in outbound messages, dropping inbound messages on the floor, a confusing or broken login system, mistaken billing, a high schooler’s idea of how to identify what country a call was made to. Does no one competent at Verizon care?

Search web pages I’ve seen

For 20+ years I’ve wanted the ability to search the web pages I’ve seen. Simple full text search on page contents, maybe also on some metadata like page title and the text of links to the page. You’d think this would be simple but it’s not. There’s 20+ years of systems that claim to do this that no longer work. It’s a cursed product category.

Firefox has some built in history search but it’s terrible; not sure what it is searching but it’s definitely not the full text of every page. Also a lot of pages are missing from it. Still the history database could be useful to feed to some other tool. It’s in a sqlite file in the user profile.

There’s a March 2022 discussion of tools for this. I read it all and was discouraged; it’s clear there’s no good solid product. I sifted through all the discussions and settled on two options: ArchiveBox with some custom scripting to import browsing history or else Recoll with an addon to capture browsing history.

I looked at Recoll and gave up. The Windows build requires payment to download, there’s no easy way to try it first. And the website says the Windows version has indexing limitations. I need a solid Windows program.

ArchiveBox could be promising. But the desktop app is Electron, marked “alpha”, and requires Docker to run. There’s an Ubuntu headless version but they only provide a PPA for 20.04, a 2.5 year old Ubuntu release. The install instrnuctions have you installing stuff globally with pip. I quit at that point.

I’m being cranky here but I really want a clean product for this function, not some hackerware. Or if it’s going to be hackerware I’d rather roll my own.

One subtlety; it’s not really enough to just get URLs and download them again. You really want the text as rendered in the user’s browser, to catch login data. Even with that it’s not going to be perfect unless you really snapshot the whole page; the sensible thing of giving back a URL from the search engine has the same problem that the URL now may not look like the URL then.

Update: this isn’t a search tool, but NirSoft’s BrowsingHistoryView is a nice table viewer for browser history. Much nicer than Firefox’s built in view.

BrowserParrot looks promising but is Mac only. Can’t tell if the project is active or not.

HeyDay also looks interesting. It’s more AIish than a simple search engine but might be helpful. $19/mo. Update 2: I tried HeyDay and it is not for me. It’s definitely doing something with my browser history. But it requires more active involvement than I want. It keeps asking me to categorize pages I’ve seen into topics, way more labor than I want to perform. It does do some stuff passively; popups on pages and in Google searches saying “hey, this is like this other thing you looked at”. Which in theory might be nice but so far the suggestions have been intrusive, not helpful. The UI is pretty demanding. All in all, not for me.

Update 3: I have failed to find a product that will do this for me. I’m doing a tiny bit better with Firefox history though. The key was changing the sort order from “by Date” to “by Last Visited” so now my results are in reverse chronological order, which makes it much easier to find again that thing I saw yesterday.

Blocking control-mousewheel in browsers

For whatever reason I find myself accidentally inputting control-mousewheel events in my browsers a lot. In both Chrome and Firefox this changes the zoom level of the page, something I pretty much never intend to do. (And if I do, I use Ctrl-Plus and Ctrl-Minus instead.) One fix for this I’ve been using for years is a small AutoHotKey script that captures those events and cancels them.

#IfWinActive ahk_class Chrome_WidgetWin_1
{
    ^WheelDown::return 
    ^WheelUp::return
    #MaxHotkeysPerInterval 1000
}

#IfWinActive ahk_class MozillaWindowClass
{
    ^WheelDown::return 
    ^WheelUp::return
    #MaxHotkeysPerInterval 1000
}

The ahk_class of a window can be found with the “Windows Spy” program that’s included with AHK.

Starlink service degraded: 20Mbps, 1TB data cap

Ugly changes in the Terms of Service for Starlink: residential customers have been degraded to 20-100Mbps expected download (from 50-200). Uploads are now 5-15, down from 10-20. Latency has also crept up: 25-50ms now, not 20-40. And a new unwelcome feature, a 1TB / month soft data cap before speeds are further degraded.

Starlink sure has fallen a long way from “no data caps! great latency for gaming! 100+Mbps!”. OTOH this new service level is at least closer to what they actually deliver. Over the last 90 days I’ve been getting 90Mbps average download speed with nightly slowdowns to 10Mbps. Uploads of 6.6Mbps and latency 55ms.

TBH the data cap is not a disaster; the average American household uses 513GB / mo although 15% use 1TB or more. It’s a soft cap, you get degraded to 5-50Mbps if you go over (or you can buy more). And the 1TB cap is defined in terms of “peak hours” but then that’s 7am to 11pm, or the 16 hours people are awake. I can make good use of the uncapped hours though with automated downloads.

What I don’t like about caps is how opaque they are to users. Starlink has added a daily usage graph so you can at least see what you’re using. But there’s no way to see what is using your data. And ordinary users don’t have tools to manage data usage; there’s no good way to use less.

Starlink still hasn’t communicated anything to its customers, we only know about this change from a TOS update. It seems unlikely we’ll get any sort of price break, just expected to accept the degraded service. Update now there’s an email to customers over the cap. Also a link to their so-called “Fair Use Policy” which explains the throttling.

Update 2: they sure botched this rollout. They emailed customers whether they had been over cap in the past but told a bunch of people the wrong thing, so sent a second email correcting it. They also told business users they would be throttled to 1 Mbps; obvious nonsense, but again required a correction. And all that on top of the original, probably mistaken quiet non-announcement via a TOS update.

For the record: archive links for Oct 6 2022 (pre-cap) and Nov 4 2022 (with cap).

WiFi channel 13

I can’t figure out how to make my American equipment connect to WiFi channel 13.

I’m at a hotel with adequate WiFi in Innsbruck. My Pixel phone connects to WiFi no problem, but my Windows 10 laptop (EdiMax and Killer Wireless adapters) and my Samsung Tablet can’t. Ken’s iPhone, iPad, and Windows 10 laptop (IBM) all do connect.

I used a scanner on my phone to figure out that the only AP near me is using Channel 13. Which is not allowed for use in the US and thus is blocked on American equipment. Usually it’s a simple software block and should work if the device realizes it’s in Europe. I tend to turn off location stuff on my computers, which may be why it works for Ken and not me. But after an hour+ of trying various settings, new drivers, etc I can’t make it work on either device. What a dumb thing.

Most online advice I found was “change your AP not to use that channel”, which is not helpful. Some Windows 10 advice is to look at Advanced device driver Properties (not registry) for a “Country Region” setting. Neither of my adapters have that. Trying to change locale settings and time zones and stuff doesn’t work. Hilariously, my Samsung tablet tells me I have to connect to WiFi to change region. But I think that’s just about video DRM anyway.

Update: another hotel with excellent 2.4GHz wifi has Channel 12 closest to me. My phone connects no problem; the laptop refuses. Fortunately there’s also service on many other channels, crazy strong actually (-50 to -60 dBm). WiFiAnalyzer on my phone seems to have a bug; I can’t always see the other channels, maybe some filter logic problem. NirSoft’s WifiInfoView on my laptop shows lots of networks on channels 1-10. Nothing at all on 11 and 12 seems invisible to me.

MicroSD card speeds simplified: V30 A2

If you want to buy a decent general purpose MicroSD card in 2022, buy something that says “V30” and “A2”. I’m happy with the Sandisk Extreme. It works pretty well as the primary disk in a Raspberry Pi and will also work for 4K video, maybe even 8K.

In detail.. There’s a confusing array of different class definitions for SD cards. Ignore “Speed Class” (2, 4, 6, 10) or UHS (1 or 3); those are obsolete. Also ignore SDXC, SDHC, and SDUC; those refer to storage capacity and you can just read the size.

The primary throughput rating on a card now is V, for Video Speed, and modern choices are V30, V60, or V90. V30 is 30Mbps and is fine for 4K video. There’s a nice chart here of speeds. Note a V30+ card will also probably be labeled “Speed Class 10” and “UHS 3”. Faster is better but you pay for it, so unless you know you need it save your money.

The only random access rating on a card is Application Performance Class and comes in two ratings: A1 or A2. There’s no real price increase for A2 so get that. This isn’t so important for recording video but means absolutely everything for use as a general hard drive, say in a phone or a Raspberry Pi. A2 isn’t so great; it’s 4000 read IOPS. Compare 600,000 IOPS for a fancy SSD. But at least it’s got a rating. Old fashioned spinning disks are more like 50-200 IOPS, so even that A2 is a big improvement over what we used to use.

The Sandisk Extreme 128GB I like is $20 for 128GB, V30, A2. Some prices for various speeds of 128GB cards from NewEgg

  • V10 A2 $13 - $17
  • V30 A1 $11 - $20
  • V30 A2 $11 - $20
  • V60 A2 $27
  • V90 A2 $100

V30 A2 is the sweet spot for performance; no point getting anything slower for general use. You pay a significant premium for V60 or V90. By all means pay that if you need it, but you probably don’t. 128GB seems to be the sweet spot for storage; 64GB cards cost almost the same.

Windows 11: 22H2 and Memory Integrity woes

More boring Windows sysadmin crap, no satisfactory conclusion.

Windows 11 22H2 came out today. I tried to install it. It gets to 37% and fails with basically no useful error message. “Window Update error code 0x80070001”. Thanks dudes. Searching for that error code is not helpful, with a bunch of cargo cult advice for a zillion different things that might be wrong.

I tried using Get-WindowsUpdateLog to give me a text file log of what went wrong but it’s impenetrably detailed. This looks like the error but I can’t imagine what is the actual problem.

2022-09-20 15:37:00.9942721 16468 23084 Deployment      *FAILED* [80070001] file = onecore\enduser\windowsupdate\client\engine\handler\osdeployment\helper\osdeploymenthelper.cpp, line = 612
2022-09-20 15:37:00.9942763 16468 23084 Deployment      *FAILED* [80070001] file = onecore\enduser\windowsupdate\client\updatedeployment\handler\osdeployment\installer\osinstaller.cpp, line = 1157
2022-09-20 15:37:01.0008701 16468 23084 Handler         Install complete for update ID: 8E409263-45B4-438D-AD01-6E9674AB032A.1 Return code is 0x80070001. Requires Reboot:No
2022-09-20 15:37:01.0008721 16468 23084 Handler         Enter deployment handler NotifyResult
2022-09-20 15:37:01.0009405 20108 24312 Deployment      Deployment job Id 51AE112D-2F4D-46DB-A0A4-381CB450EAAE : Update 8e409263-45b4-438d-ad01-6e9674ab032a.1 failure delegate invoked.
2022-09-20 15:37:01.0009697 16468 23084 Handler         Leave deployment handler NotifyResult
2022-09-20 15:37:01.0010261 16468 23084 Deployment      *FAILED* [80070001] file = onecore\enduser\windowsupdate\client\updatedeployment\handler\osdeployment\installer\osinstaller.cpp, line = 356
2022-09-20 15:37:01.0010271 16468 23084 Handler         *FAILED* [80070001] Leave deployment handler Install

So I started trying to figure out what else might be wrong with my system. One persistent problem is Windows Security claims that Memory Integrity isn’t enabled; that’s some virtualization thing to isolate processes. It wouldn’t turn on because an obsolete driver was blocking it. What driver? Some ancient Western Digital thing; I don’t even have any WD hardware on my system. It just got an update via Windows Update which resulted not only in the old version being installed but a slightly newer version also incompatible being installed. Great jerb. Anyway you can manually remove the drivers by using pnputil on the wdcsam files. I have no idea if this could break a system but I chanced it and it worked.

Well, sorta. Now I could enable memory integrity. Then it reboots to install itself and during the reboot I get a blue screen of death with something about Bug Check 0x7E, which means “System Thread Exception Not Handled”. That’s programmer speak for “shit’s fucked up, yo”. Searching online finds other people with this problem with the usual scattershot advice for fixing things and the occasional malware recommendation.

Just before then the event log had errors about IntelHaxm: “HAXM Failed to init VMX” and “HAXM can’t work on system without VT support”. I’m confused about this. I definitely have virtualization support, I’m using Hyper-V for WSL2. I don’t know about VT support. Also wondering if the Intel thing is a problem; this is an AMD Ryzen CPU. This Windows system started life on an Intel CPU and I transplanted the drive to an AMD system. Everything’s worked fine (it installs new drivers for the hardware it detects) but maybe there’s some weird vestige? Or it could be completely unrelated. I give up.

Windows 11: fixing crackling microphone

My headset plugged into my motherboard (Realtek audio) stopped working on my machine, maybe about when I upgraded to Windows 11? Not sure, but when I talked people would hear noise but just a burst of static. The fix was the re-set the format to 2 channel, 16 bit, 44100 Hz.

Windows sound drivers are an absolute mess. The fancy new Windows 11 UI works fine for basic things, but all the important stuff is still hidden in the Windows 7 Control Panel style settings. Why TF hasn’t Microsoft fully ported all the control panel stuff yet? It’s been 7 years since Windows 10 came out and yet still a lot of important settings are hidden in Windows 7 APIs.

In the end I found this guide most useful, using the local “Listen to this Device” loopback, Discord, and Google Voice to test. The web app for Google Voice bafflingly has no microphone playback / test I could find, but if you place a phone call to +1 (909) 390-0003‬ something will answer that will echo calls back to you. (Sadly this number has been tagged “Gateway to Hell” online enough that you might see that name.)

In the end my problem was the microphone device had somehow been set to 32 bits per sample. (This happened two years ago, too.) Which breaks everything not in some coherent way, but by just playing corrupted staticy audio. Nice. Windows is sure doing no favors to ordinary users letting people choose all these formats. 16 bit 44100 Hz is just fine for anyone who isn’t running a recording studio. (Or 48000 Hz; love having two nearly equivalent choices.)

Tailscale first impressions: very good

Goodness what a networking miracle. After years of failing to get VPN tunneling set up between two houses, I finally gave Tailscale a try. I thought it’d take me a few hours to get going. No: 10 minutes, tops, and I was VPNing from one house to another without regard for the NAT on one side and the Starlink double NAT on the other.

Never seen a complex networking software like this work so easily. The install experience is a dream; great clear docs, everything Just Works. Linux, Windows, Android, just install the thing, log in via Google with one click, done. I immediately could ping the new Tailscale IP address to reach my machine. There’s a great, easy to understand web console showing status of all your Tailscale hosts.

Behind the scenes it’s not magic so much as well-put-together parts. Wireguard is the underlying VPN protocol, making it easy to set up point to point tunnels. Some sophisticated NAT traversal (and relay servers) ensure everything can connect to each other. All the keys, negotiation, and naming is handled in a datastore Tailscale runs. You authenticate to Tailscale using one of many choices; Google is definitely very seamless.

The one thing I’m on the fence about with Tailscale is that it’s designed as a point-to-point VPN between hosts running Tailscale. That means that while I can access my Linux box behind NAT, I can’t access my thermostat on the same LAN directly like you’d normally expect with a router VPN. They do support full subnet routing via a Tailscale node, that seems like a big commercial feature for them, but it’s not the simple default setup. OTOH this P2P model will cover 90% of what I need to do and has some advantages aside.

I assume there’s no way to use Tailscale without trusting Tailscale itself; its software and service are in the middle. I’m fine with that but I wonder how that limits their sales to big companies. There is an open source alternative server that so far the Tailscale company has been friendly about.

Configuration

I didn’t really have to do any setup beyond install, but I did a couple of extra things.

I set up DNS aliases in a domain I own for all my hosts. Now I can connect to sfwin.ts.example.com instead of some opaque IP address. Tailscale has their own beta feature for DNS (MagicDNS) but it works by having your client machines use their DNS server instead of your own. That’s probably fine but I didn’t want to quite jump to that yet. MagicDNS will automatically add new Tailscale hosts to DNS records; I’ll have to do that manually.

I forwarded UDP port 41641 from my router to my Linux server in SF. This isn’t necessary, but I noticed that traffic between my two Linux boxes behind NAT routers was going via one of Tailscale’s relays, overhead I’d rather avoid. Tailscale does have a lot of NAT traversal, even simple UPnP would have worked, but this static forward is fine by me too. I’m not positive but I think it’s helped.

Kicking the tires

tailscale status is an invaluable command for seeing what’s going on with your peers. It prints basic status of your hosts with extra information for open links like idle, tx 820 rx 732 or active; direct 98.97.1.1:16227

tailscale ping has some tailscale-specific info. For instance this is what it looks like when I ping a host behind double NAT when the link was previously down. I’m not positive but I take this as evidence that the link first comes up via a relay in Seattle, then switches to direct connection after a few pings.

nelson @tt ~ 1 ❯ tailscale ping gvlin.ts.example.com
pong from gvlin (100.106.1.1) via DERP(sea) in 316ms
pong from gvlin (100.106.1.1) via DERP(sea) in 97ms
pong from gvlin (100.106.1.1) via DERP(sea) in 76ms
pong from gvlin (100.106.1.1) via 98.97.1.1:16227 in 224ms
nelson @tt ~ 3s ❯ tailscale ping gvlin.ts.example.com
pong from gvlin (100.106.1.1) via 98.97.1.1:16227 in 95ms

I’m curious about performance. For two hosts without Tailscale I could get about 360Mbps copying a stream of random numbers with a direct link (via ssh and rsync, so maybe some encryption involved). With tailscale I got maybe half that, 200Mbps, using 140% of CPU on the server and 80% of CPU on the client receiving the file. I did one try of a copy via a relay and maxed out at about 10Mbps; if that’s a real problem you can run your own relay server. I didn’t test packet loss or latency using iperf3 or the like, but I suspect it’s not much different than the underlying medium.

Tailscale hosts are getting addresses in the 100.64.0.0/10 block used for private networks. Boy I hope that never collides with Starlink’s use of this block! They also have IPv6 support but I’m not sure whether I’m likely to ever use those addresses.

One confusing thing; on Linux tailscale isn’t using the routing table for its VPN traffic. While there is a tailscale0 network device, there is no route shown in ip route for the 100.64.0.0/10 block. Instead it’s in the IP Tables, as iptables -S shows. I don’t really understand IP tables so I couldn’t decipher all the rules but it looks like there’s one blanket rule, not a specific rule for each destination host.

Tailscale links go down after just a little bit of disuse but come back up immediately when used. Latency for that first packet through is under one second.

Making my Windows machine part of Tailscale means the WSL Linux images running on it also can access the private VPN addresses. I believe WSL2 works entirely via forwarding through the host Windows networking, so that’s not a surprise.

Tailscale has some higher end authentication features, in particular a way to integrate ssh logins. I haven’t tried them. There’s also an alpha feature for collecting a list of “services” running on Tailscale nodes for easy access.

HVAC thermostat access: Carrier Infinity Touch

Trying to diagnose an HVAC control problem. Software details below on how to get access to data from the Carrier thermostat.

I have a very fancy central AC system with a Carrier Infinity Touch thermostat and three zones controlled by dampers. My office is in the main zone 1 and is set to 75F, but in the late morning it cools down to as low as 69. The thermostat is in another room and unfortunately right next to the bedroom zone 2, with a door between we usually leave open.

I’m able to measure a few things: the temperature from the HVAC thermostat, the temperature from a Laseregg sensor about a foot away from the thermostat, and the position of the damper for each zone (0-15, scaled to 50-65). Unfortunately I can’t get access to HVAC fan speed or how hard the compressor is working (ie, what stage).

Here’s details of zone 1 on three different days:

The key message here is with the door shut (on left), the two thermometers (blue and yellow) tracked each other’s temperature within 2F. But with the door open (on right) the divergence goes up to 5 degrees. The middle graph had me opening and closing the door during the day; not positive but basically every time the blue thermostat line dips down is when I closed the door.

I have no theory for why the two thermometers would show different temperature trends at all, or why the difference would vary depending on the door being closed. The thermostat is mounted on a wall, but I don’t think that wall is unusually hot or anything. Is it possible the thermostat isn’t reporting a simple temperature sensor but some complicated synthetic thing based on air temperature?

The other thing I learned from this experiment is what the dampers that control zone flow are doing. Zone 1 is the main room with the thermostat graphed above; zone 2 is on the other side of that door I’m opening and closing.

Three days of temperatures in zone 1 and dampers zone 1 and 2

It’s a bit messy, but the main thing this is showing is that every morning the AC isn’t even cooling zone 2 (purple), all the cold air is going to zone 1 (orange). Zone 2 comes on in the afternoon and usually zone 1 tapers off, although yesterday on the very hot day basically both zones were full open.

No clear conclusions here; I really wish I understood why the thermostat and the Laseregg thermometer diverge so much. But I do see why my office in zone 1 gets so cold in the mornings; all the air is being diverted into that zone. With the door open I suspect that cold air then bleeds into zone 2 enough the HVAC decides it doesn’t need to explicitly cool zone 2 itself. Closing the door helps with that, or maybe if I set zone 2’s temperature a little lower it’ll change things.

The real solution would be to move the zone 1 thermostat further away from zone 2.

Trying to understand all problems through my lens of software engineering is foolish. I suspect a real HVAC expert would be able to understand the problem quickly. I should call the folks who installed this, their system designer seemed good, but the techs they send out aren’t creative problem solvers.

Software details for accessing Carrier data

Here’s how I got this data from my Carrier HVAC.

The thermostat comes with a crappy website for controlling it and no API for data. Fortunately folks have hacked this; Infinitude is the key software and there’s a Home Assistant wrapper.

Infinitude is a Perl proxy server. You run it on your LAN, use the thermostat config to point it at the proxy, and now you have a MITM for recording data and control. It’s a pass-through, the Carrier Internet app still works. Infinitude has its own Web UI with status display and the ability to configure some or all of what the thermostat does. It also has an API.

Infinitude also has support for a serial interface to the thermostat with high frequency data; I didn’t mess with that. And apparently the thermostat now has MQTT support so that’s an interesting alternative that someone may hack support for. (Or not; it may be that a side effect of MQTT is that the proxy hack won’t work any more.) The discussion in that link is interesting btw, this thermostat is a much more capable system than the consumer UI would indicate.

I’m running Infinitude as a Docker image. It wants to run on port 3000 but unfortunately that’s in use for Grafana already (even in the container?!). And the entrypoint doesn’t let you override that. So I ended up having to modify the Dockerfile and build my own image. I’m launching with ./infinitude daemon -m $MODE -l http://:3030

Infinitude is not well documented. The docs promise a --help but I couldn’t make that work. Not sure what other command line arguments the thing supports. I’ve lost my ability to read Perl (to the extent Perl was ever readable) so I gave up.

There are some docs for the REST API but they are incomplete. A key API call not mentioned there is /api/status. Between that and /api/config I can get a lot of data off the device. What’s there?

There’s some device-level stuff, most of it not filled out. There’s a timestamp with a bogus timezone (-08:01 when it should be -07:00. Lol.) Most of interest is per-zone data accessible with jq with the key .zones[0].zone[0] for my living room

  • clsp, htsp: desired temperature setting (cool and heat)
  • rt, rh: room temperature (73-76) and humidity (40-41)
  • damperposition: numbers from 0 to 15. 15 is running full out, I think, but I’ve seen 10-15 and 0
  • zoneconditioning: active_cool, idle
  • currentActivity: home, manual (or sleep, etc?)
  • hold: off or on, depending on how I set it
  • otmr: 22:30, the time the current home program ends
  • enabled: always on?
  • fan: always off? (maybe manual fan control)
  • id: 1, the zone number
  • name: living room, the zone name

It seems to update at least once a minute.

What I’m not seeing here is how hard the compressor is working or how fast the fan is running. That data can be displayed in the thermostat, but it’s more a property of the HVAC itself than the thermostat. I wonder if the HVAC unit itself has a serial port you can tap for data? I’m not aware of it having any Internet access.

I didn’t look as close at /api/config, it didn’t seem very interesting. This is where the program seems to be available; times and temperatures.

starship shell prompt magic

It’s been nearly a decade since I indulged in customizing my shell prompt, so here I am. I’m trying Starship, a very nicely engineered solution that’s cross-platform.

Last time I customized things I settled on liquidprompt, a very complicated set of shell scripts that works pretty well. It shows me things like Git status, Python venv activation, whether I have suspended screen sessions.

Here’s the default starship in the same context.

The big difference is that second line; Starship wants to stuff so much stuff in the command line they wrap. (Do I really need to know the Python version?!)

The other obvious difference is the weird symbols; Starship relies on you using a Nerd Font, a regular font patched with like 4000 symbols stuffed in the Unicode private use area. I can’t decide if that’s clever or a terrible idea, AFAICT there’s no graceful fallback so if you don’t happen to have the special font you get a lot of broken glyphs. (Or else you have to have a second nerdfont-free configuation.)

But what I really like about Starship is the very clean implementation. It’s a single 8MB Rust binary. It seems to run very fast. And front-and-center in the config are timeouts for if scanning files or running a command take too long. The last thing you want is a slow prompt! That’s a real problem with liquidprompt in large Git repos.

Configurating Starship

The config file is reasonable; there’s a top level prompt which is basically “combine these modules”. And then lots of modules. For instance Python is defaulting to display

'via [${symbol}${pyenv_prefix}(${version} )(\($virtualenv\) )]($style)'

So that’s where the text “via”, the Python verison, etc is coming from. You can both override the format string itself and the values of variables like $style.

When reading through the docs pay particular attention to $format since that’s what actually displays. Also note some modules are $disabled by default. The docs are out of date with the binary I installed; starship print-config shows the current active config. There’s a bunch of other neat commands too; explain, timings, etc.

There’s a strange combination of using lots of extra text (like “via” or brackets around git status). And yet also having everything color coded, so the textual delineation is superfluous.

I can’t find a way to make general conditional behaviors. There’s support for conditionals on the empty string, and some modules are hard-coded to do conditional display (ie: only show hostname if remote). But no general purpose conditioning.

It’s quite voracious about showing language details. If you have a directory with both Python and Javascript files in it, you get “via  v18.7.0” and “via 🐍 v3.10.4” in every prompt.

git status bears some consideration. It often shows up as red !? which to me suggests an error state, but really it’s just saying “you have uncommitted work”.

My configuration

I spent most of an hour reading and tinkering and landed here.

That’s in a git repo with +3/-3 changes pending, a job in the background, and the last command exiting with status 1. This all runs in 1-2ms except for the git_metrics count of lines changed; that’s 10ms for this very small status. (git_metrics is off by default.) That’s a pretty maxi-prompt btw, this is what I get with a new local shell in my home directory

My config is below. Mostly what I did here was remove extra words like “via” or “in” from the various modules, also suppressed language version numbers entirely. No doubt I’ll keep tinkering.

add_newline = false
[line_break]
disabled = true

[username]
format = "[$user]($style)"
[hostname]
format = "[@$hostname]($style) "
[cmd_duration]
format = "[$duration]($style) "
[status]
disabled = false
symbol = ""

[git_branch]
symbol = ""
format = "[$symbol$branch(:$remote_branch) ]($style)"
ignore_branches = [ "master", "main" ]
[git_metrics]
disabled = false
[git_status]
format = '([$all_status$ahead_behind]($style) )'

[python]
format = '[($virtualenv )]($style)'
[nodejs]
disabled = true
[gcloud]
disabled = true

Rudimentary perf notes

Still working my way through learning ARM64; I can write loops now! I have my first “real” program, something which takes a 64 bit number and prints it out in hexadecimal. This got me interested in how the CPU is really running my code, which leads me to the perf tool in the Linux kernel. This is an strace or prof-like tool that monitors CPU performance counters, of which ARM64 has an awful lot.

Notes here are from a rank beginner; anyone who’s used perf before will not learn anything here.

I installed it on Raspberry Pi OS with apt install linux-perf. That installs perf_5.10 which you need to invoke with the version number; the perf shell script wrapper is trying to run perf-5.15 to match my kernel version.

$ perf_5.10 stat ./ch4printword

 Performance counter stats for './ch4printword':

              0.22 msec task-clock:u              #    0.196 CPUs utilized
                 0      context-switches:u        #    0.000 K/sec
                 0      cpu-migrations:u          #    0.000 K/sec
                 2      page-faults:u             #    0.009 M/sec
             1,611      cycles:u                  #    0.007 GHz
               167      instructions:u            #    0.10  insn per cycle
   <not supported>      branches:u
                13      branch-misses:u

       0.001135464 seconds time elapsed

       0.000000000 seconds user
       0.001426000 seconds sys

Neat! A little surprised this worked as me; let’s try it as root

$ sudo perf_5.10 stat ./ch4printword 2>&1 | grep cycles
           318,276      cycles                    #    1.720 GHz
$ sudo perf_5.10 stat --all-user ./ch4printword 2>&1 | grep cycles
             1,132      cycles                    #    0.006 GHz

Running perf as root also lets you see all the cycles the kernel used, which for my toy program is most of it. Presumably overhead setting up the process? The --all-user flag restricts to only show user time. Or alternately, don’t run as root.

Note the number of cycles it takes varies each time I run it. Why? Not sure, but I assume it has to do with some unpredictable interaction with other system activity and/or the way the process got created. But while cycles varies, instructions don’t. My program is deterministic.

$ for i in $(seq 1 5); do perf_5.10 stat ./ch4printword 2>&1 | grep cycles; done
             1,288      cycles:u                  #    0.004 GHz
             1,034      cycles:u                  #    0.004 GHz
             1,376      cycles:u                  #    0.005 GHz
             1,039      cycles:u                  #    0.004 GHz
               957      cycles:u                  #    0.005 GHz

perf supports running a job a bunch of times and showing average and SD

$ perf_5.10 stat -r 1000  ./ch4printword > /dev/null

 Performance counter stats for './ch4printword' (1000 runs):

              0.18 msec task-clock:u        #    0.145 CPUs utilized ( +-  0.67% )
             1,130      cycles:u            #    0.006 GHz  ( +-  0.58% )
               167      instructions:u      #    0.15  insn per cycle
                 6      branch-misses:u     ( +-  1.62% )

        0.00126752 +- 0.00000893 seconds time elapsed  ( +-  0.70% )

perf by default is printing counters for events it thinks I care about. You can see all possible events with perf list. One chunk are performance counters from the armv8_cortex_a72 itself. There’s a lot of data here, like cache misses and bus access and stuff. I was interested in branch prediction, so

$ perf_5.10 stat -r 1000 -e mem_access,cpu_cycles,instructions,br_pred,br_mis_pred  ./ch4printword > /dev/null

 Performance counter stats for './ch4printword' (1000 runs):

                20      mem_access:u                              ( +-  0.21% )
               985      cpu_cycles:u                              ( +-  0.72% )
               167      instructions:u
                63      br_pred:u                                 ( +-  0.22% )
                 5      br_mis_pred:u                             ( +-  1.81% )

        0.00122416 +- 0.00000844 seconds time elapsed  ( +-  0.69% )

One small mystery; my program has 32-48 branch instructions executed. why is br_pred bigger than 48? Perhaps this has to do with speculative execution?

167 instructions in 1000ish cycles is not very good. I thought ARM was RISCy enough you could expect 1 instruction per cycle but in reality it’s way more complicated. The Cortex-A72 is a superscalar CPU with a 15 stage pipeline and can be running five instructions at once! But this is a very short program so maybe not the best test.

I did some quick tries with perf on CPU-bound jobs.

  • 1.10 instructions / cycle: stress -c 1 -t 5:
  • 0.94: zstd -19
  • 0.44: zstd -3
  • 0.89: gzip

Those last three are I/O intensive so probably not a great test.

This blog post on performance tuning demonstrates 2.053 instructions / cycle for matrix multiplication. It also says “In scientific code with a mix of integer and floating point operations, an IPC of 2 is a good starting goal.”

Learning all this reminds me how complex micro-optimization is. Particularly for C code; you’re having to not only predict what the CPU is doing but also what the C optimizer is capable of emitting. I’d naively thought programming in assembly would make it easier to get some highly optimized code for things but I’m quickly discovering it’s so complex you probably get better results letting a compiler do the real work.

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”.

Windows 11 thoughts: taskbar customization

I upgraded to Windows 11 last night. Finally needed WSLg enough to take the jump. Install went fine and mostly I like the changes. The big visible thing is a UI refresh; nicer File Explorer, cleaned up right click menus on files, etc. It’s mostly good. Apparently rounded corners are in this season along with shorter shorts on men.

And then there’s the taskbar. They completely rewrote it. And stripped out a bunch of features. The one that’s killing me is the taskbar now must be on the bottom; there’s no way to move it to the left. Which is where you want it on a screen that’s much wider than it is tall. Which also means there’s no text labels, something I liked on a wide monitor. Argh!

So that got me looking for customization options. There are a lot. Here’s some I found.

  • RoundedTB: changes the look of the task bar: rounded, and transparent in the empty parts (so it looks like boxes, not a bar).
  • Stardock: Start10 gives you a Windows 10-like start menu (with the Windows 11 task bar). Start11 lets you customize the look of the Windows 11 taskbar and start menu in various ways.
  • StartIsBack: another Start/Taskbar customizer mostly advertising the ability to make it look like Windows 10.
  • ExplorerPatcher is a grab-bag of little changes to various UI elements, mostly to look like older version of Windows. It sounds like this just enables hidden old code, it’s not a rewrite / new Start menu like some of the others. Could be wrong about that.
  • StartAllBack: yet another set of UI tweaks, with Windows 10 style taskbar and start menu. This one is the only one that claims to move the taskbar to the left.

They’re all more similar than different really. Many of these are “bring me back my old Windows 10 GUI” (or even worse, Windows 7). I like Windows 11’s changes in general, I want to go forward, just want to tweak one or two things.

StartAllBack is the only one I installed and tried. And it’s pretty good, I’ll probably keep using it. I’m mainly using it for the “enhanced classic taskbar” which seems to be a rewrite of Windows 10 style task bars. It’s mostly OK and even lets some of the newer features like jump lists through if you want them. I sure missed my text labels for tasks on the left, glad to have them

Screenshot collage

Now that I have 18,363 screenshots of linkblog web pages, what can I do with them? My first thought was to make a giant zoomable collage but an experiment with the 960 most recent makes me think that would not be very interesting. (This image is 2688x1470; click to embiggen.)

Generated with ./magick montage -geometry 80x45+2+2 *.webp output.webp. (Fun fact; if you forget the output filename imagemagick will happily overwrite the last input file.)

I think the old screenshots could be interesting but not in this random jumbled display.

Doing all 18,000 images would result in a file about 19x bigger. 11 megabytes, and about 12000x6400 pixels big. That’s shrinking the screenshots down from 640x360 to 80x45; a full resolution file of all images would be 64x bigger, so 700MB and about 100,000 x 56,000.

Writing an Atom feed in 2022

I decided to roll my own feed for my linkblog, to put my nice images in with the text. (Pinboard’s RSS 1.0 feed has done me well many years!) This turns out to be surprisingly difficult and all tainted by the way RSS/Atom hasn’t really gotten any development in 5+ years.

So which; RSS or Atom? Ugh! Happily the answer in 2022 seems to be “literally no one cares”. So I’m going mostly with Atom for old times’ sake. But I ended up coding this with feedgen which can emit both RSS 2.0 and Atom. (RIP, RSS 1.0 and 0.91). There’s still a lot of work in actually creating the feed and populating all the complicated fields.

Useful Atom resources:

One thing I couldn’t find is a nice Atom preview tool to render what the feed might look like. In the old days I’d use a desktop feed reader or maybe my browser to do this but all I know about now is hosted apps like Feedly where it’s a little tricky to get it to reload as I iterate. Oh well.

Boy Atom sure is complicated. I was briefly involved in the creation of the Atom format but I am kind of horrified at what it is. Every single feed is supposed to have a “self link” pointing to itself. Feed entries can too, but it’s not necessary. Entries can have titles, contents, and summaries. Two dates per entry; published and updated. Etc etc. Not all of these are mandatory but sheesh. Also it’s all XML. Still better than RSS 2.0 though. It’s a shame JSON Feed hasn’t caught on although the last thing we need is yet another feed format.

Update: feed seems to work on my first try! Not sure I’ll promote it though, it’s not really better than the Pinboard feed. The thing I added was an <img> tag in the description with the preview. But both Feedly and Slack are providing preview images even without it, through their own preview systems, and the result is more or less the same. I’m not sure if they’re even using my image tag at all. For about 10% of my links it should allow for a screenshot from my own code for links where Slack/Feedly won’t show an image at all.

Update 2 My last post (ERCOT Dashboard) is a good test; there’s no OpenGraph-style preview image available but I got a good screenshot. Slack just shows no image (ignoring mine). Feedly shows my screenshot though!

Blocked by Akamai

For the past two days I’ve been taking web previews of all 25,000 links from my linkblog. Akamai seems to have blocked me in retaliation. Requests to Akamai-hosted services like www.justice.gov are giving me an old school unstyled 403 Forbidden.

I assume they think I’m a scraper of some sort. Which I am, but an awfully low key one. I’ve got a single thread downloading web pages one at a time, every 1-10 seconds. Surprised that triggers Akamai’s defenses. It’s not a huge deal for my current project, but I sure hope it goes away once I stop my survey because it’d be awfully annoying to be blocked from 10% of the Internet permanently.

A little curious how they even caught on to me. I imagine user agents; the only place I make an effort to pretend to be a desktop browser is when I download the actual image named in OpenGraph data. (Oddly this fixed a lot of problems; apparently I can download the HTML with some user agents but not the linked image?!)

I’ve got metascrape set up using undici as the HTTP client and it sends a user agent of undici.

shot-scraper’s default user-agent is Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/102.0.5005.40 Safari/537.36 which looks close to a legit desktop browser but not exactly. It’s possible to reconfigure what shot-scraper uses.

User agent is the dumbest sort of security; it’s trivially easy to spoof, so really you’re only blocking lazy well meaning people like me if you filter on it. But there’s much more aggressive forms of user agent detection. See curl-impersonate which tries to mimic desktop browsers’ SSL behavior to evade more hardcore detection.

Update: 24 hours later and still blocked. I’m mad about this now. If I’d been aggressively scraping one site repeatedly I’d understand. But some lightweight automated screenshotting of sites all over the Internet once every few seconds should not cause me to get blocked forever. I had to set up tinyproxy just to book a damn hotel. Ironically I can’t read Akamai’s own support notes on their bans, since they are all hosted on Akamai.

Update 2: the block slowly expired starting the morning of July 23, 3 days after my screenshotter tool stopped running. It wasn’t lifted all at once. justice.gov was the first site I noticed working again. Later tripadvisor.com. schwab.com took the longest and for all I know some Akamai sites are still blocking me. Schwab showed a really irritating failure mode; the main page loaded fine (hosted elsewhere?) but the login iframe was blocked. At least that showed an error; I also hit some sites where some invisible AJAX refused to load, invisibly.

Update 3: if this happens again, try the tool at https://www.akamai.com/us/en/clientrep-lookup/

Tech notes on my linkblog

My linkblog website is done, see it here: https://www.somebits.com/linkblog/

After a week or two of tinkering (and more research) I’ve come up with a nice clean web page for my linkblog. Each post has its own box with an image preview. I’m pretty excited how it looks. Also reminded myself of a cardinal rule of design projects; get something that looks good and functional ASAP. It’s so motivating!

Here’s screenshots of design iterations (from newest to oldest).

It’s a pretty straightforward layout but there’s one clever thing I’m doing, highlighting positive sentiment posts (white) from negative (black). I like how I iterated from a simple vertical design to something with alternating left and right. It’s idiosyncratic but I think it’s interesting.

Code architecture

It’s all pretty simple. Custom built Python static site generator driven from Pinboard data making liberal use of external Unix tools for complicated things. Very basic hand coded HTML and CSS, no frameworks, no Javascript. Static sites for static data!

The main loop is to sync data from Pinboard once an hour into sqlite. Then run a process to generate image previews for new links. Finally render HTML from the data in sqlite and push to a web server.

I used my friend Dan’s PugSQL for database access in Python. Very nice little tool; you write actual SQL code with just the lightest sprinkling of metadata for variable names, then execute it in your Python code. It takes some of the hassle out of writing SQL in Python without doing anything too magic. Worked great for this project. I only have two tables in SQLite and a total of 7 SQL queries. One nice thing about sqlite is there’s less need to optimize; I’m happy to make several SQL calls to render one post rather than try to do some complicated join to minimize database round trips.

Previews

I’ve written several blog posts about preview generation and I’m glad for all the research I did. I settled on a single 320 pixel wide image for a preview, height up to 320 with a preferred height of 180. My code supports multiple engines for generating an image preview but in the end I’m only using two. Metascraper, a standalone program that analyzes HTML for OpenGraph tags, etc to select an image. And shot-scraper, a standalone program that takes screenshots with a headless browser. I also tried the linkpreview service and a Python library called webpreview but they were redundant with metascraper.

Multiple engines yields multiple candidate images. I pretty much always take the Metascraper image; it’s available for about 90% of the links. In a few hand-coded exceptions I’ll prefer the screenshot. (Metascraper offers crappy images for Hacker News posts and Wikipedia pages that don’t have featured images. Also sometimes it returns an SVG image which the rest of my code can’t handle.)

Overall I’d say 90% or more of my posts have good images. A few of the Metascraper images are turkeys. Some screenshots are marred by cookie popups, etc. One neat thing is that web pages that don’t screenshot well also tend to be the ones with thoughtful OpenGraph previews.

The preview images are downloaded or generated and resized to 640 wide with lossy cwebp. Major savings there, the results are maybe 10% the size compared to just serving the actual image. Screenshots average 27kb, metascrape’s website images averages 50kb with a few oddball much larger ones because I couldn’t resize the source image. (cwebp can’t deal with animated GIFs!)

Page size and performance

I’m going for a fairly maximalist presentation so I don’t care too much about page size. 100 links on a page makes for a 5MB download, almost entirely the image previews. Google’s PageSpeed Insights gives me a pass on “core web vitals” and an 85 on Performance, which isn’t awful. The main complaint is just that it’s a 5 megabyte page with 100 medium sized images on it. I could easily solve this by just including fewer links on the page 👿. Or maybe go to an infinite scrolling / load on demand design, but the extra complexity of that does not seem worth it to me.

The one performance thing I’m not happy with is the image reflow. I don’t set an explicit height for the images because I’m using CSS to calculate the height. I’m not cropping the images but relying on overflow: hidden to contain them to max-height 320px. This all looks good, is less work for me, and has the nice property that the full preview image is available if you click on it. But it does cause a lot of reflowing while the page loads. I should revisit this.

Update: Thanks to a hint from Thomas S I now am including the native file image size in the HTML img tags. Combined with CSS rules for max-width: 100% and height: auto and the browser does a nice job laying out the images before loading them. I also added loading: lazy to the image tags at his suggestion which is a big help. The new mystery is font loading; Firefox loads them after the visible images. But that’s a deep rabbit hole.

Responsive design

This is the first time I’ve coded a mobile-friendly view for a website with a responsive design. All by hand, no framework to help me. My design is intended for desktop use, I worked with an 800px wide frame as the core design element. 320px for images, about 440px for text, and some gutters. But I wanted it to look reasonable on a phone too. So I read a couple of MDN articles and figured out how to do responsive design. It’s simpler than I realized.

The first principle is that you need to set <meta name="viewport”>. Without it mobile browsers seem to go into some compatibility mode where they render the page for a screen that’s 960px wide and then shrink it to fit in the actual CSS pixels for the screen, often about half or a third the size. That’s why fonts are so tiny for non-mobile websites on phones! So you set the viewport to width=device-width and now the page will render at the phone’s native CSS width, typically around 400 CSS pixels. (Which is probably actually 800 or 1200 physical pixels thanks to high DPI.)

The second principle is just to design the site so the page looks good at various widths in a regular desktop browser. I originally hardcoded a rigid width: 800px in my main display element which looks terrible if you shrink the browser below that (it clips). Making a more flexible layout works better. I was a bit constrained because I really wanted the preview images to be fixed at 320px, but now the text could go anywhere from 440px to about 250px and still look good.

The third principle is media queries to define explicit CSS rules for different screen sizes. My main rule is if the screen is smaller than 800 pixels to render differently; switch to a single column layout (images below text), use smaller margins, etc. For smaller mobile size screens I knock the font size down a bit too, to make more text fit. I did the opposite of the recommended “mobile first design”; my default CSS rules are for wide desktop screens, then I have overrides for small mobile screens.

Firefox has a great “responsive design mode” that lets you simulate how your page looks on various real world phones. Big help.

Future work

I’m pretty happy with where this stands. But I’m sure I’ll tinker.

One future work idea is to do some sort of pagination / archive view. Right now I’m just showing the last 100 links, without even dates displayed. That’s fine, there’s an archive view on Pinboard. But maybe I’ll eventually do more on my static site. See notes above about infinite scrolling as a possibility, too.

The other thing to tweak is continue to get better previews. Metascraper could be improved. Also I realized I could use Feedly to generate previews for me; they have an API where I can pull their preview images. There’s diminishing returns for this kind of work.

Finally I have one unexplored design idea. Display each preview as a full-bleed image in the background of a box for the post. Then put my descriptive text on top of the preview image, using some combination of blur and shading and maybe text halos to make it readable. It’s a pretty aggressive design but I’ve seen stuff like that look good before and it’d be fun to try.

WebP conversion

I just spent about an hour learning about converting images to WebP. For my linkblog; I want my link previews to be small files. Target display is 320x180ish images.

Here’s where I landed to resize everything to 640 pixels wide with a fairly high quality:

cwebp -quiet 
  -af -q 90 
  -resize 640 0 
  -metadata all 

These are guesses but seem to work about right.

-af -q 90 are the quality settings. 90 is fairly high, the default is 75. af means “spend more time making it look good”, it seems to take about 2x as long. I also experimented with the -m setting to trade off time vs compression quality but the default -m 4 seems fine to me.

The resize forces all images to a width of 640 and whatever height is natural. Twice the target display resolution for retina display.

The one surprise is some of the images (but only some) seem to get a little brighter after conversion. I thought that was a symptom of ICC color profiles not being applied right, which is why I added the -metadata all flag. But it’s still happening. I don’t care enough to figure it out; it could just be the difference in the browser resize algorithm vs cwebp.

Starting with a bunch of 1280x720 screenshot PNGs the webp versions are about 10% the size. If I leave out the image resizing it’s about 25%. That’s mostly thanks to the lossy compression which is fine for my purposes given I’m resizing too.

Overall this got my full page down from 24MB to 2MB. Worth the time!

Website previews: images for unfurls

Some notes on another way to generate one image per link for my linkblog: unfurls. Those are the site previews things like Twitter Cards or Slack Unfurls or Facebook Link Previews. They try to extract a few words and an image from the page; the resulting preview is structured data, not just a picture. Most of these basically work by looking for oEmbed tags, OpenGraph tags, or Twitter’s card tags and then just guessing if those metadata tags aren’t present.

Most unfurls are a mix of text, a little structured data, and an image or video embed. I’m focused on the image. Possibly I could generate an image from textual data too.

Page metadata: OpenGraph and friends

Facebook, Twitter, Slack, etc rely primarily on page metadata to get a text summary and example image. Only works for sites that publish the metadata but since it’s so commonly used now a lot of sites have it. These formats all offer one image. By custom that image tends to be 400+ pixels wide and roughly 2:1 aspect ratio.

OpenGraph is the big standard, originally from Facebook, here’s a useful description of how it works in practice. Dates to 2010. For my purposes the key tag is og:image. og:title gives text.

Twitter’s cards are a popular expansion of the OpenGraph idea dating to 2012. More details on supported tags here. twitter:image is the most relevant, and possibly twitter:player. There’s more tags for textual metadata than OpenGraph.

oEmbed is the oldest standard, from 2008. Metadata isn’t in the page itself, instead you have to make a query to a special JSON endpoint. Interesting image fields are thumbnail_url and maybe the photo and video types. Lots of textual metadata too. I don’t know how popular oEmbed is these days but Slack supports it.

schema.org Articles also are relevant, particularly since Google supports them. It started in 2011 as a way to tell search engines how to summarize a page. Metadata is in the page in one of three encodings (sigh). There’s also an overwhelming number of tags; maybe thumbnailUrl is what I want? or image? Honestly this is all so complicated I’m not in a hurry to learn more.

Without metadata

Metadata is great if it’s present, what do you do if it’s not? Maybe pull an image from the page? This approach doesn’t seem so popular but Feedly does it. There’s a description in item 4 of what they do. Boils down to images tagged webfeedsFeaturedVisual, or else the first big image in the story, or else the biggest image on the page.

Another option would be to take a screenshot of the page itself. I have some notes on that but it’s not very simple to get a good result.

A third option would be to use the favicon. Not awesome, but it is there.

Heuristics for combining preview data

So now we have myriad ways to find an image for the site; which one do we use? Slack has a great post (from my friend Matt!) about how they generate unfurls. They give oEmbed priority, then Twitter+OpenGraph, then HTML meta tags as a fallback. They also seem to combine data from multiple sources; their cards have room for a lot of text.

Tyler Young from Felt recently tweeted about their solution. Light on details though, mostly it’s just “it’s complicated”. That echoes what I’ve heard informally from folks who’ve worked on this problem at various companies. Lots of one-off hacks in the end.

Code Tools

All this stuff is complicated and of general interest; is there a reusable library for generating previews I can just use? npm.io has a big list, here’s some highlights from it and some others.

metascraper (GitHub) looks to be the most active of the NPMs. MIT license, active development. Has a lot of configurable options and also custom code for popular sites. This looks like a strong contender I should evaluate further.

iFramely (GitHub) is mostly a hosted service but their parser is on GitHub with an MIT License. Javascript, looks like fairly active development. Also promising.

unfurl (GitHub). TypeScript, active development, MIT license.

Link Preview (GitHub) generates OpenGraph, TwitterCard, and oEmbed previews of pages. The source is Javascript and MIT licensed. Last updates about 2 years ago. Looks like a small project.

pyUnfurl (GitHub) does the various metadata things and falls back to favicon. Python, MIT License, small project with last main development 3 years ago.

extruct is in Python (BSD license) and recently updated. OpenGraph but not Twitter (yet, there’s a pull request).

webpreview is in Python (MIT license) and was last updated two years ago. OpenGraph, Twitter, Schema, or else “from the webpage’s content”.

Metaphor is the Python code with the most Google juice but hasn’t been updated in 5 years.

Buying a service

Another option for unfurls is just buying a blackbox service for this. Embed.ly is the one I know; part of the value ad is they have “700+ Official Content Providers” who they’ve worked to interoperate with. Their $9/mo product wants to embed “cards” though, which I take to mean Javascript running on your site. Not for me. The $99/mo product is a lot more flexible but is more than I’d want to spend. iFramely also looks promising although similar problem with pricing / embeds.

Update: Ryan B mentioned using linkpreview.net, it looks promising. It has a JSON API that returns data including an image. The free plan might work for me or paid plans start at $8/mo.

It’d also be possible for me to do a bit of guerilla scraping for my own “service”. Post the link to Feedly or Twitter, then capture what preview they come up with. That might actually work pretty well, at least right until it doesn’t.

My Plan

I should start with Metascraper. It looks good, my only complaint is dealing with Node. Alternately I think I’m stuck writing my own thing, a lightweight OpenGraph / Twitter card scraper plus reimplementing some image choosing heuristics. That’s a lot of work I’d rather not do.

Once I have an unfurl tool I can use I should test it on my linblog. I’m really curious how many of the links I’ve posted have useful metadata. I’d guess about half of them in the last 3 years. Seems worth doing a survey.

Screenshots may still prove to be a useful fallback.

Generating screenshots from web pages

I’m working on a way to get one image for a link for each link in my linkblog. There’s two basic approaches: screenshots and unfurls. This post has my notes on screenshots, particularly Simon Willison’s shot-scrape tool based on Microsoft Playwright.

Screenshots boil down to running something like a normal browser and capturing the page after it renders. Sounds simple but the modern web with ads, cookie popups, etc makes this hard. The problem is getting a screenshot that shows the intended content. I tested about 50 links of mine with shot-scraper and maybe 40% didn’t work at all, or had a paywall notice or a cookie consent popup covering everything or otherwise didn’t show anything useful.

One straightforward solution would be just to take screenshots manually when adding a new link. I already like what I’m seeing when I choose to blog a link, why not take a picture? I don’t want to create new work in my flow of posting to a linkblog but honestly this wouldn’t be too much, particularly with a browser tool automating the screenshot process. A related solution would be to pay someone else to do the screenshot for you via Mechanical Turk or the like. But at my small scale I don’t think that makes sense.

shot-scraper is a promising new tool for automated screenshots. It’s a wrapper around Microsoft Playwright, an automation framework that wraps up browsers like Chrome or Firefox and makes it easily programmable. Simon’s shot-scraper puts a nice command line interface around it and while it’s written in Python, it’s more of a command line tool than a Python API. It’s fairly subtle and allows for extracting specific CSS pieces, running some Javascript in the page context, etc. I’ve had promising results with it so far but it needs some tweaking to get the more recalcitrant pages to display.

Ben Welsh’s News Homepages project is open source and also uses Playwright to take screenshots of newspaper pages. The clever thing there is a bunch of extra rules to make the 200 sites they care about look better. There are generic rules like “don’t show anything named popup_wrapper”. Also site-specific rules that boil down to hiding specific CSS classes or running a bit of extra code to adjust the page layout. The bespoke approach won’t work for me since I don’t have a short target list but some of the generic rules might work.

I wonder if it’s possible to install an ad blocker or other addons inside Playwright’s browser? (Simon thought maybe in the Javascript version, but not Python). That might be a good general purpose way to improve the screenshot quality.

Another tweak is to the user agent you send when taking the screenshot. Looking like a bot often gets you blocked so emulating a browser may be necessary. I have a suspicion that the screenshots from mobile versions of sites are likely to be better than desktop ones. Although Tyler warns that different sites work better with different user agents.

There are some web services that do screenshots that might work well: Site-Shot ($15/mo for 5000 screenshots), url2png ($29/mo for 5000), urlbox ($99/mo for 20,000), or the old Thumbshots (shutdown). Update: SavePage.io (free for 7000, $25/mo for 500k). A bunch more listed in urlbox alternatives. (Pikwy looked promising but didn’t work for me.) One thing to check with these is how easy it is to store the screenshot yourself; some seem oriented to them hosting the screenshot and charging per-view.

Overall I’m not very excited about screenshots and will probably not pursue this further for my linkblog. Unfurls / site previews seem a better path.

Reading a file inside a zip as text in Python 3

I have a zipfile. It has a text file inside it. I want to read the first file as text. Here’s how to get a file-like object that has a text stream.

with zipfile.ZipFile(fn) as zf:
  data_fn = zf.namelist()[0]
  bfp = zf.open(data_fn)
  fp = io.TextIOWrapper(bfp, encoding='utf_8_sig')

The tricky bit is all the last line. The problem is ZipFile.open returns a bytes stream. So you have to wrap it in TextIOWrapper to decode it to text. Also my source data has a Unicode byte order mark in it, so utf_8_sig is a magic decoder that will strip out the BOM if present.

This is very remedial Python but I had a hard time figuring it out.

Linkblog design

I’m working on my linkblog and went looking to other linkblogs for inspiration. Some notes on their data design and presentation. Note that the heydey of a linkblog was in 2003 so a lot of these designs are quite dated. See Cameron Marlowe’s roundup for a bunch of the old ones.

Common data elements (“authored” means the person linkblogging created the data themselves; otherwise it’s from the page being linked or automated.

  • URL of page (maybe more than one in a post)
  • Authored short description of page (sometimes title of page; not authored)
  • Authored extended description of page
  • Authored tags
  • Date link was created

Uncommon elements

  • Permalink to linkblog post itself
  • Image chosen from page (not screenshot)
  • Screenshot (only on Hot Links)
  • Social media engagement: Tweet this, Tumblr reactions
  • Full text comments (on LinkMachineGo)
  • “Via” metadata, the source for the link (on Waxy links)
  • Morale, positive/negative sentiment (Erik Benson) (I’m doing this now myself and like it a lot.)

To me the defining characteristic of a linkblog is that each post is a single URL. And that the linkblog post itself has no permalink, page view, etc. The point of the linkblog is to point to other stuff, not to be a thing itself. (A key corollary is the RSS feed for a linkblog should have links directly to the destinations, not links to the linkblog posts.) But not all linkblogs are like this; Cal’s is more of a freeform blog, just with very short posts, as is Waxy’s. And there’s a constellation of link-heavy blogs like Today in Tabs or Webcurios.

I’m not thinking of a linkblog as a social conversation. To me it’s a one-way publication.

I think it’s interesting how text-heavy all these linkblogs are, even the modern ones. Hot Links is the only one that had page screenshots / thumbnails. A couple of the modern ones seem to be doing unfurl-like images too, like a youtube embed or a single picture from the page. Mostly text though. My guess is it’s because making images is a hassle.

Here’s some screenshots from modern linkblogs.

And here’s some from O.G. linkblogs (2003ish)

Thoughts for my design

I’m going to stick with the Pinboard data schema. The important elements there are URL, short description, extended description, and tags. I also have a special tag now which indicates sentiment. I’m ambivalent about whether the other tags are useful; the old tagging metadata ethos seems like a failure to me. But I dutifully type six or so random words per link, might as well display them.

What I’m most interested in is what else can I add to a linkblog entry to make it more interesting / convey more about the target. My big wish is for an image: either a screenshot or a Slack/Twitter/Facebook/OpenGraph like unfurl. I’ve been researching how to do that. I also am curious if there’s an AI driven web page summarizer that would be useful. Probably not, and limited to text-heavy links anyway. But worth a look.

As for visual design I’m most inspired by that Hot Links screenshot above. I want to avoid the “list of text links” look although with a fancy layout like Balaji’s (4th modern screenshot) it looks better.

Sources

Here’s a list of all the linkblog URLs I looked at for this little survey.

Modern linkblogs

https://adactio.com/links/
https://belong.io/
https://linkblog.balaji-dutt.name/
https://pinboard.in/u:nelson
https://waxy.org/category/links/
https://www.iamcal.com/
https://www.oreilly.com/radar/topics/four-short-links/
https://www.timemachinego.com/linkmachinego/

O.G. linkblogs

https://web.archive.org/web/20020525043925/http://muxway.org/
https://web.archive.org/web/20030122204422/http://sippey.com/recentlybrowsed/
https://web.archive.org/web/20030204085103/http://overstated.net/oddments/
https://web.archive.org/web/20030406052139/http://interconnected.org/home/mini/archive/2003/01/22/
https://web.archive.org/web/20030407233201/http://www.kungfugrippe.com/previously/oldlinks/
https://web.archive.org/web/20030418085243/http://www.leuschke.org/quick/
https://web.archive.org/web/20030418095901/http://laughingmeme.org/mlp/
https://web.archive.org/web/20030418141712/http://erikbenson.com/index.cgi?node=Morale-O-Meter
https://web.archive.org/web/20030529063444/http://doublereflection.org/wanderings/
https://web.archive.org/web/20030711150524/http://quietconfusion.com/diversions/
https://web.archive.org/web/20030812074837/http://www.littleyellowdifferent.com/miniblog/
https://web.archive.org/web/20030815194007/http://www.tradermike.net/quicklinks/
https://web.archive.org/web/20030912200338/http://peteashton.com/linkfarm/
https://web.archive.org/web/20040210042807/http://www.kottke.org/remainder/
https://web.archive.org/web/20040929091703/http://www.dashes.com/links/
http://jeremy.zawodny.com/linkblog/
http://www.photodude.com/arbitrary/

Adding static type signatures to PugSQL

Got distracted by a yak today; trying to add Python static type checking to PugSQL generated code. I got something that kind of works but it’d take some effort to make really useful. The basic idea is to create a .pyi file for PugSQL’s queries module.

The challenge with PugSQL is it’s generating functions dynamically. At runtime it reads a .sql file that says “create a function called pugsql.compiler.Module.count_links()”. So of course VS.Code’s static type checker pylance/pyright has no idea what count_links() is and it displays a red squigglely line.

I kludged it by using PyRight’s type stub support. I used PyRight to autogenerate type signatures for pugsql, including a file named typings/pugsql/compiler.py. (These generated signatures were not very good; the command line guessing tool does less of a good job guessing types that VS.Code’s interactive stuff.)

Then I edited that file to add some type signatures for my custom methods I am creating using PugSQL.

    def count_links(self) -> int:
            ...
    def select_recent(self, count: int) -> list[dict]:
            ...
    def upsert_link(self, *args: dict[str, Any]) -> None:
            ...

count_links is the simplest, it’s a basic select count(*) from links query. Takes no arguments, returns a number. select_recent pulls off N rows and returns them as a list of dicts (select * from links limit 10). Finally upsert_link is taking a list of rows (as dicts) and inserting them.

These are pretty generic type signatures. For instance select_recent is returning typed data from sqlite; those dicts actually contain entries with types you could infer from the SQL schema. That’s a good deal more complicated to do automatically, though. It’d be awfully nice, but then my main goal here was just to shut up the red squiggly line and for that a more generic type is sufficient.

Having done all this it’s enough of a nuisance I probably won’t pursue this further. But I could imagine PugSQL emitting these .pyi files automatically, it could be pretty slick.

It’d be worth reviewing what SQLAlchemy is doing for static type checking. They have a similar problem and it looks like they’ve thought pretty carefully about a solution.

Very simple Python ORMs

Starting a new project and want something to take the tedium out of a small sqlite database (like 2 tables, a few thousand rows). I don’t want to write wrappers for SQL to insert and select rows. OTOH I don’t want a complex ORM like SQLAlchemy or Django. What are my options?

  • Peewee. Well established, seems to be the consensus choice. Don’t love the code examples but they’re fine. Docs are good. Supports migrations.
  • PonyORM. The other frequently mentioned option. Has nifty metaprogramming so you can write queries in Python. But it does not support migrations.
  • Datalite. A very small binding between Python Dataclass types and sqlite tables. Docs are thin but code is small and readable. Supports migrations, surprisingly.

Based on my last project with SQLAlchemy, migration support is important. So that rules out PonyORM. Peewee and Datalite are very different in scale. I’ll start with Datalite and if it’s too limiting, consider moving to Peewee.

Update: Dan reminds me of PugSQL which is a wrapper for easy SQL execution in Python. Not really an ORM but does take the tedium out of simple SQL queries. And avoids ORM magic.

Mikrotik / RouterOS v6 thoughts

Playing with a new router every month is not a rewarding hobby.

I got my hands on a Mikrotik Hex S and tried it as my home router. It mostly worked fine but I couldn’t figure out how to get WAN failover to work. So I gave up on it for now.

Mostly was impressed with RouterOS as a basic router product for a prosumer. The UI is idiosyncratic and their OS approach is kind of old school. But the thing works. Also it’s relatively simple and transparent for simple things. And I like the simple command line / windows app / web UI trichotomy, they all work the same way. I was able to get a basic router up and running with no trouble. (It’s pretty sad that https for configuration doesn’t work; you can enable it but there’s SSL problems.)

The docs are a mess. Apparently there used to be a user-edited Wiki with many lovingly written detailed articles. That all got thrown over in favor of some official manufacturer docs. I’d applaud that investment but the execution is not great, many of the docs are read. It took me a long time to understand the gestalt of RouterOS, the concepts you need to understand to use it.

Version management is a mess too. I used RouterOS v6.48.6, the latest long term release. They put out a v7 beta months ago which was buggy, fair enough. Then they declared v7 stable. But apparently several major features look enabled but do not work? That’s the vibe I got reasearching. I stayed away from it. Which is too bad, because you need v7 for Wireguard which is one of the features I was looking for.

The other feature I needed is WAN failover. And after a couple hours’ research I gave up and decided I couldn’t do it in a way I was comfortable with. There’s no simple way to just enable it; all methods require manually configuring routes, etc. The official docs are confusing. This blog post was more helpful and details three methods of doing it, all with drawbacks. The thing that held me up is they all require hard-coding routes to specific gateway IP addresses. But ISP gateway IP addresses are dynamic, you can’t just hardcode them like that reliably. This discussion had a link to a script that looked like it might configure things with a funky script that pulls data from the DHCP subsystem. Maybe it even works, but that was a level of complication too far for me.

Folks like Mikrotik routers. And I can understand why, particularly a few years ago. Cheap but good hardware, a solid “real” OS, very powerful configurability. But in 2022 the software felt pretty retro and the moment I ran into something complicated it got idiosyncratic. Which brings me back to OpenWRT; if I’m going to hack, might as well at least hack on something that feels like a Unix system I understand. Anyway I’m back on Ubiquiti’s router for now, at least I know what their bugs are like.

Google caches “what is my ip”

I’m in the habit of searching Google for “what is my ip” to see my IP address; they have a little onebox result right at the top that shows it.

Turns out it’s cached. Worse than useless, actively harmful.

At least that’s what it looked like. I searched “what is my IP” today when I was on WAN2, my backup, and saw my WAN2 address. Then I fixed WAN1 so it’d work again and it looked like my router returned to WAN1 from failover to WAN2. But I’d type “what is my IP” and Google still showed the WAN2 address, like the return hadn’t happened. I finally checked on some other site and saw that the failover had happened. A shift-reload on the Google search page did finally show the correct data. All of this sure looks like something is caching the IP address. Maybe it’s related to a persistent HTTP or QUIC session my browser has open?

Every time I do this I have to remind myself https://api.ipify.org/ is the best way to check your IP. Simple text result, a web service intended for this use. Ipify has other tricks too, including an inexpensive geolocation service.

Brisket smoking plan

Something different here, my notes on how to smoke a brisket. There’s a zillion pages on how to do this on the Internet with conflicting advice. (This page seems better than most). I’m cooking a 6lb flat cut at 250F, on a gas grill with wood chips. I’m going with the method that estimates 60-90 minutes / pound total (so, 6-9 hours) and has you wrap the meat during the stall to help it get hot. The key thing for all this is a good meat thermometer.

At 90 minutes / pound it should take 6-9 hours total, including resting time. Hour markers below are approximate and on the high end, should be checking and ready to change earlier based on temperature.

Night before

  • Salt meat
  • Soak wood chips
  • Make rub

Hour 0

  • Put rub on meat
  • Heat grill hot
  • Get wood chips smoking
  • Lower grill temp to 250F
  • Put in a water pan to keep humidity up
  • Put the meat on indirect heat near smoker box. Fat cap down.

Hours 0-5ish

  • Check regularly, maintain wood chips, water, grill temperature
  • Some folks recommend spritzing meat with water
  • Consider rotating meat 180 degrees (fat still down) for even smoking

Hour 5ish (maybe sooner)

  • Meat should be at “the stall”; 150F - 165F.
  • Wrap meat in foil with a little liquid. Wrap air tight!
  • Remove wood chips
  • Put meat back, indirect heat

Hour 5-8ish

  • Maintain grill at 250F
  • Cook until meat at 203F

Hour 8-9ish

  • Meat is at 203F
  • Turn off grill. Put wrapped meat in an empty cooler.
  • Let rest for an hour or more. Longer is fine!

Hour 9-9.5ish

  • Heat grill to hot: 400F or so
  • Unwrap meat
  • Put meat back on grill, indirect heat
  • Leave just long enough to dry the bark on the surface. Maybe 15 minutes?

Hour 9.5ish

  • Slice meat just before serving
  • Slice meat with fat side up
  • Be sure to use a cutting board with a juice catcher

Updates

It’s going well, pictures on Twitter. Some things I’ve learned:

  • I want to do a point cut next time.
  • My 3 burner propane Weber gets to about 240F in the middle if I turn one side burner on the lowest setting. Hard to be exactly sure, it was windy enough temperature fluctuated.
  • The Weber’s thermometer in the lid reads about 20F low at these temperatures. Indicates 220F, actually 240F.
  • This little smoker box looks good. But I have to put in a lot of chips, like every 20-30 minutes adding a big handful.
  • The cook came out just as predicted. 8 hours on the fire to 203F, an hour for rest, a bit extra to dry it off.
  • The wrapped foil package comes out just full of meat juices, I must have gotten 3 cups. I was able to save it but the foil is an awkward vessel to collect it all. Also makes you realize how different the wrap makes this from a dry smoke; a traditional brisket all that liquid would have slowly evaporated or dripped off.
  • The meat was good. Not excellent, but good and worth the effort. There’s a style of brisket, mostly burnt ends, which comes out almost like bacon; crispy and with a lot of lovely rendered fat. I think you must need a point cut for that. The flat I used was much more a solid cooked chunk of meat and that’s good too but not great. Other changes I’d make: more salt, more smoke (somehow).

Sunpower PVS6 web console

The Sunpower PVS monitor has a full HTML web console accessible on its internal network. The PVS acts as a full Internet router on a debug ethernet port you can plug into. If you plug a laptop into it the laptop will be online (routed through the PVS) and also serve extra stuff at http://www.sunpowerconsole.com/. It’s mostly a web view of the data in the JSON API but it’s an official debugging tool and is quite nice.

I have my RPi plugged into that debug port and am proxying all web traffic, so on my LAN I can access http://pvspi0.local/ and get at these pages.

Here’s a list of URLs that it supports. These come from this detailed comment which also describes what these URLs do. A lot of these are steps on a little configuration wizard that presumably installers use. I think all these URLs are safe to load but some clearly have buttons to press that could reconfigure or break your system. Don’t press those.

The info view is particularly good; here’s a partial screenshot (I didn’t include the serial numbers.) Three sections: the PVS as a whole, per-panel/inverter data, and then CT monitors.

Solar panel max output, microinverter details

My solar system is mostly doing great. But I’m obsessing over small details and one thing I’ve noted is some (but not all) of my panels seem to max out or even underperform in the middle of the day by 5-10%. I’m trying to figure out why.

Panel 2122: expected
Panel 9897: clipped in the middle

Above is a graph of two of my 28 SunPower SPR-A410 panels with SPR-A410-G-AC microinverters. These were built and installed in 2021. The graph on the left shows what I’d expect; a steady increase in output following the sun. The panels face west, so it’s not a symmetric curve. The falloff end of the day is shading.

The graph on the right is the weird thing; the DC power gets up to about 300W and then sticks there, even dropping down a bit to under 290W. It does briefly get to 334W at the end of the day, so it’s not some absolute max. It’s like that’s the max output of the panel is being limited somehow. It looks like 15 of my 28 panels do this, the other 13 have the smooth curve. It’s clipping about 10% of power production for the middle part of the day, so maybe 5% of a panel’s possible output or 3% of the whole system.

I know a 410W rated panel will never actually put out 410W. But how much should it put out? The maximum I’ve ever seen is 385W (DC) or 367W (AC).

But what I really want to know is why some panels do this odd clipping thing when others don’t? Some theories:

  • Shading. I really don’t think so, both on visual inspection and also just looking at the pattern.
  • Overheating. That was my first theory but the temperature graphs don’t really bear it out.
  • AC conversion. There’s no obvious difference in the AC vs DC power for the panels, they all look to have about the same conversion efficiency. The clipping pattern is visible in the DC as well.

Some things to do next:

  • More statistical exploration. Is it the same panels doing the same thing every day? Is the effect consistent day to day?
    select SERIAL, max(p_mppt1_kw) from pvs6_inverter where SERIAL='…9897' group by time(1d);
  • Get out the map of which panels are installed where and see if there’s a spatial correlation.

Data Details

I’m pulling this data from the SunPower PVS6 device_list API call which is accessible from the device itself. It reports the following variables for each microinverter at each panel:

  • Status: STATE, stat_ind. Always “working” or “error”
  • Temperature: t_htsnk_degc.
  • Cumulative production: ltea_3phsum_kwh.
  • Instant power measurements: p_3phsum_kw, p_mppt1_kw
  • Instant current measurements: i_3phsum_a, i_mppt1_a
  • AC frequency: freq_hz
  • No longer available: v_mppt1_v vln_3phavg_va

The interesting measures here are temperature and power in kW.

Power (and amperage) are reported both for DC power (mppt1) and AC power (3phsum). DC is always(?) the higher number so I assume the small difference is a measure of microinverter inefficiency. Which seems to be about 5% when the panel as a whole is producing about 300W.

Updates

This pattern didn’t happen on 2022-06-21, a fully sunny day. The only real difference I can think of is that my house was using more power; very hot day, AC running. So there’s more load in the house. But surely that doesn’t matter, PG&E will absorb however much power I can produce? Anyway here’s a graph of 9897, the problem panel above. All of the panels look like this this day.

9897

Korean writing: Hangul and Unicode

CAVEAT LECTOR: these are my notes after 2 hours of reading Wikipedia articles. I’m a rank amateur, in no way is any of this stuff authoritative. Better resources than this blog post: Learn Hangeul, Let’s Learn Hangul.

I’m interested in Korean writing, specifically Hangul. It’s so graphically beautiful! And I love writing systems. It seems possible to learn enough to pronounce words clumsily in just a few hours.

Hangul 한글 is what modern Korean is written in. But historically there were other writing systems. Hanja 한자 / 漢字 is the big one; was used starting around 4th century BCE and is based on Chinese characters. I think it’s a little like how kanji works for Japanese. Hanja is still in occasional use but I think mostly in text describing historical things or some proper nouns. There are some other historical writing systems too, mostly efforts to use Chinese characters to represent Korean word sounds. There are several modern Romanizations including a standard one. Also Kontsevich, a transliteration into the Cyrillic alphabet.

Hangul was invented in the 15th century by King Sejong 조선 세종 (or his advisors) and published in a written Chinese document called the Hunminjeongeum 훈민정음 / 訓民正音. It wasn’t immediately popular, Wikipedia implies the educated classes were snobbish about their classical Chinese writing. Hangul became official right at the end of the 19th century. It’s been slightly reformed over time, with some phonemes being removed or unified as they fell out of use.

Despite looking a little like Chinese on first blush Hangul is actually a phonetic writing system; each square that looks like a character is actually a syllable composed of (usually) three phonemes. In general Korean is a CVC language. A block like 한 (“han”) is really three letters called jamo 자모. So 한 can be broken down into three jamos drawn in one block: ㅎㅏㄴ (H A N). There’s a claim that Hangul is a featural writing system, that the visual shape of a jamo reflects the shape the mouth makes when making the sound. Not sure how accurate that is.

Jamos are pretty much never written alone. Instead they are combined into a square block with a fairly straightforward algorithm nicely visualized on Wikipedia. The last consonant is at the bottom. The first consonant is either to the left or above the vowel. It gets a little more complicated because some letters have complex forms.

One extra detail: at least in Unicode, jamos come in both leading (choseong) form like ᄀ and trailing (jongseong) form like ᆨ. The shapes look the same but in this font I’m using they’re shown at different heights. I’m not sure why leading vs. trailing is encoded differently or whether Korean native speakers think of them as different things; since jamos don’t normally appear alone it’s a pretty academic point.

English speakers should be aware that Korean phonology is quite different from English or similar European languages. A “t” sound could be a simple t ㄷ, a tense t͈ ㄸ, or an aspirated tʰ ㅌ. These variants are written as different jamos and are basically entirely different consonants even if they sound kind of the same to an English speaker’s ear. Modern Korean is not tonal but historically it was. Hangul used to use diacritics to indicate tone.

Korean in Unicode is a bit of a mess. My understanding is almost all systems encode Korean with Hangul Syllables, characters in the range U+AC00 to U+D7AF. Each code point is a single syllable. Use those and it’s pretty simple, there’s just a lot of them. The odd thing is these 11,184 code points are entirely algorithmically derivable as combinations of the individual jamos that make up the syllables. The graphical combination is also algorithmic. Instead of thousands of syllable code points you could just write Korean unambiguously as strings of 67 different jamos, they are in Unicode (U+1100 to U+11FF). But that’s not what people do in practice (see the road not taken). I think the only time you’re likely to see the jamo form is if you use normalize and decompose input into Unicode NFD.

A second historical complication of Korean Unicode is mentioned in a tart comment in the UTF-8 RFC

Amendment 5 to ISO/IEC 10646, however, has moved and expanded the Korean Hangul block, thereby making any previous data containing Hangul characters invalid under the new version.  Unicode 2.0 has the same difference from Unicode 1.1. The official justification for allowing such an incompatible change was that no implementations and no data containing Hangul existed, a statement that is likely to be true but remains unprovable.  The incident has been dubbed the “Korean mess”, and the relevant committees have pledged to never, ever again make such an incompatible change.

Mentioning this mostly because it’s funny, doesn’t seem relevant to contemporary systems.

Next thing for me is I’d like to learn more about Korean calligraphy and font design. How Korean artists think about their own writing and manipulate it.

Source

My recent Starlink POPs and IP address changes

A thrilling list of my Starlink ISP’s point of presence, where my packets come out to the Internet. Looking at this because this past week a bunch of users including me have had a problem where their TCP sockets won’t stay open for more than a few minutes, breaking all sorts of stuff. Each date is when my IP address changed.

  • 2022-05-29: Seattle
  • 2022-06-01: Los Angeles
  • 2022-06-04: period of instability
  • 2022-06-04: LA
  • 2022-06-06: LA
  • 2022-06-07: instability
  • 2022-06-07: LA
  • 2022-06-10: LA
  • 2022-06-11: LA

I first noticed my TCP connection problem on 2022-06-07, about the time of that period of instability. It’s mostly been gone since 2022-06-08 but it came back at least a little bit today and is gone again.

The command to do this is

grep '^2022' homeip.log | fgrep -v '157.131' | fgrep -v 173.195 | uniq -c -f 2

Alternate routers

So I’m not happy with my Ubiquiti router and I had a bad experience with OpenWRT. What are other options? I’m considering three choices. My metric here: decent UI, small device that’s just a router (I have a separate Linux server). Must support dual WAN failover and Wireguard VPN tunnels.

Mikrotik and RouterOS. For years I’ve heard about these European routers as being a good product. RouterOS is said to be idiosyncratic but capable. They make a confusing variety of routers. The Hex S seems to be the leading small consumer product and $70 is a fantastic price. The RB4011 and RB5009 get lots of recommendations on Reddit, both at $220. The problem is you can’t really buy these in the US, either not at all or not at that price. Best I can find is like $110 for the Hex S shipped and from dodgy companies that either don’t have stock at all or are probably shipping from Europe.

Netgate and pfSense. The path not taken in routers, based on FreeBSD. Has a good reputation. Buying hardware from Netgate is clearly the path of least resistance. The Netgate 1100 is the small consumer product at $190. Also has flaky availability; Newegg and Amazon are like $230 and ship in a couple of weeks, which suggests “not in stock”. pfSense is nominally open source but I think is amd64 only, which rules out running on Raspberry Pi hardware. Note there’s a remarkable amount of sleaze around this company, the opnsense.com lawsuit and a scary-bad Wireguard implementation.

OPNsense. A fork of pfSense. There’s a company selling hardware but at about $800 entry level it’s clearly not for the home consumer market. A lot of enthusiasts seem to be buying mini PCs to run t his.

I don’t quite know why I’m so focussed on cost; I’ve certainly wasted many valuable hours farting around with failures. I guess I don’t have much faith that throwing $800 at it will actually get me a more reliable router. Also I just don’t have the needs that the higher end hardware is solving.

My best option is probably to order a Mikrotik Hex S and just wait for delivery. I wish I had any faith in the vendors who are selling it in the US.

Update: I got a Hex S from ispsupplies.com. They showed 1000 in stock on Saturday and I got it Thursday, at the list price of $69 plus $10 shipping. They’re already sold out! Note they are selling a unit labelled “tariffed” which I guess has something to do with Trump’s trade war with China but doesn’t seem to matter to me at all.

HSBC: generating security code

HSBC has a broken two factor authentication system that I finally figured out how to make work. I’m not the only one having trouble; searches like “hsbc generate security code” are very popular.

The Android app generates the code. The key thing is you cannot be logged in to HSBC on the mobile app while generating the code. If you are logged in you are taken to an “Accounts” page that shows current balances. Nowhere from here can you generate a code. You have to log off first.

Once you are logged off the screen asking you to login asks for a fingerprint or a “Digital Security Device passcode”. (The latter is a second password that you set up as part of their 2FA system.) Do not log in. Instead, press the “Generate security code” button at the bottom of the screen, then choose “Log on security code” from the popup menu. You’ll have to verify your fingerprint and then it will give you a 6 digit code. That is your temporary security code you can type into the web application to log in.

To complicate matters more; if you are logged in to HSBC both from a desktop browser and from the Android app then HSBC gets confused and complains about how you have two active sessions at once. I think I had to log in on the desktop website like 4 times before I finally managed to finish my business.

I tried taking screenshots to illustrate this but hilariously the app seems to be blocking screenshots, no doubt “for my security”. None of the online help docs have pictures that match the only screen in the app that actually lets you generate codes.

Update Nov 2024: nothing has improved at HSBC. But I got a screenshot from the website.

Starlink stats for a year

Some data from my automated monitoring. Speed is measured with an Ookla speed test every 15 minutes or (now) every hour: daily min, max, and average. Latency is measured with telegraf native pings to 8.8.8.8: daily min, average. Packet loss is the daily average percentage of ping packets lost. There’s some messy data here; sometimes my house fails over to a 12Mbps fixed wireless link which pollutes these measurements (but only a little). And there’s a suspiciously low bandwidth stretch in December and January that could well be a monitoring bug.

Download speeds
Latencies
Packet loss

Important to read these right. These are daily average statistics: the min/avg/max bandwidth for each day, the min/avg ping time for each day. Each latency measurement is actually several pings sent at once, so I’m taking the average of the average and the min of the min.

The primary pattern that jumps out here is the increase in latency starting in January. That coincides with when I got moved from a Northern California POP up to the Seattle POP (I think via a satellite relay near Winters, CA). Although note the change is gradual; this isn’t a one-off bump in path length. Another possible explanation is that’s the period Starlink started adding a lot more users and I’m seeing buffering.

The min bandwidth graph does not bear out my perception, which is that congestion is getting worse. It’s definitely getting slower every night. Below is a graph of average download speed for 15 minute samples over a week in January; the pattern now is about the same. But the minimum daily I’m getting is still in the 10-20Mbps range just like it’s always been.

Mastodon account migration (Apr 2022)

My old Mastodon instance stopped working. I want to migrate to nelson@tech.lgbt. Unfortunately migration is pretty limited in Mastodon. There is no simple way to move your actual content, your toots. You can move your list of who you follow though, and in some circumstances get your followers to follow your new account. There’s three ways to migrate:

  • Just redirect the old account. This doesn’t actually move any data or set up the new account at all, but it does tell any new visitors you’ve moved.
  • Use the “account migration” tool. This basically does a redirect, but then also “irreversibly force everyone to unfollow your current account and follow your new account”.
  • Migrate manually with data exports and imports.

The first two methods require the server you’re moving from be online and federated. My old server is dead. But I do have a data export archive so I can use that to set up the new account.

What’s in a Mastodon export? It’s a bit messy, there are several files.

  • Who you follow, block, mute. Also lists and bookmarks. These are in separate CSV files you have to download individually. These are the stuff you can usefully import elsewhere.
  • All your toots in an archive, along with a bunch of images. The toots are in a big JSON blob. There’s also some other data like your avatar image. These cannot be imported.

Bottom line, the only thing I can really import usefully is who I follow. And doing that won’t get them to follow me. Mastodon’s blog post says “moving instances is painless and straightforward with Mastodon” but that’s really not true. Not surprised, doing this in a federated system with user security as a top priority is hard.

The import seemed to go smoothly. It’s not instance, the import page says “we’ll get to it eventually”. It seemed to take a few minutes.

The import was not complete, but maybe it takes awhile. My export had 275 accounts I was following. First time I looked after 15 minutes I had about 114 people I was following (according to the new server’s export tool). The second time after 45 minutes it was 177. I don’t expect all 275 of the accounts will ever import, some are from servers that are gone.

I’m starting to get followers again, I suspect because they saw the “nelson followed you” notification. It will be impossible to get most of them over without the old server coming back up.

The nicest thing about my new instance is the skin is now some clean, single column layout of toots. I really hated that old darkmode multicolumn thing!

OpenWRT (RPi4): giving up

I’m giving up on OpenWRT on my RPi4. I’ve spent the last few days getting it working and while it’s mostly good, I don’t trust it. I’m about to go out of town for awhile and I can’t leave my partner with a possibly flaky router, so I’m back to the Ubiquiti router. It’s buggy but I understand what the bugs are and can live with them. OpenWRT is very impressive and would probably work for me, but it requires more tinkering than I want to do. It does not spark joy in me.

The main problem with my OpenWRT setup is the mwan3 failover isn’t working for me. I got woken up by my alarm system loudly beeping, the stupid thing it does when there’s no Internet for a few hours. Starlink had gone down again. That’s not OpenWRTs fault, Dishy itself was out. But the mwan3 failover in OpenWRT didn’t work like it should have.

I could probably diagnose or fix this if I wanted to spend the time. The permission denied error in my logs is probably a good place to start. But I just don’t want to bother. (FWIW failover works if I disable one interface entirely. But that may just be Linux routing working, it has both WAN interfaces as routes. mwan3 is pinging interfaces and logging errors but I’ve never seen it actually mark one bad and switch.)

More generally there’s a bunch of rough edges in OpenWRT. The lack of persistent USB device naming is awkward, and potentially a source of a hard to diagnose problem in the future. The way package upgrades work (or don’t work) makes me nervous. I don’t trust that a full system upgrade will work when the time comes. I don’t like that I had to spend 5-10 hours reading docs and tinkering to get the things set up I want. All in all I want a router to just be an appliance, something I don’t spend time thinking about. OpenWRT is more of a firmware for hackers who want to be thinking about their routers.

I’ve said this before, I’d love something with the ease of use of the old Tomato firmware that’s based on OpenWRT. OpenWRT has improved a lot since 2015, LuCI is a very nice UI. Back then I got a comment that Gargoyle might fit the bill; I see that project is still getting updated, so maybe it’s worth a try. Also maybe my expectations are unreasonable. There’s lots of consumer routers out there that do a basic home LAN just fine, Starlink even gives you one. But I want more; I want multi-wan failover, I want VPN tunneling, I want detailed diagnostic data. It’s asking a lot.

Still I’m glad I spent the time with OpenWRT. I’d definitely reach for it again if I had specialist needs or was in a mindset to be more patient with the tinkering required. It’d also make a fantastic foundation for derived products. I think several commercial routers are sold with some variant of OpenWRT pre-loaded. Rumor has it Starlink’s own router is based on OpenWRT.

OpenWRT + Wireguard (RPi4)

My new, unrewarding hobby of router tinkering continues. This time setting up a Wireguard tunnel between my two houses. I want my two LANs 192.168.0.0/24 and 192.168.3.0/24 to talk to each other transparently via a VPN tunnel. I’d gotten this sorta working between Linux boxes inside the two LANs before but the routing never quite worked. Running a VPN tunnel directly on the router is one reason I’m now trying to set up this RPi4 with OpenWRT.

Long story short, it was very easy to get my OpenWRT router connecting as a client to a working Wireguard server on my other LAN’s Linux box. I can’t fully test this because I don’t have Wireguard setup on the other side’s router yet. But the tunnel seems to be working at least somewhat.

Note to self: my Ubiquiti router at the other house is set up to not answer pings. Ping is not a good test! Ssh is though.

Once again the OpenWRT docs for Wireguard are very good. The basics tell you how to install it including a LuCI interface and this client guide has some extra good info.

It boils down to the same way you set up Wireguard anywhere. Generate a key pair, configure the server to accept the new OpenWRT public key, configure the OpenWRT client to connect to the server and its public key, and you’ve got the tunnel up. It helps to log into the OpenWRT command line and run “wg show” and the like manually, but LuCI actually has a full UI for configuring and monitoring. Note that when you add the interface there’s a Wireguard-specific “Peers” tab you need to configure.

The one big gotcha is the “No Host Routes” option (aka nohostroute) as discussed here; it’s in Interfaces / General Settings. Without this OpenWRT will add a route specifically for the host endpoint specifically on one interface. This interacts poorly with a multi-WAN setup like mwan3. Setting nohostroute tells OpenWRT to not set an explicit route. There’s some concern that if you then configure all traffic on the router to go through the VPN link then Wireguard itself will try to also talk to the Wireguard server via the Wireguard interface, causing some sort of loop or recursion. Not a problem in my case.

In the Peers settings I went ahead and explicitly included Allowed IPs of 192.168.7.0/24 (my VPN endpoint subnet) and 192.168.0.0/24 (the LAN at the other end of the VPN). I’m not sure that’s necessary.

I’m confused about what to put in the Firewall Settings for the wireguard interface. This 2018 guide suggests creating a new zone and configuring rules for it. But then it says “This step is probably optional (you could just add the interface to the lan zone)” and I think that’s probably correct; in general I want to treat the other size of this VPN tunnel as part of my LAN. I definitely don’t want masquerading/NAT for it! I can’t really test this properly until I have a router on the other side set up doing Wireguard. I don’t understand modern Linux firewall rules very well.

All of this is complex and at the edge of my patience for dealing with stuff. OpenWRT and Wireguard are very powerful and flexible tools. More than once I found myself wishing there was some hand-holding simplification for me, a “just press this button to make it work” thing. But then I don’t know how common goals like mine are.

OpenWRT + RPi4: failover and load balancing

I have two ISPs; I want to use Starlink all the time unless it goes down, in which case I want to failover to my fixed wireless. OpenWRT supports this with the MWAN3 package along with load balancing and various forms of traffic-based routing. It’s flexible and a little complicated. The whole reason I am ditching my Ubiquiti router is their long standing bugs in their failover implementation; I’m hoping OpenWRT’s is more reliable.

The MWAN3 docs are excellent but do assume some networking knowledge. Long story short, it’s a set of scripts that implements load balancing and failover by manipulating Linux policy routing. Basically it pings the interfaces and adjusts the routing table appropriately if a connection goes down.

See also my previous post on OpenWRT + RPi4 with a single WAN.

Hardware and device names

I’m using a Raspberry Pi 4 as my router. I’ve purchased two TP-Link UE300 USB ethernet adapters for my WAN ports. They are plugged in to the two blue USB-3 ports. This means I’m going to have two actual hardware ethernet devices for the WAN, eth1 and eth2. (eth0 is the LAN which is the RPi’s on-board ethernet.) Some of the MWAN docs talk about VLANs and switches and devices named like eth1.0; no VLAN needed with the USB hardware.

Unfortunately as far as I can tell OpenWRT has no built-in provision for naming devices consistently. When I was plugging and unplugging things I would see one of my adapters go from being “eth1” to being “eth2” despite it always being plugged into the same port and the MAC address not changing. This is not good, it makes identifying which interface you want to use for what difficult. However I think as long as you don’t hotplug anything the device names are assigned consistently in order. If you look in dmesg there’s messages like these:

usb 2-1: New USB device found, idVendor=2357, idProduct=0601, bcdDevice=30.00
r8152 2-1:1.0 eth1: v1.10.11

USB 2-1 seems to be the name for the upper blue USB port. With two dongles plugged in, USB 2-1 seems to always get named eth1 and USB 2-2 always seems to get named eth2. All bets are off if you unplug and replug things afterwards though.

A better solution would be to name devices by the MAC address or some other (relatively) immutable property of the hardware. I found some notes on doing this online here, here, and here. That last one refers to the OpenWRT “Community Build” for RPi4 but that project looks a bit messy and there’s some drama going on with it so I haven’t tried it.

Anyway, after 5 reboots the device names have been stable so I’m going to stick with this. For my notes:
Starlink, usb 2-1, eth1, WAN1, 5C:A6:E6:AA:BC:9A
SmarterBrodband: usb 2-2, eth2, WAN2, 54:AF:97:5B:F9:63

One last note on naming; OpenWRT has a concept of “interface name” in Networking / Interfaces, a step of indirection from devices names. Ie, I have eth1 named “WAN1” in OpenWRT and a lot of other OpenWRT software uses WAN1 as the name. I ran into a problem because I named my interfaces WAN1/WAN2. The mwan3 scripts default to assuming these names are “wan” and “wanb” and I regret not using those names for simplicity.

Setting up the second ISP

Before you do anything with mwan3 you have to get the second ISP working in OpenWRT. This is as simple as adding it in Network / Interfaces. The “gateway metric” advanced setting is important; Linux will send packets to the gateway with the lowest metric. If two devices have the same metric (which is the default if you don’t edit it) I’m not sure what happens, it looks to only use one of them without mwan3 or some other load balancing configuration.

If you’re using luci-app-statistics this is a good time to go to Statistics / Setup and make sure you have graphs turned on for all of your network interfaces.

Installing and using MWAN3

This is as simple as opkg install mwan3 luci-app-mwan3 (or the LuCI equivalent). However the moment you install mwan3, mwan3 is going to start running and doing routing. The default config is reasonable, it tries to load balance on “wan” and “wanb”. But because I used “wan1” and “wan2” instead as my names nothing worked. Ironically I hadn’t even installed the LuCI interface yet, so without I had to edit config files by hand.

The config file is in /etc/config/mwan3. There is also a “mwan3” command line tool that is very helpful when tinkering.

The LuCI interface is in two places. Network / Load Balancing is where the config is done. Status / Load Balancing is the status page. (Some of the docs refer to an obsolete location for the status page.)

Configuring MWAN3

The docs are great so I won’t try to reproduce them. In summary though you describe interfaces, one per ISP connection. Then you define members which are statements like “wan-m1_m3 uses interface WAN1 with metric 1 and weight 3”. Members are combined into policies; the member that’s currently up and valid and has the lowest metric is the one the policy will use. If there’s two members with the same metric, it will load balance according to the weights. Metrics get combined into policies like “balanced” (use both wan and wanb) or “wan_wanb” (failover; use wanb only if wan is down). Finally you define a set of rules which say “traffic of this type gets sent out this policy”.

It’s a complicated and flexible system. The default config is to load balance the two connections with slightly unequal weights. I just edited the rules to use the “wan_wanb” policy instead of “balanced” to get strict failover behavior instead. (I also edited to accomodate my different naming convention but only for interfaces; I left mwan’s “wan” and “wanb” naming for members, policies, etc).

There’s a lot of subtle failover behavior you can configure, particularly in the interfaces section. That’s where you set things like ping intervals or how many pings have to fail before the interface is considered dead. I’ve left all the defaults in place other than changing the IP addresses it pings. The package uses the docs’ defaults except reliability is set to 2. I think that means the behavior is it tests every 10 seconds. A test is it pings each of 4 hosts once with a 4 second timeout; if 2 of the pings succeed then the test passes. If 5 tests fail in a row the link is considered dead. 5 successes and the link is alive again. There’s a complicated extra set of heuristics for “check_quality” but I believe those are disabled by default.

There’s also a global option to enable syslogging. Turning that on to “notice” gives a reasonable, non-spammy syslog of failed pings and failover.

Does it work?

Yes! So far so good. It all seems a bit complicated for basic failover but once I got going the configuration was really pretty simple.

One gotcha when testing; if you search Google for “what is my ip” it will helpfully show you your IP address. But this might be a little out of date; in some cases you can still have a browser connection open on the backup WAN interface even though new connections are being done on the primary WAN. I think curl http://api.ipify.org/ is a more reliable way to verify what your router is choosing at the moment.

Observed behavior on the testing is a bit more complicated than I thought. The syslog messages from mwan3track talk about a “score” that’s getting incremented faster than the 10 second interval I thought it had.

Basic failover seems to be functioning. I’ll know more in a day or two, I’m curious how well the default heuristic is going to work with Starlink’s “drop out for a few seconds” failure mode as well as the nightly congestion. The worst thing is if the router flaps over to failover mode too often, sometimes it’s better to wait out a transient failure. Will need some tuning no doubt.

I want to give a shout-out to both the LuCI mwan3 UI and the Wiki docs. They’re both quite understandable and nicely designed.

Update: failover didn’t work last night. Around 4am Starlink got a firmware update and rebooted itself. My monitoring tells me my house couldn’t ping 8.8.8.8 for about 4 minutes afterwards. Looking at the syslog it’s clear mwan3 was aware of the outage; it detects that the network lost carrier and talks about setting the link down, then up again in a few seconds. There’s talk about disabling the interface, etc. But there’s no logging about failed pings (which I would expect) and judging by my monitoring, it did not fail over to the backup. There’s also several log lines with errors in them like “netifd: WAN1 (10264): Command failed: Permission denied” which does not inspire confidence.

OpenWRT on Raspberry Pi 4

I’m fed up with my Ubiquiti routers. UnifiOS has a bunch of bugs related to WAN failover that have been there for a year+. Also a lot of mysterious behavior and some odd engineering problems. And still no official solution for Wireguard last I looked. So I want to switch (back) to OpenWRT for routing. I want three ethernet ports in the end; LAN, WAN, and backup WAN. I’m not using the WiFi on the RPi4 at all. I could, but I have hardware with better antennas.

These notes are a work in progress and are not a fully followable cookbook. It took me like 5 hours of tinkering in different orders to get this going. Don’t worry, it’s not normally that hard. Here are some other sources I found helpful for doing this: one, two, three.

Step 1: Hardware and device drivers

OpenWRT runs on all sorts of hardware but I’m going to do this with a Raspberry Pi 4. It’s way more powerful CPUs and RAM than a typical router. The networking is a bit weaker though. The RPi4 gives you one ethernet port on the PCIe bus and the rest have to be USB ports. The TP-Link UE300 is a commonly recommended USB adapter, it has an RTL-8053 which is well supported. My LAN will be on the on-board ethernet, the WAN links on USB. I think this setup is good enough to support gigabit throughput and is certainly good enough for Starlink’s max 200 Mbps. I’m told you can do traffic shaping and VPN stuff with very good speeds using the RPI4 CPU, but I haven’t tested it. (Few consumer routers can do gigabit Internet with these fancies.)

Another interesting hardware option is an RPi CM4 with a router board. That gives you two full Gigabit ethernet ports connected to the PCIe bus. A third option is to only have a single ethernet port and use VLAN tagging so the router can work in a “router on a stick” mode.

Step 2: Basic install

OpenWRT has pretty good docs for running on an RPi 4, I just followed them to get a basic system going. Note that the RPi 4 is way more powerful hardware than OpenWRT is normally aimed at, so some of the extreme things that OpenWRT does to save resources may not be necessary. Some folks recommend using ext4 as the filesystem instead of the compressed SquashFS. There’s also something about resizing the partition to use all the SD card storage. I didn’t bother.

Flash your SD card, then boot the router without the USB ethernet devices plugged in. (Or with, it doesn’t matter, but don’t plug in any WAN cables yet.) Plug a laptop ethernet into the on-board ethernet port. OpenWRT should come up and be serving DHCP on the ethernet. Point your laptop to http://192.168.1.1/ and you’re logged in to LuCI, the OpenWRT web interface. Note that OpenWRT will call this ethernet port eth0 and it will be bridged into br-lan.

Update May 2023: this HOWTO is more up to date than my notes. It uses OpenWRT’s firmware selector to prepare a download with the ethernet drivers you need in step 3.

Step 3: enabling your USB ethernet device

There’s one hard thing setting this up; OpenWRT doesn’t have the kernel drivers for USB ethernet installed by default. You need the kmod-mii, kmod-usb-net, and kmod-usb-net-rtl8152 opkg packages (IPK files) installed. No configuration needed, but you do have to install the packages. The problem is you’re not connected to the Internet to just install them.

You have several options for getting them installed. My choice was to manually download the needed packages from the OpenWRT repository to my laptop, then upload them via LuCI to the router. (You have to install them one at a time and click “Dismiss” manually on the install popup). It’s also possible to plug a WAN cable into the one working ethernet and get access to the router somehow (keyboard and screen? routing tricks?) to install them. I like the “2nd way” in the linked Reddit post; you make a custom OpenWRT image that included the necessary drivers.

Step 4: configuring the WAN

Now that there’s an ethernet device for the WAN you have to configure it. Do this in LuCI; go to Network / Interfaces and add an interface for eth1. Call it WAN and then go to firewall settings and put it in the WAN zone. This is a little mysterious but I think that’s all you have to do. I rebooted somewhere in here just to be sure that it was all working right.

Step 5: Improve OpenWRT

The blessing (and curse) of OpenWRT is it’s a very flexible Linux system and you can do a lot with it. A search for packages matching “luci-app-*” is a good way to see what’s available. Here’s some of what I’ve done.

Update the software lists and manually update each package one at a time. The updates aren’t exactly recommended but before I did that some new LuCI stuff I installed broke the old LuCI install until I updated it.

Install some quality of life packages: less, bash, curl, nano, mg (for me).

Install luci-app-statistics. You also have to enable this by going to Statistics / Setup and saving the config.

TODO / options

Some things I have not yet done but may get around to (and update this blog post if so)

Install mwan3 for failover. Done, see this post for my notes.

Install wireguard for a VPN. Done, see this post for my notes.

See if I can export monitoring stats somehow to my InfluxDB instance for plotting in Grafana.

Install luci-app-sqm for traffic shaping

My own notes

Some notes of interest to me only.

The network interfaces are:
LAN eth0/br-lan E4:5F:01:5F:AB:D8
WAN1 eth1 5C:A6:E6:AA:BC:9A
Wireless not enabled

System / logging / external system log server to my Linux server on the LAN

DHCP range: 192.168.3.2 - 192.168.3.199

Override DNS servers and use 8.8.8.8 and 8.8.4.4

Set a static route for Starlink for 192.168.100.1 / 255.255.255.255 on eth1.

Some static leases (all have a lease time of 86400)
gvl 94:c6:91:1e:c8:38: .75
printer 84:25:19:0e:7b:0b: .67
pvspi0 e4:5f:01:78:d7:f9: .140

Starlink DHCP vs UnifiOS

My Starlink connection will work for days, then get in a mode where every 5 minutes the connection will fail for 30 seconds before it comes back. Long story short it looks like Starlink has a problem where it’s not responding to DHCP address renewals sometime.

Complicating matters; this is a Ubiquiti USG-3P router running UnifiOS and I have a backup WAN configured. Ubiquiti’s backup WAN stuff is a bit flaky, and also the failover does tend to both hide connection problems (when it fails over) and cause some (the failover itself breaks existing sessions.)

I’ve opened a support ticket for this, TIK-213261-55007-82. And I got two replies!

Apr 12: our engineering team is aware of cases where customers are having WAN DHCP renewal issues and the 5 minute lease expires. Our DHCP server engineers are actively working on this and I did send a link to the blog post to the lead engineer, appreciate the write up. Apologies for the issues and please bear with us.

Apr 15: our network software team deployed two fixes last night to hopefully resolve the DHCP renew issue

I finally got some DHCP logging set up to understand what’s going on at the router when the problem happens. Details below, mostly for my own troubleshooting.

The USG-3P has three ethernet ports. They are

  • Starlink, the primary WAN: on eth0, typically at an IP like 100.74.162.37.
  • My LAN: on eth1, 192.168.3.1
  • SmarterBroadband, the backup WAN2: on eth2, 10.33.1.1

My understanding of the DHCP behavior is that when connected, Starlink gives out an IP address in the CGNAT block 100.64.0.0/10 with an expiration of 5 minutes. Ubiquiti’s DHCP client accepts this address and binds to it. It also renews it every 2.5 minutes, half the lease time. If the renewal doesn’t happen in that 2.5 minutes then the link is effectively dead, packets to it fail, and the WAN failover process starts. (DHCP clients are not allowed to keep using an address past the lease expiration!) I’m not certain how the DHCP request is answered by Starlink, but my guess is the DHCP request goes up to the satellite and down to a ground station in Seattle where Starlink answers it. My working theory is those DHCP requests aren’t getting answered.

Update: there are reports that Starlink is starting to serve 1 hour DHCP leases. (Later they say it went back to 5 minutes; maybe a temporary change?)

Observed

When things are going well, every 2-3 minutes there’s an entry like this in the log:

2022-04-09T20:30:07,108 <30>Apr  9 13:30:07 ubnt dhclient: bound to 100.74.162.37 -- renewal in 138 seconds.
2022-04-09T20:32:25,233 <30>Apr  9 13:32:25 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-09T20:32:25,292 <30>Apr  9 13:32:25 ubnt dhclient: DHCPACK from 100.64.0.1
2022-04-09T20:32:29,566 <30>Apr  9 13:32:29 ubnt dhclient: bound to 100.74.162.37 -- renewal in 142 seconds.

I believe this is an ordinary DHCP renewal process. The router has an address so it just sends a DHCPREQUEST to request the address again. The server answers back with a DHCPACK and everyone continues along.

When things are going badly, it looks like this:

2022-04-12T15:22:11,377 <30>Apr 12 08:22:11 ubnt dhclient: bound to 100.74.162.37 -- renewal in 117 seconds.
2022-04-12T15:24:08,373 <30>Apr 12 08:24:08 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:24:19,743 <30>Apr 12 08:24:12 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:24:20,862 <30>Apr 12 08:24:20 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:24:39,539 <30>Apr 12 08:24:27 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:24:47,472 <30>Apr 12 08:24:47 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:24:59,338 <30>Apr 12 08:24:57 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:25:07,502 <30>Apr 12 08:25:07 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:25:23,323 <30>Apr 12 08:25:23 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:25:43,693 <30>Apr 12 08:25:43 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:25:57,522 <30>Apr 12 08:25:57 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:26:12,669 <30>Apr 12 08:26:07 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:26:17,713 <30>Apr 12 08:26:17 ubnt dhclient: DHCPREQUEST on eth0 to 100.64.0.1 port 67
2022-04-12T15:26:28,982 <30>Apr 12 08:26:28 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T15:26:39,022 <30>Apr 12 08:26:39 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T15:26:56,422 <30>Apr 12 08:26:56 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T15:27:10,770 <30>Apr 12 08:27:10 ubnt dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3
2022-04-12T15:27:10,835 <30>Apr 12 08:27:10 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T15:27:10,835 <30>Apr 12 08:27:10 ubnt dhclient: DHCPOFFER from 100.64.0.1
2022-04-12T15:27:10,910 <30>Apr 12 08:27:10 ubnt dhclient: DHCPACK from 100.64.0.1
2022-04-12T15:27:16,963 <30>Apr 12 08:27:16 ubnt dhclient: bound to 100.74.162.37 -- renewal in 134 seconds.

That sure looks to me like Starlink is just not answering the DHCP request. An abbreviated timeline:

  • 15:22:11,377: the router thinks it has a valid address. It should have an expiration of 300 seconds and therefore be renewed in 150 seconds. But it takes awhile for it to arrive, so the actual renewal is scheduled for 117 seconds. (This delay seems normal.) The router should send a DHCPREQUEST to renew the address at 15:24:08. The address will expire around 15:26:38 or maybe a little earlier.
  • 15:24:08,373: the router sends the first DHCPREQUEST to renew its address. It sends it to 100.64.0.1, presumably the IP address at the other end of the Starlink connection.
  • 15:24:08,373 to 15:26:17,713: the router hasn’t gotten a DHCPACK reply. So it keeps sending requests every 10-20 seconds.
  • 15:26:28,982 to 15:26:56,422: still no reply. Now the router starts sending DHCPREQUEST to 255.255.255.255. I think that’s likely because the 100.74.162.37 lease expired and so the router now has no idea what address is at the other end and it’s starting over with a broadcast.
  • 15:27:10,770: the router sends a DHCPDISCOVER. I’m not certain but I think this means the router has given up on the old address entirely and is starting over as if it has never heard of the network.
  • 15:27:10,835: the router receives a DHCPOFFER from Starlink. We’re back in contact! This took 65ms, or just about one round trip on the satellite link.
  • 15:27:10,835: the router sends a DHCPREQUEST, presumably securing the address it was just offered. (Note the log has the request coming before the offer, but I think the log messages just got swapped. They have the same millisecond timestamp.)
  • 15:27:10,910: the router receives a DHCPACK from Starlink, 75ms after the request. We’re connected again!
  • 15:27:16,963: the router logs that the IP address is bound. Not sure why this takes 6 seconds to announce, but that’s all happening inside UnifiOS.

I should note that in all 6 failures I’ve had this morning (once every 5 minutes), only one DHCPDISCOVER has been needed to get the connection going again. Each time one is sent it gets immediately answered. There’s a different kind of outage I’ve seen on previous days, where the router eventually does a DHCPDISCOVER and gets back the address 192.168.100.100 with a very short 5 second lease. That’s Dishy’s internal DHCP server answering with a local only address, a mode it gets into when it loses its link to Starlink’s ground station entirely. That’s a very old behavior I’ve discussed on this blog before. This every-5-minutes outage is relatively new, a few months old.

Interpretation

My interpretation of this is Starlink’s DHCP server has forgotten we had a lease. My router keeps trying to renew the lease with DHCPREQUEST and gets no answer. Finally the router starts over wtih a DHCPDISCOVER and Starlink responds immediately. That’s consistent with the satellite link basically working but Starlink’s DHCP server failing to renew my address. But I’m guessing here.

What I do know is it’s really annoying having your connection drop every 5 minutes. The WAN failover is kind of making things worse; it takes UnifiOS about 30 seconds to decide to failover. By the time it’s done that Starlink has come back up and so the router switches back to it. Basically every 5 minutes the network is down for about 30 seconds. Any TCP sessions with activity during the failover period get reset.

But the failover isn’t causing the problem, the lack of DHCP response is the real problem.

Updates / notes

A useful command for checking the logs for Starlink-related DHCP stuff

grep dhclient 192.168.3.1.log | grep -v eth2 | fgrep -v 10.33.1.1

Just saw a bizarre failure that I think must be a Unifi OS bug.

2022-04-12T23:54:16,623 <30>Apr 12 16:54:16 ubnt dhclient: bound to 100.74.162.37 -- renewal in 117 seconds.
2022-04-12T23:55:40,224 <86>Apr 12 16:55:40 ubnt sudo:     root : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/sbin/dhclient -q -cf /var/run/dhclient_eth0.conf -pf /var/run/dhclient_eth0.pid -lf /var/run/dhclient_eth0.leases -r eth0
2022-04-12T23:55:40,292 <30>Apr 12 16:55:40 ubnt dhclient: DHCPRELEASE on eth0 to 100.64.0.1 port 67
2022-04-12T23:55:44,280 <86>Apr 12 16:55:44 ubnt sudo:     root : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/bin/rm -f /var/run/dhclient_eth0.pid
2022-04-12T23:55:48,006 <86>Apr 12 16:55:47 ubnt sudo:     root : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/bin/sh -c /sbin/dhclient -q -nw -cf /var/run/dhclient_eth0.conf -pf /var/run/dhclient_eth0.pid  -lf /var/run/dhclient_eth0.leases eth0  2> /dev/null &
2022-04-12T23:55:48,213 <30>Apr 12 16:55:48 ubnt dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3
2022-04-12T23:55:48,242 <30>Apr 12 16:55:48 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T23:55:48,242 <30>Apr 12 16:55:48 ubnt dhclient: DHCPOFFER from 100.64.0.1
2022-04-12T23:55:55,691 <30>Apr 12 16:55:55 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T23:56:04,640 <30>Apr 12 16:56:04 ubnt dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 7
2022-04-12T23:56:11,101 <30>Apr 12 16:56:11 ubnt dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 13
2022-04-12T23:56:11,164 <30>Apr 12 16:56:11 ubnt dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
2022-04-12T23:56:11,164 <30>Apr 12 16:56:11 ubnt dhclient: DHCPOFFER from 100.64.0.1
2022-04-12T23:56:11,219 <30>Apr 12 16:56:11 ubnt dhclient: DHCPACK from 100.64.0.1
2022-04-12T23:56:17,169 <30>Apr 12 16:56:17 ubnt dhclient: bound to 100.74.162.37 -- renewal in 134 seconds.

This looks like the router just decided to restart dhclient. And the first thing it did was a DHCPRELEASE, breaking my connection. I have no idea why the router did this but it looks like Starlink responded quickly to the requests the router was making.

Measuring ISP congestion without load tests

My Starlink seems congested in the evenings. What are some strategies for measuring the congestion? The simple one is to run a speed test, see below for details on that. But speed tests are wasteful. Is there some lower impact monitoring I can do? This post is a bunch of ideas and questions, no solution.

Update Nov 2023: I’m finding IRTT is pretty good. It’s a fancy ping. It does a good job measuring both latency and packet loss and it’s not hard to pick out the signal of evening congestion.

Pings

My first thought was just to measure ping latency and packet loss; if the ISP is congested then latencies go up (queueing) and packets start getting dropped. Pings are a lot less traffic than load tests and there’s a lot of software to do them. This sort of works but it’s pretty noisy and pretty far removed from what I really care about, which is “can I use the Internet to do stuff?”

It might be smarter ping / packet loss measurements could work. My existing ping is already a little clever; every 15 seconds Telegraf sends 5 ICMP pings at once and reports what percentage was lost and a latency distribution. Packet Loss Test has an interesting take on measuring latency and jitter with WebRTC (in the browser!). iperf’s bursts of UDP packets are also a good way of measuring instantaneous throughput and could be done without using too much bandwidth. Ping probing is an idea worth exploring.

A related idea I wrote up is using some sort of traceroute-like probing to not only detect congestion but guess where it’s happening in the network. I think this is probably impractical in the general case, but maybe a custom solution for Starlink’s infrastructure could be helpful.

Passive monitoring

My next thought was to measure TCP retransmits at the router for existing traffic as it goes by. They’re a primary cause of low bandwidth and a primary signal of congestion. This should be doable in theory with stateful packet inspection in the router but I’ve never seen any software that does it. Anyone know about it? I also think the resulting data might be pretty indirect.

The other solution would be to measure TCP retransmits at the client endpoint. This is easy in Linux, probably not hard in Windows, but probably impossible on, say, my Roku streaming video device. It sounds like a significant hassle.

Any passive monitoring has a problem that you aren’t really sure if the congestion is on your client end or some problem on the server end. Load testing services presumably solve this by being well provisioned. But I suspect in practice most of my TCP traffic is going to very well connected sites like Youtube or Cloudflare and any slowness is more likely on my end than theirs.

Load test results

Running load tests is certainly the easiest thing and I’ve been doing that for months. Here’s a week of running an Ookla speedtest every 15-60 minutes:

The average of 130 is great. But every evening it dips to well below 50 Mbps. Worst measured is around 10Mbps. This testing shows the congestion problem pretty well.

The problem is load tests are expensive: each one download 250 megabytes of data over about 20 seconds (when things are fast). When I was running 4 an hour the speed tests were a significant fraction of my overall daily bandwidth usage, maybe 30% or more. They were making the video streaming worse. I’ve cut that back to once an hour but it’s still a waste.

Community monitoring

One bad thing about load testing is that it’s selfish; only I get the results of all that wasted bandwidth. Starlink Status tries to do better, by collecting stats from many users and sharing them. It’s a great idea but the execution is a bit lacking.

What would be really great is if Starlink were transparent and published its own traffic and congestion stats. Then I could just look to see how they’re doing. A few independent users could run their own tests to verify they aren’t misleading people. It’d be cool but I’ve never heard of an ISP volunteering this kind of competitive data.

Home LAN disaster mystery

I truly b0rked my home network yesterday. It took more than an hour to fix. I still don’t understand what went wrong but I’m wondering if my ethernet switches got in a bad state.

It started when I tried swapping my Ubiquiti router out for an OpenWRT router. The new router was working OK, the whole network was fine. I installed a few packages to OpenWRT (including wireguard, unconfigured) and rebooted it and then my network was down. No DHCP, couldn’t even connect with a static IP, OK I figured OpenWRT somehow broke and so swapped back to the old Ubiquiti router.

That’s when the mystery started. Nothing worked with the old router plugged back in. Again no DHCP, static IPs not working. Lots of blinking lights on the switches though, suggesting maybe some networking was still happening. I tried power cycling the router and the switches in the path between my computer and the router. No luck.

So then I began a tedious process of getting the network working starting from the router. Unplugged everything but one laptop. Still no DHCP. But static IP worked. That’s when I learned the router’s DHCP server wasn’t running. It was before! Not sure if UnifiOS “lost” the DHCP server setting? The Unifi controller was offline but my understanding is the router should keep its last config, which should have included DHCP service. Weird. So that’s one mystery, why did my router stop doing DHCP?

Fortunately the minimal configuration UI on the router itself does let you turn DHCP on. Turning that on and I had one router working with one laptop. And soon after that, one switch plugged into the router. But the Unifi access point plugged into the switch still didn’t seem to be working; connecting via WiFi got no DHCP. Weird.

But it got weirder when I went to the second switch, the big one at the center of my LAN and plugged into the first switch near the router. Nothing plugged into it worked. The ethernet cable coming to that switch worked on the laptop, but plug that into the switch and then the laptop into the switch and boom, no working ethernet. I finally just replaced the switch entirely and suddenly everything started working. Including the Unifi access points.

Today I tested the suspect switch and it seems fine. Also the router seems fine. So that’s another mystery, why did this equipment look like it wasn’t working after rebooting a router and works fine today?

One possible explanation for all of this is that somehow my ethernet switching got in a bad state. And that state was somehow polluting the network so nothing was working. I don’t think this is a very good theory. The switches are simple unmanaged Netgear GS108s, pretty bulletproof. No persistent state at all and nearly stateless entirely. I did try power cycling the switches a few times to no effect.

There is a bit of state in ethernet switches though: the spanning tree protocol. Also some sort of memory of which ethernet devices are plugged in to which port. Could that somehow have gotten corrupted?

My network is pretty simple. There’s no physical loops in the network topology (other than that implied by wifi). I’m not using VLANs at all, although I do note OpenWRT has some default VLAN configuration that I don’t understand and didn’t alter. There’s a total of maybe 5 unmanaged switches and 60 devices.

Honestly I’m just speculating about magical explanations. I don’t really know. I do know I’m scared to try swapping routers again.

Update: I tried the OpenWRT router again and failed, although not as catastrophically. It worked fine on first setup, then I rebooted it to test it and suddenly not only did I not have Internet, but the router wasn’t answering anything at all. No idea what’s going on. One guess is installing the wireguard packages with opkg somehow caused a problem, even though I didn’t configure wireguard. It also looks like Starlink’s Dishy terminal is not immediately answering DHCP requests from the router the moment it asks, so that’s not great. That doesn’t explain why I couldn’t even talk to the router at all though.

Google Takeout notes

I finally got my Google Takeout archives downloaded, the most important of my cloud backups. I tend to prefer Google for my services so a lot of stuff is there dating back 20 years. Google Takeout is an excellent product. What’s in the dump?

I chose to download Takeout’s default: everything but Access Log Activity. It came to about 67GiB of zip files, 72GiB uncompressed.

The top level of the dump includes a nice HTML explanation of what’s in it. With per-product documentation for the types of files you’ll find there and what formats they might be in.

Here’s info on some of the meaningful data I found that I was expecting to see.

  • 9GiB: Mail. The biggest and most precious of all my Google data. All stored in a single .mbox file, which is awkward but not an unreasonable choice. The file is not date sorted. The volume per year is confusing: 2012 and 2020 are big at 13,000+ messages. 2019 I only had 6000. Maybe it’s spam related. There’s also a few extra data files for things like filters, blocked users, etc.
  • 35GiB: Photos. I’m a heavy user of Google photos. Contains both original and edited images, also metadata in a simple JSON format. A little confused at the directory structure; many of the files are in folders like “Photos from 2020” but some are in per-Album directories, I think there are duplicates.
  • 23GiB: Drive. If you asked me I’d tell you I didn’t use Google Drive. I have no idea how this got so big. The useful stuff there is copies of my Google Docs; spreadsheets mostly. The big stuff is a bunch of photos I then imported to Google Photos, I could probably delete them from Drive. It’s a very random and poorly organized collection of stuff.
  • 2.5GiB: YouTube. All the content I’ve created (videos, comments). But also detailed watch and search histories going back 11 years.
  • 0.3GiB: Groups. MBOX format archives of Google Groups I’m an admin for.
  • 0.1GiB: Contacts. VCF format contact lists.
  • 0.1GiB: Calendar. ICS format, single file.
  • 0.3GiB: Location History. JSON files tracking my movements, used for Google Timeline.

And some of the less interesting or accidental stuff.

  • 0.3GB: My Activity, Google Pay. The biggest surprise to me; Google records meticulous details on when I use specific products, there’s online version of the product here. Goes back at least 10 years and includes Android apps, details of what Google Map views I’ve looked at, credit card transactions, YouTube video views, every search query for two years. It’s all stored in a generic format that seems to apply across Google products. Also the dump is an absolutely terrible HTML format with like 4KB of styled HTML per record. Example of a record for an Android app launch:
  • 0.1GiB: Maps. Data spread out over several directories. Bookmarked places, some KMZ files for custom maps I made.
  • 0.4GiB: Location History. Google’s recorded where my phone has been since I first installed Google Maps. They have a nice history browser for this, I also built my own visualizer product for the data. I really like having it but I think most people would find it surprising and creepy Google keeps this.
  • 0.7GiB: Google Play Games Services, Google Play Store, Android Device Configuration Service, Recorder. Stuff related to my Android phone, including a record of every version of every app I’ve installed and some saved game state.
  • 0.8GiB: Nest, Google Home. Stuff about my thermostat. Including 2 years of detailed temperature readings, etc from my house.
  • 0.6GiB: Blogger. I forgot I ever had a Blogspot blog but google didn’t. Also records of my comments on a lot of other blogs.
  • 0.6GiB: Voice. I have a Google Voice number I basically never use. But it gets spam voicemails, for which sound files and text transcripts have been saved for 7+ years.
  • 0.4GB: Google Account, Profile. A record of a year of explicit logins (as opposed to passive authentication). Love the inactive account emails I apparently wrote a few years ago: “What a horrible thing, but apparently I’m no longer able to access my Google account which means I’m likely dead or incapacitated.”
  • 0.1GB: Chrome. I don’t use Chrome much so this is very small. Among other things it contains a history of visited URLs going back 3 months.
  • 0.1GB: Hangouts. An archive of some GChat messages from 2017?

I’m pretty sanguine about all this data. I want Google to be keeping a lot of data for me and I trust them to be careful caretakers of it. Some of it is incredibly useful; I was really excited when I learned Google Maps had my location history, for instance. Google does a reasonable job letting you control just what you can track and I really appreciate being able to download the data.

The My Activity stuff is the one thing that made me nervous. Partly the awful format is coloring my impression. (There’s several projects on GitHub that parse and analyze it.) But also they’re storing a lot of sensitive data in a generic way that’s not sensitive to the particular app. I don’t really care they have a record of my credit card transactions, but I am a bit nervous at this second record of my Google Maps views or the exact times and places that I launched Grindr. I believe Google keeps this data in this format for security audits.

Data export from cloud services

Goodreads lost all my data, writeup here. This hammered home the value of data export services for making my own copy of stuff. I had an export from last July so the Goodreads loss wasn’t entirely catastrophic. Some notes on other data export services.

Data export is obviously a competitive problem for services. If I can’t get my data I can’t easily migrate to a different service. So evil companies want to keep you locked in. Consequently the data export products are often not very good. Countering that are laws like the GDPR and CCPA which give consumers rights to request their data. I’m finding most of the big services I care about do have a reasonable export service. A good hacker spirit also still pervades in some tech companies, they build export because they think it’s the right thing for users.

Google Takeout is the gold standard. The Data Liberation Front did pioneering work in convincing a company to provide export tools many years ago. The tool now works very well. I’m particularly impressed there’s a way to set up a new data export every two months; all the other services are one offs.

Most of these data export services can be slow. Various nonsense explanations (“for your security”). I cynically expect companies keep them slow to be awkward. But one insider I asked confirmed that they can also be slow for legitimate technical reasons. If you’ve got, say, a real-time messaging system then scraping back for 15 years of message history can be pretty hard on the datastore. Backup requests are seldom time critical so built-in throttles make some sense.

It’s a big problem to actually do anything useful with the data dump once you get it. Some of the services (Twitter) include little webapps to at least sorta browse the data. Some just give plain CSV or JSON dumps and you’re on your own. I was hoping to find a diversity of wonderful open source software that could consume these exports. But in retrospect of course not; building those is a lot of damn work.

There’s less organized community around data exports than I’d hoped to find. The IndieWeb world is a good starting point. Datasette is one general purpose data viewer; Dogsheep is a nice collection of tools to import various formats in to sqlite for Datasette. HPI is another interesting general purpose viewer toolset. Also FreeYourStuff which seems to include some scrapers for sites without export tools.

Some of the exports reveal a surprising amount of extra data I didn’t know the sites had. Feedly has a list of everything I’ve read with dates, for instance, which is kinda neat! Facebook has a huge amount of stuff, some alarming, it would take awhile to comb through what all they’ve collected on me. “apps_and_websites_off_of_facebook” seems to be surveillance capitalism in action.

A thread I need to follow up on is what the IndieWeb kids call POSSE: Publish (on your) Own Site, Syndicate Elsewhere. Make it so you own a copy of all the data as you create it. It makes a lot of sense, Cory Doctorow has written about how he does that. It’s a lot of work.

I spent some time today pulling backups for data of all the sites I could think to check. I’ll update this list as I discover more. It’d be awesome to automate refreshing these backups every month or three but given all the security and performance issues that seems difficult.

2856    ./pinboard
56696   ./23andme
601960  ./twitter
4524    ./metafilter
5772    ./feedly
744212  ./facebook
316     ./goodreads
24      ./letterboxd
1356    ./wordpress
8       ./reddit
4       ./google
8       ./yelp
8       ./amazon

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.

vs.code: playing well with others

I very much like my idiosyncratic coding setup with proportional fonts and automatic code formatting in VS.Code. But it doesn’t play well with others. Every time I save a file it completely reformats it in my preferred way. Not popular at pull request parties.

Making per-workspace settings that are more collaboration friendly is very easy thanks to VS.Code’s flexible settings. It basically boils down to creating a .vscode/settings.json file in the project workspace with a few settings to override the weird ones I have. By far the most important is “format on save”; the others just make my display fixed width like most people’s so I see what they’re seeing. Here’s the overrides I have in my workspace settings:

{
        "editor.fontFamily": "Consolas",
        "editor.letterSpacing": 0.0,
        "editor.tabSize": 4,
        "editor.formatOnSave": false,
}

WSL copy/paste clipboard

Useful command line pipeline tools for WSL, similar to MacOS pbcopy and pbpaste.

To paste the contents of the Windows clipboard into a WSL shell pipeline

powershell.exe Get-Clipboard | wc

To put the outputs of a command into the clipboard

echo foo | clip.exe

That’s the basic version. There’s a nicer version described here or packaged here suitable for installing. It uses sed to strip the DOS newlines and extra newline out of the clipboard content. Also uses tee in front of clip.exe, I think so that it will echo the output back to stdout as well.

Pretty clumsy having to invoke this code! But I believe WSL 2 has no API for accessing the Windows clipboard. It’d be simple enough to imagine in WSL 1’s emulator, but since WSL 2 is more of a VM approach it’d be more work. And then it’d be some weird WSL system call no other Linux understood, anyway. Although... WSL-G must have clipboard support, I wonder if there’s an alternate approach.

My custom solar monitoring system (PVS6)

I’ve been tinkering with monitoring my solar system and have come to a fairly nice useful setup. Time for a post documenting where I am. The details on how I did all this are in previous blog posts but I’m summarizing here. Some code in this gist.

The Display

Daily view

The daily view is focused on giving me a basic picture of my electricity usage. Green is production for the day, black is the PVS6 measurement of net (ie: production - consumption). Yellow is PG&E’s own view of net. I suspect PG&E’s data may be more correct; I’m not sure if the PVS6 CT sensors measure reactive loads correctly. Doesn’t much matter anyway; PG&E is the authority whether they are right or wrong. Mostly I just care that they are close. (Jan 7 is a data measurement anomaly.)

Minute-by-minute view

This view gives a lot of detail minute by minute. The top panel is a detailed view of production and consumption, what is a single bar in the daily graph. The second graph compares production to a forecast. Below that are details of individual panel production. The individual sparklines towards the bottom are fun; the panel in the upper left goes to 0 in the morning in the shadow of the chimney on my roof. At the bottom is a simple sparkline of lifetime net production, I had a little party when it passed 1MWh.

Implementation

The data import code is all in this gist. The Grafana panels are not shared anywhere, sorry.

Here’s all the places I’m pulling data.

  • PVS6: the Sunpower solar monitoring system
  • PG&E: manual downloads via their “Big Green Button”
  • Predictions: forecast.solar

The whole system is built with Telegraf collecting the data into an Influx database and a Grafana dashboard to visualize it. What a great set of tools those are! A real pleasure to learn and work with.

The PVS6 stuff is the bulk of it. Turns out Sunpower has a JSON endpoint on a web server in your PVS6 and folks have worked out how to interpret the data. It’s pretty hacky; I’m using a Raspberry Pi to proxy the data onto the rest of the network. I’ve written a ~200 line Python script to collect the JSON data from the PVS6 every minute and emit it in Influx wire format for import. It also does a little analysis within the minute’s dataset to facilitate easier graphing.

The PG&E import is a very simple bit of Python code that converts PG&E’s data into Influx. I have to do this download by hand in the website right now. They do have an API but it requires some sort of signup I haven’t tried to do yet. I should add that PG&E’s Big Green Button CSV export is really quite good. The CSV data is clean and simple. And they have history! I was able to get 9 years of this house’s electricity usage. Nicely done.

The forecast.solar import is also very simple. They have a easy-to-use API where you tell them your location and the size and orientation of your solar system. Then they give predictions for power generated, including weather-corrected. The free version of the API is fine for this use; I download a new prediction every six hours.

Next steps

I plan to keep tinkering with the data display. I suspect as time goes on I’ll be more interested in the daily summaries than the per minute view, so I’ll probably pay more attention to that.

It’d be nice to automate the PG&E data download.

I’ve had some thought about packaging this all up as a Raspberry Pi image. I think the whole thing could run on pretty much any flavor of RPi, it’d be like an add-on to the PVS6 with a nice local web dashboard. But that’s a lot of work and I have zero interest in offering a product that uses an unauthorized Sunpower interface. Sunpower has a fairly decent monitoring website with something much like my daily summary view. They also have tools for installers showing per-minute data. Those aren’t available to end consumers, I think on purpose, and I suspect they would not be thrilled by me offering a competing product.

Solar sparklines

Look at all this free electricity! Time scale is 6 hours. These are 410W panels which in practice seem to max out about 320W AC, or 350W DC before the inverter takes its share. This is from Jan 13; maybe I’ll get more in summer.

Installing Oculus on a PC: “Not Enough Space”

The Oculus Windows app installer has a bug; you can’t install it on an NTFS dynamic partition. If you try it reports there’s not enough space, despite there being plenty. Dynamic partitions are extremely common on Windows machines.

The workaround I used was to run OculusSetup.exe /drive=D. I happened to have a D drive that was a basic partition and while there’s no GUI option for choosing the install drive, there is this command line switch. If you’re not so lucky, there’s a lot of advice online suggesting making a 20GB virtual disk and installing there.

This bug is six years old. I always wonder how bugs like this happen; do the developers just not give a shit? Sometimes I think it’s incompetence but Oculus is a very impressive piece of tech in general. The linked Reddit discussion suggests this is some ham-handed attempt to avoid installing to removable media, so maybe it’s deliberate. Maybe it’s a DRM thing? What a stupid decision if so.

Debugging a WiFi problem

Still tinkering with Raspberry Pis and my Sunpower PVS6 solar controller. I had it all set up with a new RPi Zero 2 W when I had a new problem; the WiFi was flaky. It kinda sorta mostly worked well enough, I could get the HTTP requests through to it usually. But ping was showing 40% or more packet loss with a latency of 200+ms. I have a very clean WiFi environment, that should be 0% loss and 2ms latency.

A whole lot of testing later and I established that the problem is some sort of interference on 2.4GHz Channel 1, but only in my garage near the Sunpower box. That corner also has all my other ethernet equipment, is where the generator and solar feeds come in, and where the utility power and electrical panel are. So a lot of wires. None of that stuff should interfere with 2401-2423Mhz and there are a lot of mysteries still.

Switching my access point to channel 3 (2411-2433Mhz) seems to solve the problem. Part of the root cause of my troubles is I’d pinned the WiFi channel in the garage to 1 a year or more ago, I forget why. I’ve now set it to auto. I’ve had experiences where it seemed to be working for a few hours at a time before, so I don’t fully trust it yet. Edit: after rebooting the AP went back from channel 3 to 1. So I’ve configured it to hardcode channel 3 instead of “auto”. Whatever the interference is, the Ubiquiti hardware isn’t detecting it.

The most useful thing I did in the end was get 2 access points and 3 clients and try moving them around every few hours to see what triggered the problem. I used telegraf to ping them once a minute or so (but see below) for long term monitoring, and then occasional command line pings once a second for short term testing. Over two days I was able to narrow the problem down to the one channel in the one location, but it’s not related specifically to any particular hardware.

Some things I learned:

  • wavemon is a helpful tool on Linux for showing WiFi status. so is /proc/net/status and learning all the arcane options to the iw command.
  • The UniFi dashboard has some decent stats of its own hidden away under “Air Stats” for each individual access point device.
  • WiFi has its own link layer retransmit; lots of those might account for higher latency. But I don’t know what timescale it is on: 1 ms? 500ms? You can see WiFi retransmits in wavemon as “failed” and in Air Stats as “retry”.
  • Despite all these diagnostics none of them really showed me evidence the link was bad. All the basic link quality reports were 90% or better. No ridiculous number of retries (although it is 16% at the access point.)
  • Linux machines, including RPis, need to be configured for the country for wifi to work at its best. Particularly important for 5GHz.
  • Even with a perfectly good 5GHz channel available an RPi4 might still choose 2.4GHz. I could not find a way to reliably coerce it to use 5GHz.
  • Raspberry Pis have a variety of low power optimizations that mean they may not respond well to a ping every minute when otherwise idle. My RPi4 regularly takes 100ms to answer the first ping, then is a solid 2ms after. My original RPi Rev B just misses pings entirely if nothing else is happening on it. The RPi Zero 2 W seems pretty solid but then I’ve got it doing other real computation. Anyway my once-a-minute ping was showing phantom errors where there were none. A once-a-second ping test worked better.
  • There’s a power saving mode in the RPi radio hardware itself you can turn off with iw.
  • Raspberry Pis may in general just not be very good at wifi.
  • Don’t use mDNS names for ping testing. The mDNS query itself may get lost to a flaky / low power Pi and you never find the host.
  • TCP retransmits hide a lot of sins. But it only works right until it doesn’t. When my WiFi link was bad about 5% of my requests wouldn’t get through at all.

WiFi on Linux: country registration (Raspberry Pi)

My Raspberry Pi 4 would not talk via 5GHz to my Ubiquiti Access Point. Turns out the problem is the AP was running on channel 157 (5785MHz, 80MHz wide) which is not a globally allowed WiFi channel. It is allowed in the United States. Ubuntu on RPi4 has no country configuration for the WiFi unless you set it explicitly. Setting it for US jurisdiction should fix it.

On Ubuntu the config file /etc/default/crda is where to set it. Note you have to set it to “US”; “us” does not work. On Raspberry PI OS it’s in raspi-config under Localisation options. It’s also configurable in the wpa_supplicant.conf file you create when setting up a headless RPi.

Once the system is running you can inspect the state of your current wifi config with the commands iw reg get and iw phy phy0 channels, see output below. There’s documentation on how this works here, here. The apt packages crda and wireless-regdb are also of interest, as is /lib/crda.

$ iw reg get
global
country 00: DFS-UNSET
        (2402 - 2472 @ 40), (N/A, 20), (N/A)
        (2457 - 2482 @ 20), (N/A, 20), (N/A), AUTO-BW, PASSIVE-SCAN
        (2474 - 2494 @ 20), (N/A, 20), (N/A), NO-OFDM, PASSIVE-SCAN
        (5170 - 5250 @ 80), (N/A, 20), (N/A), AUTO-BW, PASSIVE-SCAN
        (5250 - 5330 @ 80), (N/A, 20), (0 ms), DFS, AUTO-BW, PASSIVE-SCAN
        (5490 - 5730 @ 160), (N/A, 20), (0 ms), DFS, PASSIVE-SCAN
        (5735 - 5835 @ 80), (N/A, 20), (N/A), PASSIVE-SCAN
        (57240 - 63720 @ 2160), (N/A, 0), (N/A)

phy#0
country 99: DFS-UNSET
        (2402 - 2482 @ 40), (6, 20), (N/A)
        (2474 - 2494 @ 20), (6, 20), (N/A)
        (5140 - 5360 @ 160), (6, 20), (N/A)
        (5460 - 5860 @ 160), (6, 20), (N/A)

$ iw phy phy0 channels
Band 1:
        * 2412 MHz [1]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40+
        * 2417 MHz [2]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40+
        * 2422 MHz [3]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40+
        * 2427 MHz [4]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40+
        * 2432 MHz [5]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40- HT40+
        * 2437 MHz [6]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40- HT40+
        * 2442 MHz [7]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40- HT40+
        * 2447 MHz [8]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40- HT40+
        * 2452 MHz [9]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40- HT40+
        * 2457 MHz [10]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40-
        * 2462 MHz [11]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40-
        * 2467 MHz [12]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40-
        * 2472 MHz [13]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40-
        * 2484 MHz [14] (disabled)
Band 2:
        * 5170 MHz [34] (disabled)
        * 5180 MHz [36]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40+
        * 5190 MHz [38] (disabled)
        * 5200 MHz [40]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40-
        * 5210 MHz [42] (disabled)
        * 5220 MHz [44]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40+
        * 5230 MHz [46] (disabled)
        * 5240 MHz [48]
          Maximum TX power: 20.0 dBm
          Channel widths: 20MHz HT40-
        * 5260 MHz [52]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5280 MHz [56]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5300 MHz [60]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5320 MHz [64]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5500 MHz [100]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5520 MHz [104]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5540 MHz [108]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5560 MHz [112]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5580 MHz [116]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5600 MHz [120]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5620 MHz [124]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5640 MHz [128]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5660 MHz [132]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40+
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5680 MHz [136]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz HT40-
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5700 MHz [140]
          Maximum TX power: 20.0 dBm
          No IR
          Radar detection
          Channel widths: 20MHz
          DFS state: usable (for 726 sec)
          DFS CAC time: 0 ms
        * 5720 MHz [144] (disabled)
        * 5745 MHz [149] (disabled)
        * 5765 MHz [153] (disabled)
        * 5785 MHz [157] (disabled)
        * 5805 MHz [161] (disabled)
        * 5825 MHz [165] (disabled)

mDNS, hostname.local, and WSL2

Modern computers can often be reached by the DNS name hostname.local. This is implemented via Multicast DNS, mDNS, which originated in the early 2000s as part of the zeroconf work to make networked computers usable without manual configuration. Apple’s Bonjour was the first implementation of it I saw working widely. Linux machines tend to use Avahi. For Debain and Ubuntu systems apt install avahi-daemon is generally enough to get the system announcing its name.

The magic of multicast

It works via multicast. mDNS-aware name resolvers know that if a domain name ends in .local, the way to resolve it is to send a UDP multicast request to 224.0.0.251:5353 or and see if anyone answers. (There’s an IPv6 equivalent). Multicast generally propagates across your whole LAN; if a host sees a query for their own name it answers back to 224.0.0.251 (not the requester directly) with a DNS record. It’s not exactly standard DNS packets, some slight modifications in place, but the basics are the same.

It works great! As long as you have a reliable LAN. I’m using it on some Raspberry Pi devices with a flaky WiFi connection and that’s not a good experience.

As an aside, can I say how much I love multicast? Ethernet broadcast too, and even the less common anycast. Being able to send a packet to the local network without being exactly sure who the recipient is can be very useful in all sorts of applications. A lot of stuff we do like NTP would work better if it regularly used multicast. Unfortunately multicast over the routed public Internet is pretty much a dead-end technology; no one has ever figured out how to manage it scalably.

mDNS services

I mostly use mDNS myself for .local domain name resolution. But mDNS is a full service discovery framework. You can use it to ask for things like “is there a printer on the network?”

Avahi comes with a discovery tool to get a quick dump of services on the network.
avahi-browse --all --ignore-local --resolve --terminate
Here’s an example of the services my printer offers

+   eno1 IPv4 Samsung M267x 287x Series (SEC...)   _privet._tcp         local
+   eno1 IPv4 Samsung M267x 287x Series (SEC...)   _scanner._tcp        local
+   eno1 IPv4 Samsung M267x 287x Series (SEC...)   UNIX Printer         local
+   eno1 IPv4 Samsung M267x 287x Series (SEC...)   PDL Printer          local
+   eno1 IPv4 Samsung M267x 287x Series (SEC...)   Internet Printer     local
+   eno1 IPv4 Samsung M267x 287x Series (SEC...)   Web Site             local

On my LAN I have services for Sonos, Roku Airplay, the printer, my Samba fileshare, and some things Home Assistant has published.

I believe the service discovery is all implemented via mDNS queries, with some extra information placed in TXT records. It all looks fairly elaborate, RFC 6763 is one reference for how it works. Now I’m curious how carefully specified the metadata for things like printers are. Is there a clear standard or is it all freeform and customary publication?

WSL and mDNS

WSL2, Microsoft’s Linux VM for Windows, also supports .local domain names. It’s a little weird. My windows machine is named “Nelson-Win10”. On the rest of my network nelson-win10.local resolves to 192.168.3.114, the DHCP-assigned address for the host Windows system. Just like you’d expect. But inside a WSL2 shell it resolves to Nelson-Win10.mshome.net (172.27.48.1). That’s a private-use address and the domain name is something Microsoft has been doing for years as part of their Internet connection sharing stuff. This address is reachable from the host Windows system. It’s not accessible on the rest of my LAN because I don’t have routes for that subnet, I wonder if it would work if I added one? Anyway this is all a workaround for the fact that localhost doesn’t work very well (or at all) across the host Windows and WSL2). Honestly all the networking in WSL2 to the outside world is kind of confusing and maybe buggy. But hostname.local works on the Windows machine itself.

(Note that in a command shell on Windows itself, nelson-win10.local also works. It resolves to an IPv6 link local address in the fe80::/10 block.)