Some Bits: Nelson's log

51 posts in 2019

UPS battery lifetime

I use cheap UPS units for battery backup. Things like the CyberPower CP825LCD, basically power strips with a 12V battery and an inverter. They work OK.

For a few years. The lead acid batteries in them eventually wear out, and after 3-5 years they don’t hold a useful charge anymore. They lose capacity over time, too. Unfortunately these cheap UPS units don’t have a good way to monitor their battery health. You only notice when the power goes out and find you have 5 minutes of battery backup, not 15. Or else the unit just fails entirely and starts beeping confusingly or doesn’t provide power, even when plugged in.

Checking battery health

There is a way to easily check the battery life though, at least with CyberPower UPS units. Their PowerPanel software connects to the USB port on the UPS and gives you info on battery status. Including a self test which calculates battery capacity in the moment

Before I clicked the “self test” button it was saying Battery Capacity was 100%. But that was a guess based on the fact the battery was fully charged. Self test swaps over to battery power for a couple of seconds and then measures drain. This battery really only has 1/3 capacity which means it’s time to replace it.

You can also do a simpler version of this self test by just yanking the plug and seeing how long the UPS lasts. Works better if the UPS has some sort of display of battery life remaining. But I found that a little confusing; this software test works better.

Every UPS I’ve had also runs its own self test regardless of whether there’s any software talking to it or not. I’ve never seen this test report any useful information, though. Maybe when it fails that’s what sets the UPS off on the endless beeping until you change the battery? Dunno. I sure wish they’d invest a little more into communicating to the user this necessary maintenance.

One other neat thing about the software: they report wattage used as well. For some reason the CyberPower LCD units don’t show that on the LCD screen.

Another blessing of the software is it lets you turn off the beep alarm when the power goes out. I already know the power is out, I can tell because of how dark it is. I don’t need every UPS in the house beeping at me.

These UPS units offer software for Windows, Mac, and Linux. The last time I used the Linux software (from APC) it was scary bad code running as root so it could run shutdown. But it did reliably output numbers on battery activity that I could graph with munin.

Replacement batteries

The simple solution to a failing battery is to replace the battery. The CP600LCD I have that just failed is $70 new, or $35 for a battery from CyberPower. Not great. But fortunately lead acid batteries are standard and common; as long as it’s a lead acid battery with 7V, the same Ah capacity, and the same physical size, it’ll work. (Probably any capacity battery will work but if you want it to fit the case, you’ll want the same size.) I ordered an ExpertPower battery for $17.50, or just half of the CyberPower official price.

The one thing to look out for is that the connection terminals come in two sizes: F1 and F2. F2 is wider. My UPS has F2 connectors but the new battery has F1 spades, I’m hoping it’ll still fit well enough to just work. You can also buy very simple adapters, metal clips, but the Amazon price on something that cheap is ridiculous.

Don’t put your old battery in the garbage, they are hazardous waste. Instead dispose of them like you would a car battery. Most trash collection companies have a special pickup or dropoff option for them. Places like Auto Zone and Home Depot often take car batteries for recycling, too.

Better batteries

Battery tech has come a long way; why are we still using old lead acid batteries? Mostly because they’re cheap, and UPS units don’t need to be compact or light. There are other battery tech options though.

Our ordinary lead acid batteries are “VRLA”, sealed. There’s a different type of “flooded” lead acid battery that’s open. They work for more cycles, but they are constantly venting hydrogen and needing distilled water added to it. So not really practical for home use.

I’ve never seen a NiCd or NiMH consumer UPS. The articles I’ve read say they are just too expensive for the performance, although I’ll note that didn’t stop laptop manufacturers in the 90s / early 00s. There are some hacker projects you can find building cheap 5V UPS backups with NiMH AA cells for low power devices like Raspberry PIs. Sounds fun.

As for lithium, I think it’s just too expensive. APC does build one consumer lithium-ion UPS, the APC BG500. But at $270 for a 500VA backup it has a hard time competing with the $50ish 500VA from lead acid batteries. It’s smaller and the battery will last twice as many years, sure, but for 5x the price? There’s a range of high end rackmount lithium UPS units for datacenters where compactness matters, but now we’re talking thousands of dollars.

IoTaWatt energy monitoring

I’ve been playing with an IoTaWatt energy monitor. This is a bit of hacker-friendly kit that measures electricity usage on each circuit in your breaker box. It gives you real time wattage data with 5 second samples and makes it much, much easier to understand where power is going in your house.

There’s a lot of products on the market now that do this kind of thing. Many are full consumer turnkey products like Neurio or Sense. They have cloud based monitors and some fancy pattern recognition to tell you things like “your refrigerator is failing”. I opted for the more hacker-friendly one, both to keep the data private and to be able to play with it more myself. See also OpenEnergyMonitor. I tell you, what I really want is something like a Leviton Smart Load Center, where the panel and breakers do this kind of monitoring themselves. (Price seems to be ~$4000 for a house, compared to $1500 for traditional dumb breakers.)

This post is long because I’m in the middle of learning about this stuff. But after running it just for 24 hours I learned some things like I have a leak in my water system somewhere, that my office uses 80W even when everything is “turned off”, and just how much electricity videogames use when you’re playing them. Having precise numbers for all this stuff is great.

How it works

The key sensor technology is the Circuit Transformer, a ~$10 metal coil you clamp around the hot wire of a circuit you want to monitor. The magnetic field in the main circuit induces current in the CT, which you can then read out the other end as either variable voltage or amperage. The common split-core CTs are installed without disturbing the wires in the breaker box at all, and nothing is electrically connected. Even so it’s important to keep the CTs plugged in to the controller box; if they aren’t they can build up a dangerous charge.

The CTs are plugged in with 3.5mm jacks to a controller box. The IoTaWatt is an Arduinio-class system that basically takes 14 CT sensors as input, stores the data on an SD card, and has a web interface over WiFi. The custom software (not Unix) includes a decent graphing interfaces and enough APIs to load the data up to some other system like Emoncms or your own stuff. It seems pretty good.

Installation

A temporary installation isn’t as hard as I feared. You take the panel for your breaker box off, exposing all the wires. Then you clip the CT sensors of the appropriate sizes around the wires you want to monitor. Done! You don’t even have to turn the power off first although obviously you should to be safe.

Of course it’s not so easy. The tricky part in North America is we use split phase power. We get 240V from the power company but it’s split into two out of phase 120V legs. The CTs only monitor a single leg, so if you’re measuring a 240V circuit (like a well pump or a dryer) you need to use two CTs, or pass both hot wires through a single CT, or double up the measurements. Also it’s easy to install a CT backwards, so the values are all the wrong sign. Fortunately the IoTaWatt has many software tools to compensate.

The other problem is a permanent installation. All the CTs and wires take up a lot of room in the breaker box. And the IoTaWatt also has to go somewhere, and be plugged in to two wall transformers. If you have a big breaker box you could just leave it inside (if code allows), but I’m not sure how well WiFi works there. I haven’t figured out a good permanent install.

What I measured

I just went with a simple temporary install to get some basic measurements. I only measured for a subpanel in my house and wasn’t able to get some of the more interesting things like the refrigerator. What I did get:

  • My office: a simple 110V circuit. This is where I spend all my time and includes my PC, my PS4, and my TV. Also overhead lights.
  • Furnace fan: simple 110V circuit? Gas heat, so fan only.
  • Pool: full 240V circuit. I’m only monitoring half of it, so I have to double the numbers reported. This may not be entirely accurate if the load is not balanced. But my 385W pump load shows up as 200W on the graph, so doubling is roughly correct.
  • Well pump: a 240V only circuit. I should double the numbers reported.
  • Septic pressure dose pump: another 240V only circuit, should double.
  • Subpanel supply: a full 240V circuit, with two monitors installed. I believe it’s correct to sum the two numbers when measuring the load.

Data and Graphs

Here’s some data I collected after running the monitor for 24 hours.

Power usage for individual circuits (already doubled as needed):

  • My office: 4600 Wh
  • Furnace fan: 1200 Wh
  • Pool: 3200 Wh
  • Well: 1400 Wh
  • Septic: 700 Wh
  • Total measured: 11,000 Wh
  • Subpanel supply 1: 7400 Wh
  • Subpanel supply 2: 9300
  • Total subpanel: 16,700 Wh (or about $4/day)

Office and Pool

Office and Pool

Here’s a graph of power usage over the course of a day. The yellow line is my office, the blue line is the pool.

The pool is easy to understand. Note the graph is at half scale, I forgot to click “double” in the setup. The filter pump turns on around 2am, has a brief priming jolt, then runs steadily at ~400W until 6am. There’s a 30 minute window of very high usage, 1800W, that’s when the second pump turns on to run the sweeper. There’s also an occasional usage of power during the day, well below 100W. That’s a little pool cover pump I have that runs when there’s enough water. It was raining this day. The pool uses 3200Wh a day or $8.

My office is harder to understand. At night it’s a steady 80W; that’s with most everything turned off or in sleep mode, but I still have a bunch of network equipment and vampire loads from TV gear. The load in the morning of about 200W is when I turn on my computer and do low power stuff like reading web pages. It spikes up to 400W when I’m playing a game on my PC. The 350W load is when my PC is relatively idle but I’m playing a game on my PS4. The TV seems to also spike the whole circuit load up to 200W. There’s also some overhead lights in the mix. Putting this all together, I can estimate these loads:

  • Constant load 24/7: 80W
  • Idle PC use in morning: +120W
  • PC gaming: +300W
  • PS4 gaming: +250W
  • Watching TV: +100W
  • Full day: 4600Wh, or ~200W average.

Furnace, Well, Septic

Furnace, well, septic

The furnace fan (in red) uses 120W when it’s on. It doesn’t run at night. It averaged about 50W this day.

The septic pump runs a few times a day; this value should be doubled. It’s sorta correlated to water usage but not really, it’s not as simple as “every time I flush the toilet”. It’s a high load when it runs, 2000W, but only briefly. Average daily usage is 30W.

The water pattern is more troubling. (Again, values in graph should be doubled). My well pump is coming on every 30 minutes and it’s basically uncorrelated to water usage in the house. That to me says I have a leak somewhere. I turned off the outside water while monitoring this and the frequency went from ~25 minutes to ~33 minutes, so while there may also be a smaller leak outside the big loss is coming from the indoor plumbing. I’m pretty sure I don’t have any leaky faucets or running toilets. Maybe it’s the well itself and the water system’s pressure tank. Apparently a common failure mode is that the check valve leaks pressurized water back up into the well, so it has to refill itself every once in awhile. The power usage isn’t so bad (60W average, or $15 a month) but I don’t want to waste water. And it’d be better not to have the wear and tear on the pump.

Subpanel Inputs

This is the graph of the power going into the panel. Both legs of the 240V circuit, I believe it’s correct to sum these. Not sure why they aren’t balanced more? The yellow line seems to go higher when I’ve got lights turned on and the office is busy, so maybe it’s uneven 110V loads. Not sure it really matters anyway. Note that the 5 circuits I’m monitoring in detail only add up to 11,000 Wh of the 16,700 Wh the panel supplied this day. I’ve got a bunch of other circuits I’m not monitoring, I guess they add up to about 1/3 the usage.

Conclusion

I like this IoTaWatt! Even with a temporary install I think I could learn enough in a few days to model out all the power usage of my house. Idle load, average load, and max load for every circuit in the house. That will be hugely helpful when designing a power backup for PG&E’s stupid outages, whether a generator or a battery.

What I really want is to have this kind of monitoring all the time, storing history in the background. Would love to see how my usage patterns vary over time, or spot new water leaks, or realize when the refrigerator is failing. I think the IoTaWatt is sufficient to do that, at least if you can find a nice way to install it permanently.

I do think an integrated system like the Leviton Load Center makes more sense though. I wonder if their system is in any way open? I fear the answer is no. No hint it works with any of the open source software, and Leviton doesn’t even have it working with Alexa yet. I bet there’s a way to scrape data out of the web app.

Bonus

Another graph, this of the next 24 hours. All the doubling, etc is done correctly.

Backup cell ISP notes

My Internet in Grass Valley is flaky enough that I’m looking at getting a permanent mobile service as a whole-house backup. Right now I just use my phone as a hotspot and switch my computer to it when necessary. That works OK but it only gets my own computer, I’m curious about switching the whole house. (Also dreading it; what if one of the devices decides to download a 10 GB update while on mobile?)

Ethernet / router options

The Ubiquiti EdgeMAX EdgeOS router I uses supports having a second WLAN connection as either load balancing or pure failover. Obviously I’d want failover. The trick is that you need to plug the mobile device into an ethernet port on the router. So the usual wireless hotspot doesn’t work.

The one device that looks exactly right is the Netgear 4G LTE Modem. $110 for a SIM card in, ethernet out. Perfect! See review here. Except it explicitly says it does not support Verizon, my carrier of choice. Some of the user comments suggest it does work on Verizon but my guess is only the LTE works and if you have to fall back to 3G it can’t do CDMA. Not ideal. I could use it with AT&T. Also it does not support LTE Advanced.

This review site’s roundup of ethernet-out devices is discouraging. Only Netgear makes the simple ethernet-out product. There’s a couple of things that are also wireless hotspots or routers that have an ethernet port, maybe they could be adopted. Or something really expensive like this new 5G hotspot. One final option would be to get a USB device and use a Raspberry Pi to output ethernet, assuming it’s possible.

Another option that looks slick is the Ubiquiti Redundant WAN over LTE. $200 for some solid-looking LTE hardware that plugs into your ethernet. Also has a setup with AT&T for service already, $15/mo plus $10/GB. The only point of confusion for me is how the failover happens. The device says it’s for UniFi networks, so I imagine it does some Ubiquiti-proprietary coordination with the router (UniFi Security Gateway) to act as a failover. If so then it probably won’t work with my old EdgeOS device.

Back to hotspots

So maybe using a hotspot is the right idea and I should just get a dedicated hotspot device and service. It’s manual failover and won’t cover my whole house, but there’s lots of product choices. The Inseego MiFi 8800L Jetpack (aka Verizon Jetpack) looks terrific. It even supports LTE Advanced! It doesn’t support Verizon 3G which is weird for a product Verizon is explicitly selling. Maybe that’s OK though, 3G is on the way out in the US.

OTOH just using my phone works well enough for the few times I need to do this. Never been sure I really needed a dedicated device. I’m using a Pixel 3 and it supports LTE Advanced.

Mobile data providers

If I get a dedicated device I need a data contract and SIM for it.

I can add a second line to my Verizon account. $10/mo and then $10/GB. I’m unclear but I think this will share my phone’s data balance? I always have way more data than I need, so that seems like a good choice.

I took a quick look at AT&T prepaid MVNOs, as something I could use with that Netgear modem. The best I could find in the US was Red Pocket Mobile. $10/mo for 1GB, and then $10/GB for topups. Or $25/mo for 5GB if you know you’re going to use it a lot. I did not look at getting a proper monthly account with AT&T, or adding a line to existing AT&T service. I suspect the pricing is the same as Verizon.

Conclusion

Three options

  1. Stick with using phone as my backup. A hassle, and manual, but it’s paid for already.
  2. Get a Jetpack mobile hotspot and switch to it manually. More convenient, but still a hassle. Small extra monthly fee.
  3. Get the Netgear LTE Modem and an AT&T MVNO. Give me proper failover, although there’s the risk we then blow through the data thanks to some ignorant device. Have to buy a new contract, so can’t use existing data on the Verizon account.

Option 1 sure is the least demanding up-front.

Some rough watt-hour numbers

PG&E’s incompetence means I’m thinking about electricity storage recently. Some rough numbers:

Devices you charge and use:

Batteries you can charge things from:

There’s a huge variety in the stuff I lumped together as “charger”, particularly how well they furnish AC or DC for usage. Your car battery is only as good as the inverter you plug into the stupid cigarette lighter, for instance. That EGO Power Station is designed to be a full portable AC power solution that can put out 3000W of clean power (well, for 20 minutes). Briefcase solar systems can also recharge themselves from solar panels.

I currently own a Powercore and two spare UPS units, for a total of about 275Wh. With that I can charge my laptop 4 times, my iPad 8 times, or my phone 25 times. I also have the car which is good for about 3x more charging just off the battery, which doesn’t count idling the engine to keep its battery charged.

Update learned a couple of things in the latest outage. The car inverter works pretty well, but my 2017 A3 only puts power out the 12V sockets if the engine is running. You can leave it running unattended if you start the engine with the door open. The car manual says 120W maximum out the socket, so my 300W inverter purchase is overkill and I guess I could blow a fuse. Other thing I noticed is the inverter was no good for trying to charge a CyberPower 875AV UPS; the display on the UPS showed it was picking up a little charge but not really. The cheap TrippLite UPS I have did seem to charge better from the inverter, or at least the inverter got awfully warm.

My electric bill says my house averaged using 35,000 Wh a day for the last year. A lot of that is optional load; in a low power situation I wouldn’t be running the pool pump, the electric oven, etc.

A single rooftop solar panel generates roughly 300W maximum, or 1370 Wh per day (average over the course of a year in NorCal).

Archiving and deleting 23andMe

I decided to delete my 23andMe profile. All told it took about a week and I have a copy of everything I care about. Could have gone faster but I was careful and slow about it.

I did the test in 2011 with mixed feelings; genetic data is so super private and yet also so readily available to a determined attacker. I was curious what the reports would say. And I kind of wanted to support the company, I believed their research mission.

The consumer product never quite excited me. Other than one very significant thing (story forthcoming) it’s told me nothing useful. A lot of the stuff they highlight is dubious. I don’t see any reason to continue to pay for access to it.

And then there’s the law enforcement fuckery. Police keep getting more and more aggressive about accessing genetic databases. It’s not clear the courts will protect people. Time to delete the data.

Note that deletion isn’t really deletion. 23AndMe seems to make a good faith effort to remove data and destroy samples. But they may have shared some data and it’s no longer entirely under their control. Also your entire genetic data is stored “to meet CLIA requirements”, apparently some regulatory requirement where the government wants labs to keep data so they can evaluate lab quality. In theory all that stuff should be anonymized but I wouldn’t trust that against a determined attacker. If I’d known all this back at the beginning I never would have done the test.

So, what to do when deleting your 23AndMe account? Here’s what I did. Note I have very old data in their system, from a genetic test in 2011.

  1. Contact any connections you have and let them know you’re deleting your data. If you shared something with a family member it might be nice to give them a couple of days to take one last look at your data.
  2. Download all user data. This page is accessible from Settings, at the bottom under Data. It has buttons for downloading various sections. The reports data wants to print; I printed that to a PDF file.
  3. Be sure to download raw genetic data. It doesn’t download immediately; it creates a request and you get an email when it’s ready. (Mine took just a few minutes and was 24MB). This is the most important data on the site, the raw genetic test output. It’s all your SNPs. It’s possible to analyze this data with lots of tools, both online and offline.
  4. Download your archived reports. This only applies to pre-2016 accounts, before the FDA settlement, and only contains old science reports.
  5. Browse your current reports. One last trip down memory lane. It turns out I do not have the Neanderthal trait that makes people sneeze after eating dark chocolate. Thanks, 23AndMe, that’s definitely worth risking my genetic privacy to know!
  6. Consider downloading / printing any detailed reports you are interested in. They seldom contain any more personal data than is in the summary report but the surrounding context may be useful.
  7. Consider downloading Profile Data. This is a record of inputs you’ve given the site, like address changes and your self-reported phenotype. You have to request a download; it took two days for me. Mine was a few uninteresting tiny CSV files so I’m not sure it was worth the bother.
  8. Request account closure. That’s the final step, the deletion. The big red button is at the bottom of this page. They send you an email to confirm with some caveats.

Once I submitted the final deletion my account looked inaccessible the moment I tried to log in. Well I could log in, but it looked like an empty profile. The site didn’t promise any final notification when the deletion is completed, no idea whether I’ve simply been marked as status: deleted or they actually scrubbed my data. Presumably destroying biological samples takes some time.

As noted above, various copies of your genetic data will be kept for years and there’s nothing you can do to delete it. I believe these are all anonymized and won’t be easy to associate with your name, but that still seems pretty crappy to me.

I will give 23AndMe credit, nowhere in this process was there some retention process slowing me down. They never even asked why I was deleting! I appreciated that; it’s much harder to, say, cancel cable TV.

23AndMe’s deletion details

This is the disclosure in the email from 23AndMe about what deletion means. Note the third bullet item about “will retain your Genetic Information”; despite my request they are not actually deleting my data.

We received your request to permanently delete your 23andMe account and associated data. The following apply when you submit your deletion request:

  • If you chose to consent to 23andMe Research by agreeing to an applicable 23andMe Research consent document, any research involving your data that has already been performed or published prior to our receipt of your request will not be reversed, undone, or withdrawn.
  • Any samples for which you gave consent to be stored (biobanked) will be discarded.
  • 23andMe and the contracted genotyping laboratory will retain your Genetic Information, Date of Birth, and sex as required for compliance with legal obligations, pursuant to the federal Clinical Laboratory Improvement Amendments of 1988 and California laboratory regulations.
  • 23andMe will retain limited information related to your data deletion request, such as your email address and Account Deletion Request Identifier, as necessary to fulfill your request and for the establishment, exercise or defense of legal claims.

Once you confirm your request to delete all of your data, 23andMe will begin processing your request. This decision cannot be cancelled, undone, withdrawn, or reversed.

Better NVidia driver updates

NVidia makes excellent graphics cards with decent drivers.

They also make shitty marketing-ware bloated with crap you don’t want. I’m referring to GeForce Experience, the wrapper around the drivers that runs on Windows. It claims its primary job is updating your drivers. But somehow it needs 100s of megabytes to do that, has a bunch of stupid features in it you don’t want, and requires a login to an NVidia website account to work. Worse, the login requires a CAPTCHA. Right there on my Windows desktop. Stupidest damn thing. Of course the real reason for all this is building ad profiles and marketing and blah blah blah. See also: “NvTelemetry”.

One option for GeForce Experience is simply not to use it. You can still manually download drivers online and install them by hand. For now. But that’s a hassle.

A better option is TinyNvidiaUpdateChecker, a very minimal app for updates. It looks at your machine for the installed version of the drivers, looks online for newer versions, and will install an update for you. It runs super fast, requires no login, and just does its job without getting in the way.

The one drawback is it really is minimal. The default setup is to run once and display its UI in a console window (lol). There’s a guide for making it run at system startup instead, which boils down to “make a shortcut with the --quiet argument and make it run at startup”. It’d be nice if it had an installer and an optional system tray mode.

There’s also an advanced feature called the minimal installer. That breaks apart the NVidia update and only installs some pieces. The goal is to avoid GeForce Experience and NvTelemetry, which are laudable. But the docs makes it sound like you might also not get PhysX, HD Audio, etc. That doesn’t sound great to me, but maybe I misunderstand.

Updating nameservers in Ubuntu 19, Pi Hole edition

For some reason, every time I reboot my Ubuntu 19 box had /etc/resolv.conf configured to point the name server at 127.0.0.1. There’s no nameserver running there, so it fails. I want it set to 192.168.0.1. Where is this coming from? Is it related to having had Pi Hole installed at one time? systemd? What?

tl;dr: there’s like 5 things in an Ubuntu 19 system that might be modifying your name server, and tracking it down is really terrible.

In the old days you edited /etc/resolv.conf and were done. (libc knows to read this file and use it when resolving names. Crazy, huh?) That works transiently but is undone if you reboot. If you look at the file there’s a dire notice

# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.1

OK, so systemd is a DNS resolver too now? Awesome. Don’t let the 127.0.0.53 surprise you; that’s basically another name for 127.0.0.1, localhost. Only they’re being sorta clever. But my system is broken; it’s not set to .53, it’s set to .1.

Then you go down the rabbit hole. That command systemd-resolve --status is giving you systemd’s idea of how to resolv names. That in turn seems to be configured by files in /etc/netplan, something you may have created if you configured static networking. Changing those will (presumably) alter the behavior of systemd’s DNS server.

But my problem is my /etc/resolv.conf was being regenerated at boot time to point to 127.0.0.1, not 127.0.0.53. systemd’s resolver is never involved. How to fix that? Second rabbit hole; there’s a system called resolvconf that might be overwriting it with information in /etc/resolvconf. Only what’s on my system isn’t the real (old) resolvconf, it’s actually systemd’s resolvectl running in a resolvconf-compatibility mode. I fiddled with it for awhile and I still don’t understand how this stuff works, but it seems to not be writing this entry.

I finally did a grep and found even though I’d uninstalled Pi Hole, it left behind a /etc/init.d/pihole-FTL script. Which is running resolvconf at boot time to re-set the nameserver to 127.0.0.1. This script shouldn’t still be on my system, and removing it should stop the clobbering. So I removed and rebooted.

Hah, joke’s on me! Every reboot, the 127.0.0.1 entry gets rewritten. Where is it coming from? I found it in /run/resolvconf/interface/enp3s0.dhcp. I’m not using DHCP, I have a static IP address. But that encouraged me to pay attention to /etc/dhcpcd.conf which, yes, is the actual source of the text overriding resolv.conf. I changed it from “static domain_name_servers=127.0.0.1” to 192.168.0.1 and name service works on reboot! Who knows why this matters.. dhcpcd is still running; it appears to be used to configure interfaces with static addresses even if DHCP isn’t involved.

But systemd still has one joke left on me. Now when I cat /etc/resolv.conf there are two name servers.

nameserver 192.168.0.1
nameserver 127.0.0.53

I have no idea why systemd decided to inject its .53 in there. It didn’t when the DHCP wrote 127.0.0.1 in there, but change that number to 192.168.0.1 and now systemd’s all in a hurry to put itself there. It may be coming from files I’m afraid to edit in /run. Anyway now half the queries go directly to my name server, half are looped through systemd first.

Fortunately the systemd loop seems to be working. I can’t dig @127.0.0.53 but no ordinary query ever hangs in a way consistent with a broken nameserver. systemd-resolve --status suggests that resolver is configured usefully (forwarding all requests to 192.168.0.1). So I’m just gonna leave it alone since it’s working, even if it’s not what I want.

The problem with systemd isn’t just that it’s a giant beast that tries to do everything. It’s that it’s also magic and poorly documented.

Update (DHCP edition)

I went through this ordeal again on another Ubuntu 18.10 box that I’d installed PiHole on. It took me forever to figure out where the bogus entry in /etc/resolv.conf was coming from. I finally found it in /etc/dhcpcd.conf

Ubuntu’s network configuration is a serious dog’s breakfast of competing files overwriting each other. AFAICT, any of these subsystems might be responsible for configuring /etc/resolv.conf:

I have not found this documented clearly anywhere. The way things overwrite config files quietly is really awful.

Linux watchdogs in 2019

My home server is dying unexplainedly. Totally locks solid, nothing in the logs, very confusing. While I figure out what’s wrong (power supply?) I decided to go implement a watchdog to reboot the system if it fails.

This turns out to be hard in 2019, with Ubuntu 19. tl;dr there are two choices: systemd or the good ol watchdog daemon. See also: softdog.

systemd has watchdog support. Unlike many things in the systemd hydra, this one makes sense to me to integrate. It’s configured in /etc/systemd/system.conf. However it’s not well documented and relatively limited, so I decided not to use it. Even so my system has a PID 77 named [watchdogd] that I think is part of systemd. No idea what it’s doing, if anything.

watchdog is the old school Linux daemon that does watchdoggy things. Ubuntu 19 offers version 5.15-2, and if you install it by default it doesn’t do much. You have to configure it via /etc/watchdog.conf, ensure it loads at startup, and (maybe) install a kernel module to help it.

watchdog works by running a bunch of different tests. It’ll try pinging a network address, check if a file has been modified, see if the load average is too high or if there’s no RAM available. If not it’ll reboot the system. The shutdown is internal, it doesn’t fork any processes.

By default the Ubuntu watchdog.conf has no tests enabled. I think this means it does nothing at all. (It’s possible there’s some “if the system is totally dead then reboot” thing still hiding in there, but if so I don’t see it.) To be useful you want to configure various tests. I have it pinging my router; in theory my computer is still working even if the router is down, but in practice it seems more likely my server’s networking has died. (There’s a systemd upgrade bug.). I’m sure this will end up shooting me in the foot some day.

This is what a watchdog shutdown looks like in the syslog

Oct 13 18:57:31 ub watchdog[30919]: no response from ping (target: 192.168.3.1)
Oct 13 18:58:33 ub watchdog[30919]: message repeated 31 times: [ no response from ping (target: 192.168.3.1)]
Oct 13 18:58:33 ub watchdog[30919]: Retry timed-out at 62 seconds for 192.168.3.1
Oct 13 18:58:33 ub watchdog[30919]: shutting down the system because of error 101 = 'Network is unreachable'

BTW, this is the point to note that in theory if you screw up a watchdog config bad enough, the system might reboot itself so fast you can never get in and fix it without rebooting single-user mode at a console. Fortunately the default config is to reboot after 1-2 minutes of failure, giving you time to get in and fix anything dumb or disable watchdog entirely.

What happens if the machine is so locked up that the user space watchdog process can’t run at all? What will trigger a reboot then? Enter kernel support for watchdogs, a feature that goes back to 2002. The basic idea is if some process ever writes to a file named /dev/watchdog, if that file is not written to once a minute the kernel will reboot itself. The kernel’s own watch on itself is implemented at a low level with some sort of CPU timer. Serious systems have extra hardware for this kind of self monitoring, but this method should work reasonably well on a consumer PC unless the kernel itself or the whole CPU locks up.

However if you look on Ubuntu you don’t have a /dev/watchdog file. You have to install it. The simple way is to “modprobe softdog”. Getting this to happen at boot time is remarkably difficult because the module is blacklisted and systemd refuses to load it. The best workaround is to modify /etc/default/watchdog to load “softdog” as a module, fortunately they thought ahead on the need for this. Once you can do that you can enable the test in watchdog.conf.

Putting it all together, here’s how to enable a watchdog in an Ubuntu 19 system

  • apt install watchdog
  • edit /etc/default/watchdog to load the “softdog” module
  • edit /etc/watchdog.conf to enable the tests you want. I enabled ping and watchdog-device.
  • run “systemctl start watchdog” to enable it (or reboot)
  • check the syslog to see that watchdog is logging your active tests and looks reasonable

Update

Sadly the softdog isn’t enough to fix my problem; apparently the computer freezes so solid that the little bit of software needed to reboot doesn’t run. Maybe the CPU locks up entirely, I have no idea.

One escalation would be a USB hardware watchdog like this or this. Looks like it doesn’t require software at all; it plugs right into the hardware reset switch on the motherboard. Presumably it uses USB to power itself and monitor if the computer is working. These are sold for Bitcoin mining rigs, that’s hilarious.

I wish I could find out what was causing the computer to freeze up and replace it. Could be the power supply or motherboard or CPU or RAM.

Update 2

Turns out PCs and Linux do have a proper hardware watchdog, called the TCO Watchdog. There’s some info about it here. The key thing is the iTCO-wdt kernel module and the wdctl userspace tool. Also more info about systemd’s support here, which includes some useful details on the TCO thing.

I worked around my problem with an external hardware watchdog.

Epic Launcher: running copied games

The Epic Launcher on Windows stores its games in C:\Program Files\Epic Games. However if you copy a game from one computer to another, the Epic Launcher on the new computer won’t recognize it or let you play it. Super annoying if you want to avoid re-downloading 60GB of stuff you already have a copy of. (Steam does not have this nuisance.)

The workaround for this is to first start installing the game on the new computer using the Epic Launcher. Let it download for a few seconds, then abort the install (don’t just pause it) from the launcher. Then go in to the folder and delete the game directory on the new computer. And then copy the files from the old computer to the new. Finally in the Epic Launcher click “Resume” and it will verify the files rather than re-download and let you play the game.

This solution is described in How to Move Fortnite to Another Folder, Drive, or PC. The problem is also discussed in EpicGamesLauncher - Recognising already installed files which includes some hints about a C:\ProgramData directory that may contain the hidden state that’s missing if you just copy the program files. I didn’t pursue that avenue for making things work but it’s a good idea.

Upgrading systemd kills Ubuntu networking

Two or three times this year I’ve had a bug in a relatively fresh Ubuntu install where upgrading systemd kills the networking. I’ve got no idea what’s wrong and no physical console on the machine to inspect it. It feels like something simple like the upgrade script shut down networking but then didn’t bring it back again, but of course it could be anything.

So far this is happening only on my 18.10/19.04 box in San Francisco. Fortunately I have physical access so at least I can reboot it (usually). I haven’t seen it happen on my 18.04 box in a datacenter.

Ubuntu has a couple of recent bugs about this. Bug 1803391 boils down to a one time bug in an upgrade script in systemd. Bug 1782709 is open and confirmed with many reports and no clear idea what might be wrong. It looks like the kind of bug report that stays open for 4 years until someone closes it as irrelevant :-(

I do not want to learn so much about the guts of systemd and dpkg to diagnose this. systemd is particularly gnarly to debug since it does so much. Among other things it’s also capturing system logs, so there’s a risk whatever is being logged about the error is disappearing during the upgrade. Or not, who knows?

Again, I’ve made my peace with systemd, but this bug is a great example of the danger of centralizing so many functions into one component.

Edit I’ve placed a hold on systemd upgrades for now. Never upgrading systemd is not a solution, but this will serve as a reminder for me to only do the upgrade if I’m able to access the physical machine.

systemd and PolicyKit1

I’ve mostly made my peace with systemd but its usability sure leaves a lot to be desired. My fun interaction for today, trying to start a small service:

$ systemctl start hover-dns-updater.service
Failed to start hover-dns-updater.service: The name org.freedesktop.PolicyKit1 was not provided by any .service files
See system logs and 'systemctl status hover-dns-updater.service' for details.

A surprising error, particularly since I’m not even using any sort of desktop Linux. And no, the suggested systemctl status command doesn’t show any information at all about why the service failed to start, the log is empty.

The simple fix was to re-run systemctl as root, with sudo. Everything worked! That’s probably what one should do in reality anyway. I’m not up to date on Ubuntu’s current status of least privileges and user accounts, but in general “starting system services requires root” doesn’t surprise me.

However, there is another way. Install the policykit-1 package with apt. That will allow that systemctl command to work without being root. It requires you type your user password to authenticate yourself (again), so it’s not clear where it’s really useful.

I’ve never heard of policykit. This is what the README says:

polkit is a toolkit for defining and handling authorizations. It is used for allowing unprivileged processes to speak to privileged processes.

802.11 bad signal diagnostics (Ubiquiti)

Ken’s computer was having a bad time connecting to our wifi network via 802.11n. I finally figured out it was mostly a problem with signal strength in his room, a second computer displayed the same symptoms with that same 802.11n adapter. We solved the problem by upgrading him to a 802.11ac adapter. Along the way I learned some things about WiFi signal reliability. Usual caveats applied: I’m just learning this stuff myself and am an amateur

802.11 link layer reliability

WiFi’s link layer has its own set of complex reliability stuff built in, sort of analogous to TCP but solving a different problem. That makes WiFi quite different from ethernet, which AFAIK doesn’t have any link layer stuff for handling a lost packet other than the basic collision detection logic (nearly irrelevant in modern switched networks). There’s also some rate negotiation in modern ethernet; if 1000Base-T isn’t working reliably it’ll step down to 100Base-T. But that’s about it. I think ethernet makes the assumption its link layer is basically reliable and figures it’s the upper layers’ problem (ie TCP) to deal with lost packets.

WiFi is an inherently flaky medium though. It’s expected that not all packets will get through the radio æther unmolested by gremlins. So the 802.11 link layer has a couple of mechanisms built into it for reliability.

One tool is forward error correction. The codewords broadcast on 802.11 aren’t just the bits; they’re error correcting codes capable of fixing single bit errors at varying rates. I believe in practice wifi sends anywhere from 2 bits for every 1 bit of user data to 6 bits for every 5.

A second tool is link layer retries, something a little like TCP’s retry and ACK protocol. This is called “ARQ (Automatic Repeat Request)” in what I’ve read, and basically amounts to tracking sequence numbers and resending packets when not acknowledged. I don’t know how many retries are attempted or whether retries stall the link, this article has details that suggest it’s 4 or 7 retries. But note all this retry is happening on one local wireless link, in under a millisecond. Very different from TCP’s waiting a full round trip for a retransmit.

A final important tool is speed negotiation. Much like TCP uses lost packets and ACK clocking to figure out the maximum speed, WiFi gear monitors error rates and if it sees too many, steps down to a less aggressive data rate. There’s a bunch of choices here summed up by “MCS index”; you might up the error coding from 3 in 4 to 1 in 2, or use 16-QAM instead of 64-QAM, or whatever. I don’t know much about how this works in WiFi but I imagine it’s quite subtle and different from TCP’s algorithms. This paper (I haven’t read) has a description of some of them in practice.

I enjoyed reading this paper about 802.11 reliability. A couple of tidbits I picked up.. Up to half the theoretical bandwidth on an 802.11 connection is consumed by reliability mechanisms, particularly ACKs. Also there’s a paradox that faster links seem to be more reliable. There’s a lot of potential reasons for that, from the tautology that the link is faster because it is more reliable to odd things like faster data transmits mean less time spent flying through the æther and exposed to gremlins.

So that’s the theory. WiFi is designed with a lot of tools to deal with inherently unreliable radio communication. Error correction, retries, rate negotiation, it’s doing a lot.

802.11 diagnostic tools

Despite all that magic Ken was seeing speeds of like 500 kbps on his wireless link, truly awful. The most useful tool I found for measuring this on Ken’s client was simply DSL Reports speed test. That’s testing throughput all the way to an Internet site so is not really a very good test of a local wifi link. But I verified once or twice he was seeing the same slow speed internally, and he was getting a link much slower than our Internet connection. The nice thing about the consumer speed test tool is it shows you momentary bandwidth so you can get a feel for jitter, packet loss, etc. There are many better specialist tools for testing link throughput on your local WLAN; I took the one easiest to put my hands on.

On the server side, I have a fancy UniFi network with a complex bunch of network control software I never use. Turns out it has useful reports though! See Identifying Wi-Fi Issues with Debugging Metrics.

Well that’s your problem right there. According to my UniFi access point, Ken’s computer is receiving at a rate of 1 Mbps. That’d explain the 528 Kbps throughput. Yuck! I never could figure out why it was that low though. Or why it never seemed to increase again, the adapter went to lowest common denominator and got stuck there.

Another useful set of graphs buried in UniFi’s tool are time series charts of the AP’s performance. Graphs like this:

Note that’s a graph from when things are mostly going OK, I don’t have a picture of the problem. But at the time it was not working well the 2Ghz band was showing 80% channel utilization; all for Ken’s crappy 1 Mbps stream. And also lots of dropped and retried packets. Bad news.

I did very the same 802.11n adapter on a second computer also sucked in the same room; so it seemed to be the adapter, not the computer. But 802.11ac was fine. So the solution was simple, spend $25 on a decent wifi adapter and be done with it.

802.11ac, 802.11ax, and friends

A few years back I wrote up a blog post about 802.11n. The learning that went into that served me well. 802.11n is a fairly complex technology and also a very good one; the improvement over 802.11g was enormous. Well now it’s been a few years and 802.11n is old news, 802.11ac is standard and 802.11ax is the new hotness. What are they? (Same caveats as always apply; this is a gentleman amateur’s understanding, mostly based on reading Wikipedia articles.)

One observation; everyone talks about max throughput as the big performance number. But what people really hate about WiFi is when it’s unreliable. I’d much rather have a reliable 100 Mbps connection than a flaky 1 Gbps connection. Related are the number of retransmits that the wireless medium has to do and how that percolates up to dropped packets and unreasonable jitter at the IP level. Right now wireless connections are way, way worse for latency-sensitive applications like videoconferencing or gaming. Fixing that is not the focus of the stuff I’ve read about wifi improvements, but it may still be a happy side effect.

802.11ac

802.11ac is the evolution of 802.11n, a roughly 2013 technology. Sometimes it’s marketed as “WiFi 5”, and also it comes in two major flavors; Wave 1 and Wave 2. To a first approximation 802.11ac is technically just like 802.11n but simply faster. More bits per codeword, wider bandwidth channels, etc. These add up to faster networks with more robust fallbacks, but no major new concepts.

The big change in practice is a lot of 802.11ac connections run at 5GHz (2.4GHz is also supported). 802.11n in theory can run at 5GHz but a lot of the systems only supported it at 2.4GHz. The higher frequency means the signals don’t work as well indoors, but also mean more bandwidth. Even better the 5GHz band has a very generous allotment of channels and a bunch of smart stuff so that it can avoid interference with neighbors, so it works better in dense urban areas.

Nominally an 802.11ac channel is 20MHz wide, but 802.11ac can use up to 160MHz effectively combining 8 channels for 8x the bandwidth. (802.11n was limited to 40MHz). The other big improvements are more MIMO streams (8 vs 4 in 802.11n) and up to 256 symbols per codeword (vs 64 at 802.11n). All those combine for yet higher effective thoughput. In reality most equipment doesn’t support the very highest throughput modes. That’s where the Wave 1 and Wave 2 marketing language comes in; Wave 1 tops out at 1.3 Gbps, Wave 2 at 2.34 Gbps. In reality you’re going to get more like 200-800 Mbps if you’re doing well.

Which brings us to more marketing language. WiFi adapters are sold with language like “AC 1300”. That doesn’t mean 1300 MBps. That means it’ll run up to 400 Mbps at 2.4GHz and 867 Mbps at 5.0 GHz. Even though you only get one or the other, the marketing people add the two numbers to come up with the product description. They also apparently round up, so 400+867=1300. Dumb, but at least it’s clear enough what it means. Your AC 1300 device will never go faster than 867 Mbps. And bigger numbers are better.

Most of 802.11ac’s changes over 802.11n are “go faster”, but there’s a few new concepts too. One is Multi-User MIMO, which somehow lets a router support more bandwidth for a cloud of devices than the maximum throughput just for one device. I think this is spatially based, so that bandwidth to, say, the north of the device is independent to bandwidth to the south.

The other change is beamforming. This lets the equipment do something like a directional antenna, directing signal in the direction it’s trying to communicate. Only you don’t have to move the antenna, instead the electrical elves inside the antenna form the beam by holding up little mirrors. (I may have some of the details wrong but I’m sure my explanation is more comprehensible than the correct one.) I have no idea how well it works in practice.

So that’s 802.11ac. “Faster 802.11n that prefers 5GHz” is a reasonable summary. At this point any new hardware you buy should support 802.11ac. And it may be worth upgrading any old 802.11n gear you have; switching to 5GHz is a nice thing.

802.11ax

802.11ax is the 2019 hotness, also branded WiFi 6. I don’t really know much about it, but to a first approximation it’s yet another improvement beyond 802.11ac. A lot of the changes seem to be about avoiding congestion in denser areas. Smarter dynamic power management, better MIMO options, and the ability to use a wider range of frequencies between 1 and 7 GHz.

The addition of Orthogonal frequency-division multiple access (OFDMA) sounds like a big deal. This is a new way to share spectrum among multiple users which should help contention. I think it’s all coordinated by a single access point so I guess it works for one WLAN, not resolving contention between neighboring WLANs.

Another change is changing guard intervals to a longer period. That sounds like it’d lower bandwidth but benefit longer distance operation. There’s also changes in subcarrier spacing and symbol durations I don’t understand.

It’s not clear what the maximum throughput of 802.11ax will be. People are throwing around the number 10 Gbps, which is phenomenal. According to the wikipedia chart a single stream tops out at about 1200 Mbps, but you can have multiple streams. Be interesting to see what people get in practice.

802.11ad and 802.11ay

I’ve never encountered these but given the cutesy naming (one letter above ac/ax) I include it here. These are 60Ghz protocols, also called WiGig, and I’m curious if they are an evolution of WiMAX. Maybe not; the drawback of 60GHz is not only does it not penetrate walls, but you can only throw it about 1km through the air. So it’s not great for a fixed wireless network. But so much bandwidth! 802.11ad can do 7Gbps, 802.11ay is talking about 176Gbps. Wikipedia talks about this being interesting for use for wireless displays.

Yet another new server setup post

My little projects server at somebits.com is dying. The disk errored and remounted itself read-only two weeks ago and I only just noticed. Time to set up a new server. Last time I did this five years ago I took careful notes and they are useful to me now. So another boring blog post about the new server. These recent notes for my home server were still useful.

I’m still treating Linux servers as these little carefully customized hand crafted collection of installed packages, configurations, crontabs, etc. The real world has moved on to managed services but every time I look to do that for myself it’s either too much work for a little tiny service (docker, chef/puppet/whatever) or else too expensive (cloud hosting). This time around I got recommendations to look at Ansible for low-impact server setup automation, but given I set up one server every 5 years it seems overkill. Also recommendations for Dokku as a free hosted service manager. That in turn creates Docker images and also feels like overkill and a bad match for Apache.

Part of me would love to just push all this server management “to the cloud”. But it’s still not cheap to do that for anything custom / dynamic. My old server was $59/mo, my new server is $25/mo. For a dedicated bare metal machine. It’s hard to match that price using fancy cloud stuff. My long term goal is to get my services down to simpler static files so I can just host them that way, without complex software. And any new complex software I do make, do it with cloud management.

It’d be really nice to replace Blosxom with some static site generator; then literally everything I serve on the Web would be static files. Doing that requires resolving my other blogs too; this secret work blog, also my linkblog / Pinboard account.

What to install

Looking at my list from 5 years ago I still run most of the same services. Except now I feel it’s time to shut a few down. The live rivers map; it’s a tutorial for outdated technology. And logsoflag, it’s also outdated and not something I want to keep working on. The rivers system was the most complex thing I ran (postgres, tilestache, nginx proxy, ...) so not reinstalling it saves a lot of time.

Most of what I serve is via Apache and virtual hosts. Things to get working:

  • somebits weblog: Blosxom CGI
  • somebits.com: static files
  • windhistory.com: all static files
  • somebits.com/rivers: replace with shutdown notice
  • logsoflag.com: replace with shutdown notice, maybe leave the tool working in legacy status.
  • n177xy.com: shutdown notice
  • daedalusbits.com: shutdown notice
  • Let’s Encrypt certificates for *.somebits.com, windhistory.com, logsoflag.com. Separate certificates for the three this time.

I also have some other stuff running that needs installing:

  • autossh tunnel to my house
  • crontab entries for blog, linkblog
  • munin: default config
  • chrony: default config

Configuration Notes

apache. Default Ubuntu 18 config is OK; it uses the event MPM which is reasonable. I added the following modules: cgid expires headers rewrite ssl userdir. Configured charset to utf8, added my own nelson.conf. update I forgot some content was in /usr/lib/cgi-bin; had to restore that three months later!

blosxom. Had to install libimage-size-perl for one of the Blosxom plugins. Also had to patch a problem in the atomfeed plugin; the use of {{{updated}}} as a template fell afoul of a backwards incompatible language change in Perl 5. <3 ancient languages. Also had to install python-minimal to get a /usr/bin/python (that’s Python 2), for some ancient cron jobs.

munin. Has to be installed after apache, or the apache stuff doesn’t get installed.

autossh. Same as before.

rsnapshot. Same as before.

Outcome

New server is all set up, remarkably easier since I could just look at the live running server and copy files from it. I had a backup, but nothing like a live system to clone...

Then I tried to get the disk back read-write so I could wipe it. What a mess. Trying to remount failed because the block device was marked read-only, presumably by the device driver. Trying to re-mark the block device just didn’t work. So then I ran fsck on the disk, the one mounted read-only as the operating system. Lol. Machine locked up solid. Also didn’t reboot. I guess I was hoping fsck would either refuse to run if the disk was mounted, or else somehow magically the OS would keep working even with fsck running. Nope.

RIP little server. 5 year at $59/month comes to about $3500. The hardware probably cost $1500, but then I’m playing for hosting too.

How PoB Item Tester works

I’ve been obsessed with the Diablo-like game Path of Exile for the past few months. Great game. For the code nerd in me, I’ve been fascinated by how the community has created a bunch of addons and tools to run with the game, despite the game having no support for them. The kludges are thick and woolly and fascinating.

The primary way most of these addons work is via AutoHotKey, a Windows-specific scripting system that occupies a role a little like AppleScript does on MacOS. AHK has been around forever; its main feature is that it’s very good at capturing global keyboard events and doing odd things in the background that don’t fit the usual GUI paradigm. I use it to remap CapsLock to search Google, for instance.

PoB Item Tester is the most complex addon I know. You hover over an item in the game, press Ctrl-C to copy its description to the clipboard, then press Ctrl-Win-C to have a window popup that shows what the item would do if you used it. Behind the scenes it’s using Path of Building to do calculations that simulate game behavor. PoB is a standalone Windows program that itself is a tour-de-force of reverse engineering. It is a full GUI program written in Lua (!).

Functionality aside, it’s the integration that I’m interested in. Here’s what the AutoHotKey script does:

  1. Hook Control-Win-C with AHK to get the item from the Windows clipboard and pass it to TestItemFromClipboard
  2. Write the item to a file on disk
  3. Invoke a Lua script from AHK
  4. Pop up a window based on some GUI setup done previously.
  5. Get the file created by the Lua script and display the contents

So the other half of the integration is in Lua. It has a whole Mock Lua UI system to allow PoB to run headless. Some details on what the Lua script run from AHK is doing:

  1. Set up the Mock GUI. Buried in there is the part that launches Path of Building’s Lua code.
  2. Tell PoB to load the build to test against
  3. Create an Item object based on the file written by AHK (from the clipboard). These seems to do the actual simulation calculations.
  4. Capture the item’s tooltip as HTML and write it to a file for AHK to display.

So there you have it. The game sure wasn’t designed to be scripted, but clever use of the clipboard and keyboard hooks lets people write scripts that feel like they’re running in-game. Path of Building wasn’t written to be scripted either, but someone figured out how to hack the Lua to get it to run headless and do calculations for them. That’s a lot of very motivated hackery, I’m impressed.

Amazon Fire 7 first impressions

My switch to an Android phone has gone so well I wanted to get an Android tablet, too. Only to learn Android tablets are universally considered to suck. OTOH they are also very cheap. So I picked up a brand-new Fire 7 9th generation. For $49. 16GB storage, 1GB RAM, two cameras, a full WiFi multitasking computer with a decent touchscreen display for less than the price of a fancy dinner. We live in an age of wonder. (Note 16GB storage is not enough, but it has a microSD slot. More wonders: 256GB of SD storage for $40.)

So how is the tablet? OK I guess. It seems fine for reading books and watching videos, which is what Amazon sells this for. The screen doesn’t feel quite responsive to my touches all the time but I’m not sure if that’s a hardware or software problem. 1GB of RAM really isn’t enough. CPU may be a bit sluggish. Camera quality is appalling. It comes with a bunch of adware (you can pay $15 to remove it). Did I mention it’s $49? Amazing.

The OS is FireOS 6.3.1.2, an Android 7.1 / Nougat variant. It’s ugly. It only supports the Amazon Fire store which has an anemic collection of apps. (No Firefox! No Kiwix!) The Amazon versions of apps aren’t great, like apparently the Silk browser is doing some MITM attack to try to save you bandwidth. However the device is unlocked, or at least it’s not hard to install the Google Play store and from there a bunch of normal Google Play apps. (One caveat; be sure to install the Google APKs to internal storage. Don’t format the SD card as an extension of internal storage and let the apps install to it, because then they can’t be updated via the Google Play store.)

So 30 minutes of installing later and I have a good generic Android device. Firefox for the browser. GBoard for the keyboard. Evie for the launcher, (which requires more work to launch via the launch button). Alles bueno.

I can’t find some things via the Google Play store even though they’re there for other devices; Tapet, 1Password, etc. Maybe these apps don’t explicitly mark they’re compatible with the Fire and so are excluded? I’ve been able to sideload these from APKMirror but I’m a little nervous about that, I like my trusted app stores. Particularly 1Password, brrr. All the apps I’ve sideloaded seem to work fine, so I’m not sure why Google Play isn’t giving me the choice to install them.

All in all I’m reasonably impressed. It’s not as nice as an iPad, nor even really as nice as my Pixel 3 phone. But it’s literally $49 and it works pretty well. And now I have an Android device to tinker with.

How much Mailchimp is spam? What should they do?

A discussion on Twitter led me to wonder; is all the mail I get from Mailchimp spam? Can I filter it? Turns out filtering Mailchimp in Gmail is hard. But I have a mediocre solution and some ideas on what Mailchimp should do to be kinder to email recipients.

I only notice Mailchimp mail when I get some crap I don’t want to see and click the Unsubscribe link. I get a lot of these same spams from the same company, like my old college or my local pizza place. The landing page for unsubscribing is distinctly Mailchimp, which is when I notice that they’re the source of the spam.

What seems to happen is a Mailchimp customer creates a new Mailchimp list for every marketing campaign. So I won’t get any more June 5 Campaign mails, but I’m bound to get the next June 12 Campaign mail and there’s no way to make it stop. It is spam. My question is; is all Mailchimp mail spam? (Spoiler; only 93% of mine in the last year is.)

Identifying Mailchimp in Gmail

My mediocre solution for identifying Mailchimp mail is a gmail search for three special phrases in the message body, the current copy Mailchimp includes to provide their (not-very-effective) opt-out mechanisms. This text could change at any time, but it seems to be consistent for several years now. Here’s the search term, all three phrases:

“view this email in your browser”
“want to change how you receive these emails?”
“You can update your preferences or unsubscribe”

The better way to filter would be on an email header like X-Mailer, Received, or the DKIM signature. Gmail’s filters don’t seem to allow filtering on any of those criteria. Here’s an example spammy mail; maybe someone else has a better idea how to get Gmail to identify these. (There is a possibility involving Google Script but I can’t tell if that’s really a good idea to use.)

My Mailchimp statistics

In the past year I’ve gotten 57 Mailchimp mails. Maybe more if they went to the Spam folder and were auto-deleted. I have deliberately subscribed to 0 Mailchimp mailing lists, so in some sense all 57 are spam.

However, a whole lot of these Mailchimp mails come from organizations I legitimately have business with. Reed College being the primary culprit, also my local pizza place. I’d rather not get any of those emails, but they are in some sense organizations that have a reason and a right to email me. 54 of the 57 Mailchimp mails I got are in this category, or 93%. I’d rather not get any more of them.

3 of the 57 Mailchimp mails were things I actually wanted to get. Two from the XOXO conference, one from OpenStreetMap. Those organizations use Mailchimp responsibly in a way that helps me and even if I didn’t explicitly opt-in to a mailing list. I want these mails.

0 of the 57 Mailchimp mails were pure spam. None of them were from an organization I’d never heard of before. So that’s good! Update: not a day after writing this I got a pure spam Mailchimp mail, an ad for a Kickstarter game called “Cracked”.

Still, a 93% feels-spammy rate is pretty awful and Mailchimp should do better.

Mailchimp for recipients

AFAIK Mailchimp currently has essentially no product for email recipients. We’re not customers, we’re the product Mailchimp is selling. There’s this polite veneer that somehow we’ve opted in to these communications, and Mailchimp does provide opt-outs. But they aren’t really working.

My proposed solution is Mailchimp should build a small product for email recipients. Leave the defaults as-is, to not decimate Mailchimp’s business. But give users the chance to say “I never want to receive any Mailchimp mail from this organization again”. Not just opt-out of a specific list, but all lists from a particular Mailchimp customer. It’s not simple; Mailchimp would have to create an account for each email recipient with some small Web UI, passwords, etc. It’s not a tiny project, but it’s not a huge one either.

Of course Mailchimp won’t do this. They have no incentive to. Right until the moment someone like me gets fed up enough and considers blocking all of Mailchimp as spam. Imagine if Gmail did that; it would absolutely crush the company. Mailchimp should have a solution in hand before their spam problem escalates to the level of existential crisis.

(Even better would be to require an explicit opt-in from each organization, or for each mailing list. That’s how it used to work in the old Mailman days. But no way would Mailchimp do this; it’d destroy their business.)

An alternate thing Mailchimp could do is get more aggressive at policing their customers. There’s a feedback form when you unsubscribe that includes lines “This is spam and should be reported” as well as “I never subscribed to this list”. I faithfully click one or the other every time I get spam via Mailchimp, in the hopes it creates some signal inside the company and maybe their customer will be reined in. So far I see it having zero effect though, and why would it? The spammer is who is paying Mailchimp, not me.

I have several friends who work at Mailchimp. It’s a good company and they have a good product for their customers. But as a company I suspect they are myopic, focussed only on their paying customers. I’d like them to do more to stop spammy use of their product before it becomes a crisis.

WSL access to Linux files via Plan 9

Microsoft shipped Plan 9 filesystems! Starting with Windows v1903, the Windows Subsystem for Linux now includes the ability to access your Linux files. To a casual user it’s very simple; you just open paths like \\wsl$\Ubuntu-18.04\home\nelson\.bashrc in explorer.exe or VS.Code or whatever and it all just works. Quite well too, I’m impressed. So far the only hiccup I’ve noticed is it doesn’t support symlinks, not even ones internal to the Linux filesystem.

Behind the scenes there’s a Plan 9 network filesystem involved. That’s not as weird as it sounds, I wrote some notes on it awhile back. Now Microsoft has released a technical overview video. Here’s some highlights:

  • Plan 9’s filesystem is a very simple network filesystem protocol to share files between systems. They are specifically using 9P2000.L.
  • They considered using Samba and SMB instead but can’t rely on Samba being installed and usable in the Linux guest OS and didn’t want to ship it because Samba is GPL licensed.
  • They picked Plan 9 because it’s much simpler to implement. Also Microsoft already had Plan 9 server code for some other Linux container project they’d done.
  • The \\wsl$\ path is handled in the Windows system by the MUP, an existing hook for network-like filesystems. They added a new one for Plan 9.
  • The $ is in the name so that it can’t be confused with a computer whose hostname is wsl.
  • The Plan 9 server in Linux communicates with the Windows Plan 9 client via a Unix socket. (Windows supports Unix sockets; who knew?)
  • Windows can access your Linux files even if no Linux is instance is running. There’s a new Windows service called LXSManagerUser that mediates user identity and permissions.

I continue to be impressed with the quality of WSL; it’s like a real Linux system in almost every way that matters. Microsoft has big plans for a second implementation now called WSL2 that will run a full lightweight VM. I’m not as excited about that but they say it will help improve filesystem performance, something that WSL definitely could use.

Pi-Hole problem with dnsmasqd, LXD

This is for the search engines. Installing Pi-Hole on an Ubuntu 18.10 system it wouldn’t start the DNS server. Looking at “service pi-hole status” I see this error:

May 31 15:00:05 gvl pihole-FTL[30005]: dnsmasq: cannot access /etc/dnsmasq.d/lxd: No such file or directory

For once Googling the error didn’t get me anywhere useful. I finally looked and found this symlink:

# ll /etc/dnsmasq.d/lxd
lrwxrwxrwx 1 root root 28 Apr 26 2018 lxd -> /etc/dnsmasq.d-available/lxd

However the entire directory /etc/dnsmasq.d-available/ doesn’t exist. So it’s a dangling symlink. Apparently dnsmasq.d refuses to start if it finds one of those, doesn’t just skip it. Removing that dangling symlink fixed the problem and now Pi-Hole starts.

No idea where the file came in. I tinkered with LXD on this machine in the past, maybe that’s a remnant of something I installed and then removed.

SMS vs iMessage vs Android Messages

I sure wish Android and Apple would get together and unify their messaging apps. The business with iMessage being different from SMS causes all sorts of problems. I mean mostly it’s great, it’s cheap/free to iMessage and it’s faster and more featureful. Right until the moment it fails and you really want SMS instead. Or you switch away from iOS. Apple has finally made it easy enough to de-register from iMessage, but now all my old Apple friends are sorta mystified how to message me. (Derp, the same way, it’s just green now.)

I’m more confused about what Messages from Google for Android is. It seems to be a lot like iMessage, including proprietary non-SMS transport for two users who are both using it. It does SMS too. It also has a webapp version that seems to work pretty well. (So does iMessage, a desktop app, but it’s MacOS only because Apple.) The webapp sends SMS if necessary; does it do that via my Android’s cell plan somehow? Directly? It is all a mystery.

Mostly it just feels like both companies have inserted them in front of standard SMS/MMS. And they’re adding value but in competitive ways that make it worse for consumers. No one wants that.

GPSLogger detailed notes

I’ve been running Mendhak’s GPS Logger for a few weeks now on Android. It’s good! Some details on precisely what it’s logging. I’m using this as notes for building my own GPS tracker for Wanderings. GPS Logger is good but I think it’s better to have a custom one for us.

Bottom line: the CSV format is most complete, GeoJSON has most of what you’d want in a GIS-friendly format. It logs points once a minute by itself in a mix of network and GPS modes. When a location tracking app like Google Maps is also running, GPS logger will logs points as often as once a second. Now the details...

Some of this is configuration dependent; I have it set to Log all 3 sources: GPS/GNSS, network (cell/wifi), and also passive (other apps). Logging once a minute, GPS not turned on between fixes, no distance filter. Accuracy filter dialed down to 200 meters. 60 seconds to get an accurate fix, 120 second timeout on the GPS fix. I’m logging simultaneously to GPX 1.0, CSV, and GeoJSON.

Most of this data comes from 2017-05-26, when I started in Hickory, NC and flew home to San Francisco, CA. Most of these observations are based on the CSV file which the author has said is the most comprehensive.

The data files are one-per-day. They seem to contain data from local midnight to local midnight. There are sometimes gaps of several hours, I believe related to low power / sleep modes in the phone. Particularly common in the middle of the night when I’m not moving.

On 2017-05-26 the CSV file has 6975 data points.

When I’m sitting idle in my hotel most of the fixes are of type “network”. There’s typically one entry per minute (with frequently two duplicated rows). The CSV file for those populates time, lat, lon, elevation, accuracy (typically around 20), and battery. Occasionally a fix of type “gps” also shows up; those have an accuracy of about 10. They also add bearing and speed, although when not moving those are presumably nonsense. Also HDOP VDOP PDOP and GeoidHeight, GPS-specific measurements. There’s a field for ‘satellites’ but it always seems to be 0.

Once I start driving around 14:50Z I also turned on Google Maps for routing. At that point all the fixes switch to GPS and I’m getting one a second. Accuracy is around 3 and satellites still 0; no HDOP/VDOP etc though. Plausible bearing and speed data. I’m guessing these are points GPS Logger got passively? This pattern is repeated a second time on a longer drive. Google Maps for navigation again then although I’d made an effort to turn the screen off for part of the drive.

During my flight from CLT to SFO I had the phone in airplane mode and in various pockets, etc with varying ability to see the sky. GPS Logger seems to be trying to record 1 point a minute. When it succeeds there’s two duplcate rows in the CSV, one with HDOP/VDOP data and one without. Altitude, speed, and bearing all look plausible. I mostly have no data from when I had the phone in my pants’ pocket; shirt pocket is better for obvious reasons.

Last bit of the day was me in an Uber, no Google Maps running. Odd mix of GPS and Network fixes about once a minute. It’s possible the Uber app was doing location tracking in the background, I’m not sure.

The 2019-07-26 GeoJSON file also has 6975 data samples in it. Every point has lat, lon, time, time_long, provider, accuracy. Almost every point has altitude (6759), 5032 have speed, 4094 have bearing.

The GPX 1.0 file also has 6975 data samples in it. lat, lon, elevation, time, and provider for almost all points. course and speed for GPS points also. There is no accuracy logged.

A special note on elevation: these seem to be WGS84 altitudes, before the geoid correction. (I have Use MSL instead turned off in the app.) That’s putting me underwater frequently in San Francisco, even the points from network sources. Need to think more carefully about geoid correction if I want to use this data.

Summary of all fields available by log type:

  • lat / lon: all
  • time: all
  • provider: all
  • accuracy: csv, geojson
  • altitude: all
  • speed / bearing: all (GPS source only?)
  • battery: csv
  • hdop/vdop/pdop: csv
  • GPS satellites: none (csv has them, but always 0)
  • GeoidHeight: csv

PugSQL: new Python/SQL bridge

One of the themes on this blog is “I want a really simple interface to databases for Python”. But then I’m never happy with the options. ORMs are too magic, Records is weird and limited, etc etc.

A friend of mine has written a new library: PugSQL. It’s inspired by Closure’s HugSQL. You write templated SQL statements in separate files, anything you want; selects, updates, etc. PugSQL wraps those so you can easily fill in the template parameters, call the SQL, and process the results as Python objects.

It seems like a good approach to me. Very little magic. Direct access to the actual SQL. You’ll probably end up writing some boring simple SQL that some ORM could have auto-generated but then again you’ll never be unpleasantly surprised, either.

I don’t understanding looping with Promises

Did some hair-pulling work with Javascript Promises recently. I’m calling a paginated database API (CloudKit JS), so I want to fetch N results at a time until there are no other results to fetch. In simple synchronous programming you’d do this with a while loop. But Promises can’t be reused or iterated in this way, so instead you do something that amounts to tail recursion. The Cloudkit docs have a handy example:

database.performQuery(query, { resultsLimit: 10 }).then(function(response) {
    if (response.hasErrors) {
        // Insert error handling
        throw response.errors[0];
    } else {
        // Insert successfully fetched record code
        if(response.moreComing) {
            return database.performQuery(response);
        }
    }
});

I use code much like this for real and it works. But it’s complicated! database.performQuery is an asynchronous method in CloudKit JS, it is a Promise. This code creates a new query promise, then chains it via .then() to some synchronous code that processes the response. The last thing the processing code does is check if there’s more results to come (the pagination API) and if so it creates a new Promise and returns it. Which causes the Promise execution framework in the browser to go to resolve that new promise next.

It feels very much like tail recursion. I get conflicting answers on whether it genuinely is recursive, in the sense of some Javascript stack or Promises chain growing larger and larger with each request. It’d be simple enough to do basic tail recursion optimization to eliminate that growth, just no idea if implementations do it.

My problem

So I’ve got code working. My problem is the moment I try to do something more complicated, I get lost. As a practical example; what if I want to inject a one second delay between each call to that performQuery() function? I can make a new promise with setTimeout() and chain it in there, but half the time I type the code to do that I get it wrong. I got lucky and it worked once and I don’t really understand why. Then try passing arbitrary parameters conveniently through the call chain; you can, but it’s hard because Promises only take one argument to pass along so you have to stuff your parameters into a new Object. And I haven’t even tried to reason about getting error handling right, although I think if you’re naive and don’t do much of anything then the default reject/catch behavior will probably work.

async/await

There’s a new hotness coming in Javascript with the async and await keywords along with async interation. Here’s another example of it in use. I haven’t ever used this stuff myself and am not sure if it works yet in browsers.

Update: some advice on Twitter to use async/await, that it has decent browser support.

Thinking asynchronously

This is an unsatisfying blog post where I investigated a problem and don’t really have a solution. Honestly, most of the time I do async programming in any language I feel the same way. Python, Javascript, even select()-based C code back in the day. My model of programming computers is so heavily based on imperative execution I always feel all twisted when I program asynchronously.

I need to do a series of exercises fully in an async model and get comfortable. Either that or find a good Javascript wrapper for Promises that provides higher level components like “iterate this set of promises” and the like.

Android new user notes

After twelve years of iPhone use I made the jump last week to Android phones. I’ve been curious to see how the other half lived and Google had a one day sale on the Pixel 3 that was enough to make the jump. (The new Pixel 3a just released is a hell of a good price.) This marks a slow migration for me away from Apple products. They aren’t quite the quality innovator they used to be, and their closed approach to ecosystems has always bummed me out.

So far I like the Android quite a bit. Everything I expect from a fancy phone works. And I’m enjoying discovering new things. I think part of the fun here is just I’m revisiting how I use my phone from the bottom up; maybe I’d think it was juts as neat if I were switching to iOS for the first time.

Anyway, here’s a bunch of thoughts I collected as I learned the new platform

Software

The first setup where it copies from the iPhone is slick. Particularly like how it matches the apps you have. Sadly it can’t copy app data or state like logins.

Pretty much every single app I cared about on my iPhone also had an Android version. About 75% of those were found by the migration tool, the rest I had to install by hand. I only had to buy one app; Paprika, the recipe software. Most software I pay for has an account subscription model like Spotify, not a one-time app purchase model. The one app I could not get on Android was Overcast, no surprise given its author’s Apple fanboy status. Fortunately there’s lots of other podcast players for Android. PocketCasts is probably the best choice. I’m trying Podcast Addict for now but it’s a pretty rough UI to love.

It’s nice being in Google’s loving embrace; Gmail, Photos, Drive, etc all well integrated. Apple’s policies are better for users since Apple isn’t an advertising company. But their services like iCloud are not very good, I’m really glad to not be living under iCloud anymore. Google’s services are good and I’ve been using them for years, nice to have a phone that wants to integrate with them.

I like the home screen! I particularly like the ability to have widgets from apps draw little decorative things on the home screen. I also like the back button. This bit of UI is a source of confusion for many, and often myself, because it can both go back in a single app and also go back between apps. But it mostly seems to do what I mean when I press it. The shortcuts for switching between apps are good too.

Android apps are small! They are 1/3-1/5 the size of their equivalent iOS apps. For an extreme example, Facebook is 450 MB on iOS and maybe 50MB on Android. It’s common to see many Android apps < 10MB download. I haven’t read a completely convincing explanation why, but see here for some ideas. There’s also a new tool to make builds even smaller. The smaller size definitely results in noticeable bandwidth and storage savings; maybe RAM too.

The 1Password integration in the OS is terrific, particularly with apps. Way better than what iOS has tried to kludge together. More generally the integration between apps in general is quite nice on Android, it’s fairly easy to share data from one app to another in a way that never seems to work on the iPhone. The “intents” system lets apps publish APIs for other apps to use. There’s even complex automation for chaining apps together. iOS has something similar now in Shortcuts, but I’ve never used it.

Android has a file system! You can browse it with Amaze File Manager. Apps naturally share files through it, like Sonos playing files Podcast Addict downloaded. You can also bridge out to Google Drive fairly simply and then have the same files on your desktop computer. iOS has always had a notion of files too but they are well hidden and seldom (never?) cross-app.

I can run a real Firefox! With real Firefox addons! None of this “must use Apple’s embedded WebKit” crap. Firefox on iOS is a heroic effort and has a lot of useful Firefoxy features, but when you pull the mask away it’s still Old Man Smithers underneath. There’s something to be said for platform unity, but there’s something to be said for competition too.

Notifications are awfully spammy. Every app (say, Amazon Store) wants to send you notifications all the time. Even with something where it could be useful (say, Washington Post) it’s mostly annoying. It takes some looking but you can extensively customize notification behavior. Some apps have an in-app bunch of settings. And the system has Notifications settings on a per-app basis. Each app has notifications one of many channels (often only one) and for each channel you can configure whether it makes sounds, vibrates, etc.

The phone definitely feels more hacker-friendly. In particular there’s a reasonable chance interesting apps are open source, like GPS Logger. I can’t think of the last open source iOS app I saw. Also I like that I can realistically write code for my Android phone using any computer, not just MacOS. My brief look at Android Studio is encouraging, it seems like a solid IDE.

I gather Android version proliferation is a real problem. I’ve got Pie, which is version 9 of the OS. The development kit tells me if I write code for this version less than 1% of users will be able to be run it. Version 6 only has 63% of users! Also from what I see online the UI changes radically between versions. Always improving, hopefully, but change has a cost.

I also gather vendor Android modification is a real problem. Carrier-sold phones in particular have all sorts of crap on them, as do a bunch of the cheaper Android phones. Some of that crap is locked and hard to remove. I bought a Pixel because I definitely didn’t want to mess with Verizon or Xiaomi’s idea of how they could make an extra $20 off me. The only other brand of phone I’d consider buying is a Samsung Galaxy Note.

I haven’t gotten too deep into lower level system hacking, but it’s nice that Android lets you do it. Even without rooting the device. The is pretty good if you want a quick look at the (non-root) filesystem and some easy upload / download. The GSam Battery Monitor is amazing if you want low level battery watching stats. Even includes using some just-short-of-root debugging interfaces for extra detailed stats.

Android Auto seems fairly good. Not quite as slick as Apple CarPlay, but then not as proprietary either. (Apple for years prevented any other maps from displaying in CarPlay, for example.) One nice thing is you can run Auto even when you’re not plugged into a car display, it has a car-optimized display right on the phone screen. Good for testing or using in an older car without the ability to plug a phone in.

Pixel 3 hardware

In general the hardware is lovely. Flat slab of glass, no distinguishing features except an ugly bright orange button (a feature of the pink-backed phone). Under the hood the Pixel 3 has gotten some criticism for being underpowered for the price but I don’t have any perception of that. The camera is as lovely as people say. Coming from an iPhone I don’t notice the lack of an SD card although in retrospect I wish I had one. Also baffled why there’s no dual SIM; so useful! The new eSIM alternative is proving to be an inadequate kludge.

Cables continue to be a problem. The Pixel 3 has one USB-C port and nothing else (like a goddamn Macbook.) Worse though is I don’t have a USB-C port on any computers here, and they don’t ship with an adapter to a male USB-A connector. They do have an adapter for a female USB-a port, which you use when syncing two phones together, but I had to order the rest. Nevermind that most every USB charger, automobile port, radio port, etc is not USB-C. Argh. At least it’s not fully proprietary like Lightning.

It gets trickier with charging. For wired charging Pixel 3 supports 18 Watt “rapid charging” which apparently is USB-PD, an open standard only now being implemented (Apple’s new phones use it too). AFAICT USB-PD is a USB-C only thing in practice, older type A cables don’t allow USB-PD 2.0 or above. Older fast chargers on a type A cable use Qualcomm’s Quick Charge or some other proprietary thing; the best I’ve been able to do is 8W from them, maybe 10.

It gets more confusing with wireless charging. Google has a proprietary system that allows 10W wireless charging. Other standard wireless chargers (there are such things?!) are limited to 5W. In theory third parties can build 10W compatible wireless chargers but there aren’t any yet.

Of course there’s no analog headphone jack, which is as obnoxious as I feared. But I can live with it. Also the Pixel 3 apparently has no capacity to send HDMI out a wire. The USB-C adapter for headphones works OK but has different wiring from Apple’s proprietary, so I can’t use a full Apple headset with it. The supplied wired headset is fine, the fit sure is better for me than Airpods. Also the sound output is way louder than the iPhone’s ænemic headphone out.

I don’t much care for the fingerprint sensor in back. It means you have to pick the phone up to unlock it. Also the sensor is not accessible on the Pixel Stand; you have to pick up the phone. Don’t miss not having a hardware button in front for the home screen though. And the sensor itself works well. It doubles as a shortcut for “show notifications” too if you turn that feature on.

Conclusion

I like my new Android phone! I was going to spend weeks migrating; I ended up switching over the day I got it set up and haven’t missed the iPhone once. In most ways it seems to be fuctionally equivalent to an iPhone. I’m surprised the UI polish is better than I feared. And I like the relative openness and hack-friendliness of the Android.

My next goal is to start writing apps for the thing. Will no doubt have lots of notes when I get to that.

CloudKit JS: hasErrors vs isError

Well this is a nuisance. A lot of CloudKit requests have two different ways of signaling errors when you make Javascript calls to the iCloud API.

The request can look like it succeeded and returned a Response object of some sort. But instead of the response you want it can have the hasErrors flag set, in which case there’s a whole array of errors objects. This method is what’s shown in example docs.

The request can also just fail and the method returns a CKError object instead. This object has an isError property, also an isCKError. I’m not positive but I think this mostly catches client-side programming errors, like when I put in an integer where a string array was expected.

In neither case does the Promise reject; it resolves with some sort of error status. So for now every call to a Promise in CloudKit JS I make has right after it:

        if (response.hasErrors) {
            reject(response.errors[0]);
        } else if (response.isError) {
            reject(response);
        }

I wonder if there’s a better idiom.

Dismal programming language law: no matter how many language features there are for signaling errors out of band: Exceptions, Promises rejects, etc.. Programmers will ignore those and return error values in-band instead.

Installing esridump on Windows

I just wrote these notes up for a friend. esridump is a Python tool that will take the URL from an ESRI ArcGIS REST server and dump all the data in it to a GeoJSON file. It works by doing REST queries on the predicate “where 1=1;”, the only subtle thing is you have to paginate the requests because there’s a limit to the number of results from one query. It’s a nice tool; there are several others floating around out there like it.

Installing it is basically as simple as “pip install esridump”. It has very few dependencies, no GDAL or other GIS giant libraries. But I wrote these detailed notes for a friend of mine:

ArcGIS RES

  1. Install Python 3.7.3. Make sure to click “Add Python 3.7 to PATH” when installing.
  2. open a cmd shell, everything else is in there
  3. cd Documents
  4. mkdir pyesri
  5. cd pyesri
  6. python -m venv venv
  7. venv\Scripts\activate.bat
  8. pip install esridump
  9. venv\scripts\esri2geojson.exe http://SERVER-URL/ out.json

GPS Logger app for Android

I’ve made the switch from iOS to Android. One thing that means is I need a new GPS tracker; my own Wanderings app is iOS only. I may end up writing an Android custom app myself to do that.

For now I’m using the excellent GPS Logger app. It’s a very flexible passive location tracker, open source, lots of control over exactly what kind of data to log and where to upload it to.

It has three sources of location updates:

  1. GPS/GNSS locations. Honest to goodness satellite fixes
  2. Network locations. Info based on wifi and cell tower fixes
  3. Passive locations. Any time any other app gets a location, GPS Logger gets a copy

I currently have #2 only turned on and it seems very low battery impact, certainly OK to leave on for 24 hours. Once a minute it wakes up, asks the phone where it is, records the data into an internal log file, then goes to sleep. The location data seems pretty inaccurate though, I need to look closer.

I tried #1 for awhile and it seems higher power impact; not sure you can leave it running for 24 hours. (Update: it’s not nearly as bad as I first thought, and might be fine for daily use. Even once a minute.) Data is quite accurate but demanding. It wakes up the GPS chip, waits for 1-2 minutes for a good fix, then records the location. You can also tell it to leave the GPS chip on always, but there’s a warning about “dramatically decrease the battery life”.

#3 seems like a freebie, of course you should use it. I only have it turned off because I’m trying to keep it simple so I understand what GPS Logger is doing itself.

They also have abilities to filter points based on reported accuracy of the fix, and how far you moved. And there’s a way to tell it only to log if the accelerometer detects the phone is moving.

What I haven’t found in GPS Logger is anything like the “significant location changes” API that Wanderings uses in iOS. Nor anything like geofences / regions. Those may be in the Android API and just not in this app.

Update: after a few days playing around with GPS Logger I have some extra notes.

I’ve been running the GPS Logger app on Android in full logging mode for a few days now and its impact on battery life is neglible. My whole phone only uses ~40-50% of its battery in 24 hours. 0.1% of that is attributed to GPS Logger itself. 42% is the wifi radio, 25% if the screen, 10% is the OS.

GPS Logger is currently logging my position once a minute. I’ve told it to use both GPS and “network locations” (wifi/cell). It seems to request both types of position at once and almost always the network location answers first, so it never logs the GPS. I’ve run it in GPS-only mode too to get real GPS fixes, those often take 20+ seconds and don’t work great indoors.

The most problematic thing is that GPS Logger doesn’t log points at all for hours. AFAICT this is a significant problem in Android phones in general, that background apps often don’t run when the phone is in “doze mode”. It mostly happens in the middle of the night where I’m definitely not using the phone so it might be the “right thing” but it’s a problem. I’ve read various hacks and workarounds, see the GPS Logger FAQ. GPS Logger has a gimmick where it constantly has a notification on screen to try to stay more lively.

Funny thing; some apps I don’t even actually use are consuming more battery than GPS Logger. Like Maps.Me was using 2% a day until I went in and told it to be “very low power”; I haven’t even launched it! Google Fi also uses 1% even though I’m not using it.

SyncThing

After getting NextCloud set up I was uncomfortable with how complicated it was. So I gave SyncThing a try and it’s much more to my liking. It’s a much simpler system. NextCloud has a full database and users and passwords and APIs and stuff. SyncThing just synchronizes folders. In that way it’s a lot like Unison, or FreeFileSync. (More complicated than rsync, since it maintains state between synchronization runs). But it’s built for network synchronizing.

Installation is simple. Every machine that wants to sync a folder runs the SyncThing binary in the background. That publishes a nice Web UI on port 8384, also an application specific socket on port 22000. Getting two machines to sync is a little weird. Every machine has a name and you can just tell machine 2 “sync with machine 1”. A dialog pops up on machine 1 then to authorize the connection. No visible passwords, but presumably some public key crypto under the hood. Once the machines are talking to each other you then set up synchronizing folders.

I may have made things complicated myself but the folder setup seems complicated. For every new machine I add to my sync cluster I had to go through each folder and share it. There’s something called an “introducer” where one machine will offer a list of folders to the other machine, but I either don’t understand it or broke it somehow.

I also made things more complicated than necessary by disabling machine discovery. I mentioned way above machines have names; how do you find a machine on the Internet given its name? There’s some global discovery protocol built under the hood, a peer to peer network sharing names. It’s quite neat but I’d rather not be quite so promiscuous so I turned it off. You can manually configure via IP addresses if you want. (They also have a relay network for cases where two machines are so firewalled they can’t connect to each other. Neat!)

I haven’t stressed the sync algorithm too hard but it seems to be working for me. It even does something reasonable for conflicts.

I took a quick look at GitHub and the primary author is Jakob Borg, aka calmh. He also has a consulting business called Kastelo. He seems super nice and helpful on the community forum answering lots of questions. Development started late 2013.

All in all I’m quite impressed with SyncThing. It’s simpler and less featurful than DropBox/NextCloud/ownCloud, which is exactly what I want. Keep two folders in sync, that’s all I want.

(A thorough blog post would include an investigation of Resilio, formely BitTorrent Sync. By all accounts SyncThing is quite similar to it.)

Hosting your own Dropbox clone

I decided to set up my own private file syncing service. Dropbox recently degraded their free level, limiting you to three devices. Fair enough but ugh. Also I’ve been doing a funky hack with FreeFileSync where I keep personal files on two Windows boxes in sync via an external hard drive I carry back and forth. That works and solves the bandwidth problem, but is kludgy.

So.. what’s out there for free Dropbox alternatives? A quick search turns up ownCloud, NextCloud, and Seafile as popular choices. NextCloud is a fork of ownCloud and seems to be doing well so I picked that one.

NextCloud requires you’re running a server on an always-on Linux box somewhere. Installing the server is either a complex mess or as simple as could be. If you go the old school manual route it’s a mess; the server requires MySQL and a web server and a bunch of PHP stuff. They have detailed docs on how to install it on Ubuntu, but ugh.

Happily they also have a containerized server, Nextcloud Snap. And I’ll be damned but it really is as easy as a couple of lines of shell to install and get running. The only wrinkle I ran into is they really want to be running a visible web server under the / URL, and I already have a web server. So I had to change the ports the web server uses

sudo snap set nextcloud ports.http=81 ports.https=444

So far it seems to be working, we’ll see how it does in a month. The product is probably overkill for personal use, it’s really set up for a whole small office with many users, fancy integrations with apps, etc. I just want a better rsync!

The one thing I didn’t evaluate is SyncThing, the outcome of the old BitTorrent company that is in fact a better rsync. I’d like to try that and see if it’s a lightweight alternative.

Update: a second wrinkle; all my user files are being stored in the Snap directory, which is on the small / fast SSD. I wanted to replace that data directory with a symlink to a slow hard drive, but of course the symlink goes outside the Snap container’s boundaries and doesn’t work. There’s various workarounds for this but for now I’ll just live with it.

Custom web fonts in 2019

I finally updating my old somebits.com CSS to use a wider text box and a modern font. Goodbye, Arial 400px wide! I’ve not paid much attention the development of CSS3 font technology so this is all new to me. I’m using free fonts.

Which font?

Free, not ugly, and with decent Unicode range. I looked through this Wikipedia page and hit on several likely options: Bitstream Vera, Liberation fonts, Noto fonts, and Source Serif Pro. I decided I liked how Source Serif Pro looked best. I don’t know how great its Unicode coverage is; from what I’ve read it’s mostly western scripts. Fine for normal use, and hopefully the browser fallbacks will suffice for the occasional CJK or obscure other stuff.

Update: I just realized that Feedly uses ITC Charter, which is free. There’s also a Unicode-enhanced version from SIL called Charis. I converted their WOFF to WOFF2 using an online tool and tried it on my blog. It’s stylistically very similar to Source Serif Pro but not quite as good looking and significantly larger files, so I won’t use it.

Hosted fonts

The easiest way to use a custom font is use a hosted solution like Google Fonts or Adobe Fonts (nee Typekit). They have you include a single CSS stylesheet and then you can refer to the fonts by name in normal CSS. The problem with this is they then get tracking info on every page that uses the font, which is bad for privacy. So I’d prefer to self host.

Self hosting

First you have to download the font in the right format. Choices are EOT, TTF, OTF, WOFF, WOFF2, and SVG. This website says EOT and SVG are obsolete, and TTF and OTF are unnecessary, and that WOFF is basically a wrapper for TTF/OTF and WOFF2 is just an improvement on WOFF. Confusingly, Adobe’s distribution of Source Serif includes both “TTF WOFF” and “OTF WOFF” versions. This page says OTF is better. WOFF2 seems to be nearly universally supported so I’m going to go with that with the OTF variant. (A lot of sites still serve WOFF as well, but I think that mostly only matters to MSIE 11 at this point.)

You can get a clue how to self-host fonts by just copying what Google or Adobe serves as CSS. See Adobe, Google. You can get pretty far just by copying what they do but changing the URL. But starting from first principles...

The simplest thing that work is this little bit of CSS

@font-face {
  font-family: "source-serif-pro";
  src:url("SourceSerifPro-Regular.otf.woff2");
}
body { font-family: source-serif-pro }

This says “I’m declaring a new font-face named source-serif-pro and you can find it at this URL”. Then tell the body of the document to use that font. And it all works, done! It also does reasonable Unicode fallbacks for things that aren’t in the font. But not quite done; this font only is normal font; the browser will fake italic and bold versions (ie, ugly). This is better:

@font-face {
  font-family: "source-serif-pro";
  font-style: normal;
  font-weight: 400;
  src:url("SourceSerifPro-Regular.otf.woff2");
}
@font-face {
  font-family: "source-serif-pro";
  font-style: italic;
  font-weight: 400;
  src:url("SourceSerifPro-It.otf.woff2");
}
... versions for Bold and BoldItalic as well ...

That will let the browser use a properly designed italic font when necessary instead of just slanting the letters to the right. That really matters for bold, bold is used a lot in CSS (like headers). The key thing here is you’re expanding the options available on the source-serif-pro family, with the cost of now the browser has to download more files (100k each). In theory you can bundle all 4 variants into one file using variable fonts but I think that’s still a little bleedingedge.

There’s some advanced options too. You can tell the browser you only care about certain Unicode ranges, which may help with download sizes. You can tell the browser to preload the fonts or use local copies if the exit. You can fine tune whether it will use a system font until the real font is loaded. You can also tweak font rendering settings and kerning.

Anyway, now I know how to self host a font. You can see a bunch of test cases, etc in this dev test directory. The selfhosted variation is what I will end up using.

Working on a regional map for Papua New Guinea

A friend of mine is an anthropologist expert on Papua New Guinea, particularly Enga Province. There are precious few good maps of PNG (famously) so he’s asked me if I could help prepare a schematic map of the region he can use in a publication. If it goes well maybe we can submit the map to Wikipedia or something too.

For inspiration I pulled a bunch of sample maps from Bing / Google / Openstreetmap, also from the Rumsey archive and various online sources. I particularly liked this map (from this paper) and the SIL map. Openstreetmap’s default map style isn’t bad, either, and I’m encouraged by how much data OSM has. (I don’t need detailed roads, just a single image at large scale.)

It’s interesting how some of the custom maps emphasize roads, others emphasize rivers. Really terrain is a pretty key element of understanding the area too, it’s quite rugged, but most of the maps I see are constrained by print restrictions to not including terrain.

I’m also starting to read up on Wikipedia’s guidance for maps. WikiProject Maps is a good place to start. I really like their exemplar of The Big Island of Hawai’i; the combination of coloured elevation contours and subtle hill shading is great as a base for the map symbols. They also have an SVG template for icons and such. A lot of these principles only work in color though, and I think for print I have to go greyscale.

As for implementing this, my plan is to start with Natural Earth and OSM data and rough something up in QGIS. And then start working in earnest with a tool to extract the data I need and export it to SVG format. Mapnik maybe? Then use Inkscape to further style and deliver the SVG, also allow non-map experts to add text annotations. Or maybe I can lean on QGIS more than that and not write custom code to emit the SVG I need. Looking forward to learning more.

Facebook’s population density data

A group over at Facebook has released a valuable new dataset, High Resolution Population Density Maps. They used machine learning to look at aerial imagery and figure out where people live, then put dots on a map (one per arcsecond) with estimated density. Their post goes into detail; the data now is most of Africa with the whole world planned. There’s not a great browser for the data but the files are easy to work with and smaller than you’d think; a few megabytes per country.

I took a quick pass at the Liberia data in QGIS, here it is plotted by quantiles on top of Stamen Toner Light:


It’s immediately apparent that the density data is banded. Each red dot in Monrovia, for instance, has the (exact) value 23.255445274781373. Half the dots have no value, even in the middle of the city, maybe because no single building was reliably detected in them? The orange dots north of there are about 9.3. Some small villages out in the hinterlands show very high densities, like 45. I don’t know if that’s at all like reality or rather an artifact of detecting relatively few buildings in a big rural area.

By contrast Johannesburg has much more variation in densities. Maybe South Africa has better data on population-by-region than other places

Nigeria’s data is somewhere inbetween. Lagos has big regions of uniform density but there is at least some variation. I can’t figure out what the building detection did in the rural areas. Their system did correctly figure out there are people in this general area, but the dots and the buildings don’t particularly line up.

I’m no expert in this kind of data and have no idea what the state of the art is. But this looks to me like two separate datasets mushed together. One is new and fine grained, a binary yes/no building per arcsecond based on image analysis. And then there’s some larger granularity numerical “X people per building” that they’ve taken from some other data source, maybe government census data. The combined data is them just applying that number X to the binary thing about whether there’s a building or not.

It’s not bad! But I had initially thought they were doing something more subtle, where they were estimating building size or height or density. If I’d read their description more closely I would have already realized they were not doing that:

we redistributed all the census counts equally over all the buildings found within that census area. This method assumes equal population distribution per building within a census area, which we felt was the least error-prone method of obtaining population densities since it doesn’t make any assumptions on the number of people per building and constrains systematic errors to within one census area.

For an alternate take at the data, @Mikel took a shot at a slippy map using MapBox, you can see the result here. I had trouble getting it to load new points past the initial view. But see the screenshot below

CA-1: Congressional vs State Senate district

We have a special election for California State Senate in District 1 this year. Judging by past elections this district is roughly 65% Republican. I was confused because California’s National Congressional District 1 looks like a very similar part of California, the northeastern rural part. But it was only 55% Republican last year. Why the big difference?

So I made a map of the difference between the two districts. Turns out the Congressional district includes a big part of the northern central valley including Red Bluff, Chico, and Oroville (outlined in blue). (Also a tiny bit of rural area north of Roseville.) The State Senate district instead includes a chunk of the middle Sierra including Truckee and Placerville. I don’t have demographic data in front of me but it seems plausible that explains the political difference. Static map below, there’s also a slippy map online.

Details: I used 2017 data from the US census, The files are cb_2017_06_sldu_500k and cb_2017_us_cd115_500k. I then did some QGIS munging (finally, easy basemaps!) to calculate the simplified symmetric difference and display it reasonably.

Mapbox GL Native telemetry

I finally closed the loop on a long-standing problem we have had with our Wanderings location tracker. We wrote our code to be very low impact; it uses the Significant Location Changes API on iOS to track your movements in a very passive way. But our app was causing the phone to use as much as 100 MBytes/day when running in the background! All that bandwidth was accounted to “Time & Location” in iOS itself, not our app.

Much sleuthing later we narrowed the problem down to Mapbox Metrics, their telemetry service. You can see some discussion in this bug report, but the behavior is expected, not a bug. And somewhat unique to our app. If we turn off telemetry our usage goes down to < 1MB / day of data.

By default telemetry is turned on if you use Mapbox native in your app. And it listens to location updates your app gets. If your app gets a notification the person has moved, Mapbox then requests fine grained location updates for a short period of time. (5 meter movements for 5 minutes, I believe.)

There’s nothing nefarious or dumb here. The location telemetry is a disclosed part of the product and the code is open source. They have appropriate privacy protections. And it’s a reasonable form of telemetry for most apps. I imagine most Mapbox apps have the map front and center as part of the UI with location tracking already enabled, so Mapbox’s telemetry requests don’t really generate any more traffic. Unfortunately our app is just unusual in wanting low impact background updates only, not a good match for the telemetry behavior. Fortunately our users can turn off the telemetry tracking if they want. (In fact, Mapbox requires that apps provide a telemetry opt-out option for users.)

The other confusing piece of this is why does location tracking use so much network bandwidth, and why is it attributed to iOS itself and not our app? Only Apple really knows, but I have some guesses. Phones almost never use an honest GPS signal to track location; mostly location is tracked by reference to nearby Wifi and cellular signals. My guess is every time the phone wants to know its position the iOS location daemon itself makes a TCP/IP request to some Apple server to do a lookup. (I’ve definitely noticed that my location tracking goes way worse when I have cellular data turned off, say when traveling in Europe.) That data usage is significant if you are tracking location in a fine-grained way. And since the request comes from iOS and not the app, the bandwidth is accounted to iOS itself.

While I’m guessing, I think in practice “significant location change” means “moved into range of a new cell tower”. My guess is those location updates come “for free” because the cellular chip already has to do a bunch of work for tower handoffs. Based on observation, moving in range of a new Wifi network is not enough to trigger the location update.

Learning about containers

I decided it was time I learned about containers. My immediate goal is considering running the Pi-Hole DNS server in a container via docker-pi-hole or manually installing it under LXC. It’s a toy problem, but it’s one I’m considering at the moment. Really it’s an excuse to learn more about containers. I’m a newbie here and there’s a lot of depth I don’t have, but maybe my notes are helpful to someone.

What’s a container? It’s a way to run a program or collection of processes so that the service they implement is relatively isolated from the host operating system and other services running on the host. The isolation is mostly for system administration convenience, a little like we use virtualenv in Python or node_modules in Node to keep libraries separate. Only a lot more complicated than just a bundle of files. Containers package up files, running processes, network access, I/O, device access, etc.

A key reason people like containers is they provide a way to isolate a complex software package in a repeatable lightweight environment. You can hand a new employee a Docker image for their development environment without laborious instructions on how to get set up to work. Or a developer can spin up an environment on their dev machine that’s just like the one in production, run some tests, tear it down, and rebuild it frequently and fast. See this AWS Lambda emulator as an example.

Another key piece of containers is they are lightweight. A VM takes 10-60 seconds to start up (or more); a Docker container can take less than a second. The container doesn’t need much more memory than the processes running natively. And there’s a lot of tooling that makes it easy to build container images and manage them in a space-efficient manner.

Some overview reading:

Not containers

To understand a thing, first understand what is not that thing.

Virtual machines are not containers. Well, a VM is a container in some sense, but it’s more heavyweight than what people usually call a container. In a container there’s not a whole kernel and guest OS running; the processes are running directly on the host kernel. But those processes are isolated in important ways. A container is more like the traditional Unix security model of running a service as a user with access limited to just some smalls et of files. Or like the venerable chroot, which dates back to v7 Unix in 1979. But the old Unix methods of isolating a service’s processes don’t work very well, so modern containers use a newer set of kernel interfaces to enforce isolation.

AppArmor is also not containers. AppArmor uses Linux Security Modules to grant certain programs a very narrow set of permissions. These are configured with files in /etc/apparmor.d, you can browse Ubuntu’s here. For instance chronyd is limited to things like setting the time, binding a network socket, and writing a few files like logs in specific chronyd directories. If chronyd starts trying to do anything else AppArmor should stop it.) AppArmor has some overlap with container tech (LSM is a bit like seccomp). And some containers (like Docker) use AppArmor as extra security. but AppArmor is intended as a security measure, not a devops tool. (Same goes for SELinux; can be used to help secure a host running containers, but not a core component of the container.)

Container technologies in the Linux kernel

Containers implement isolation with help from the kernel. Unix has always had a modest concept of processes being isolated from each other. Memory isn’t shared by default, user permissions enforce some isolation on who can access files and other resources. But it’s not very secure and it’s not very flexible, so modern containers rely on newer APIs developed in the last 10-15 years. Many of these are fairly Linux specific, although both BSD and SysV were influential in the 90s and 00s developing isolation technologies like BSD Jails.

Namespaces are a Linux kernel feature for completely isolating one set of processes from another. In normal Unix you can see another user’s processes even if you can’t do anything to them. Inside a PID namespace you can’t even see others’ PIDs to try to access them. Same goes for filesystem namespaces, network namespaces, etc. Namespaces are created with the unshare(1) command which uses the unshare(2) system call. See also namespaces(7). You can create separate namespaces for mounted filesystems (a bit like chroot), hostname, IPC, IP network, PIDs, cgroups, and users.

cgroups (“control groups”) are a way to manage resource usage for a group of processes. nice(1) is an example of a very simple form of CPU resource usage. cgroups let you control not only priority (like nice) but also absolute amount of CPU used in a period of time, memory usage, I/O, process creation, device access, etc. The API is quite complicated, I think mostly because it works on groups of processes (and threads). See also the cgroup v2 design doc.

Seccomp-bpf is a way to control what system calls a process makes. System calls are the primary way a process affects the rest of the world; limiting system call access can greatly isolate a set of processes.

capabilities are a different way to restrict what a process can do, based on abstract capability concepts instead of system calls. I mostly think of it as a way to avoid giving a process full root access just to do one simple thing. Instead you can give a process just the ability to bind privileged ports or set the system clock or whatever specific capability it needs.

A word on security

I can’t figure out how secure containers are supposed to be. How hard should it be for a rogue process to break out of a container? The best answer I’ve gotten is “it depends on how secure you made your container”. (Which in practice seems to be “not very”). FWIW I asked on Twitter and pretty much no one considers a Docker container to be a significant security measure.

I looked a bit closer into this with Docker in particular. Docker is so complicated and uses so many different Linux security mechanisms that exploitable bugs are inevitable. And Docker is designed to not be fully isolated or virtualized; most Docker containers deliberately have at least some access to the host system, a network port or part of the filesystem at least. The Docker folks do take security seriously, and when security holes are found they get the full CVE treatment. Still it seems no one considers Docker a full solution for running untrusted code safely.

One big thing I learned is if a process has root privileges inside Docker, then if it escapes the container it very likely will have root outside the container too. There is a way to map root-in-the-container to a non-privileged user outside the container, but it’s complicated and I’m not sure how common it is. Pretty sure it’s not the default.

Bottom line: don’t assume a malicious program inside a container is really trapped inside the container. Too bad, I’d been hoping Docker would be a good way to mitigate the risks of daemons that run as root. It might yet be such a tool but it ain’t simple.

Update: containers vs. Zones vs. Jails vs. VMs is good reading.

Container implementations and tools

So there’s a bunch of low level kernel support for isolating processes in Linux. How do you use them conveniently? A container implementation bundles all those mechanisms together into one easy-to-use tool. And miraculously, a tool that might even work on something other than Linux (perhaps with a VM to help things along). There are a bunch of container implementations out there, let’s look at a few of them.

Docker is the big player for containers and whole books are written about it. Docker wraps up a bunch of those isolation technologies and makes them easy for an end user to use. Docker is cross platform: you can run other OSes both as Docker guests and as Docker hosts, although often when you look there’s a VM involved in making that possible.

To use Docker you start by getting a Docker image from a repository like Docker Hub or else create your own image. Docker images are created from a specification in a Dockerfile; the image is a collection of files and expected behavior. You then launch the image via Docker’s runC / containerd system, which creates a container. Inside that container environment is whatever the image was specified to do; one simple command line tool, a persistent daemon, a full-fledged operating system image with interactive shells. Docker takes care of managing file persistence so you can shut a container down and restart it again with the same files. Docker’s use of overlay file systems is particularly nice here, you can assemble a container out of a stock Ubuntu file system, an overlay for (say) a database server, and then an extra overlay for your actual database state that’s changing all the time. It’s all quite efficient.

The key thing about Docker is that it’s a pretty solid tool, friendly for developer-users. Also Docker Hub is amazing, it’s a community managed library of operating system images with all sorts of complex and useful things preinstalled. My devops friends also like the way a developer can run a Docker container on their dev machine to test their product, then run basically that same container on production machines to serve live traffic.

Docker’s not the only game in town though. Linux Containers (aka LXC/LXD) are a nice smaller alternative. (Docker started life as an LXC wrapper although it has since evolved.) I liked this tutorial on running Pi-Hole in LXC because it’s so straightforward and simple compared to all the stuff surrounding Docker. OTOH it lacks all the conveniences the Docker ecosystem has built up.

Snap also has my attention because it’s built in to Ubuntu. It’s Canonical’s answer to Docker. I haven’t heard of many people really using Snap but there’s a few hundred Snap-packaged apps in the store (including some that baffle me; why package the command line tool jq as a Snap?) Most of what I’ve read about it is trying to use Snap to solve the “how do I distribute user applications on Linux?” problem. Canonical wants Snap to work across Linux distros. Also I’ve read a claim that Snap is somehow better suited for GUI apps than Docker would be. It’s interesting that Firefox and Slack and the like are available as snaps.

gVisor is an interesting alternative I mention briefly because it takes a different approach. Instead of a bunch of Linux isolation technologies it works by emulating most of the Linux kernel in a user space process. That makes it more like a VM, and also a little like the Windows Subsystem for Linux. I have no idea if anyone uses it, but it’s nice that it drops in to Docker as an alternative for runC.

So there’s a bunch of ways to run a single container. In addition there are complex orchestration software layers out there to help you manage a machine cluster running lots of services in containers. Kubernetes is the one that gets most of the attention right now, there’s also Docker Swarm and Apache Mesos and a bunch of others. I haven’t looked into using any of these but I can say back in the day Google Borg was The Shit, a key part of how that company could operate at the scale they do.

So what about Pi-Hole in a container?

So now that I’ve read several books on yak shaving.. should I run Pi-Hole in a container at home? I think no. The main problem is that at least with Docker, I still have to make changes in my host computer in order to use Pi-Hole on it under the container. And there’s no real reason I can’t just run Pi-Hole directly.

Pi-Hole distributes a nice Docker image I got up and running. But it’s a bit tricky. First, Pi-Hole wants to own port 53/TCP and 53/UDP on your host, to provide DNS services. Fair enough but by default in Ubuntu systemd-resolvd already laid claim to it and gets in the way because of the strange way Ubuntu machines do DNS. So you have to modify the host network config to make it available, which sort of obviates the whole “I’m running Docker so I don’t have to make changes on my host machine” argument. Pi-Hole also wants 80/TCP and 443/TCP; not just for the admin page but also to redirect ad HTTP requests to something that returns an empty page. Again same problem, I already have a web server.

Bottom line; the Pi-Hole service wants to do stuff in the host’s network namespace, and that’s all a bit awkward since the whole point of Docker is to contain things. I’m out of my depth here but it’s a shame there’s not some way to just publish the services on a second IP address for the container, like the docker0 network device listening on 172.17.0.1. Actually that may be entirely possible, but then I have to convince my whole home network where it can find 172.17.0.1 and that’s more routing infrastructure than I have.

On top of it being awkward, Docker does introduce a fair amount of overhead. There’s the docker daemon itself (1 gigabyte of RAM mapped! Although only 100MB used.) Also containerd. Those are more daemons to fail, or have security holes, or just to have to know about.

Still Docker does all more or less work. And the overhead wouldn’t be such a big deal if I were using Docker for other things; installing various versions of PHP, say. And if I didn’t quite trust Pi-Hole to be well behaved Docker would be a more appealing choice. I kind of like the idea of an OS where every user process runs in something like a container. We’re not quite there yet.

I’m glad I did all this learning about containers! They’re neat! But they mostly solve a complexity problem I don’t really have in my little world. I still get by OK hand-managing a single Linux server and making sure my stuff is all installed in separate directories as systemd services or whatever. I definitely see where Docker is a huge help though when coordinating with people or reusing stuff in a more composed way.

Ubuntu, DNS, and sudo

I’m confused about something in Ubuntu 18.10. Why does sudo require DNS to be working? And is that appropriate in the face of Ubuntu’s default network configuration?

First, the fun part. If DNS is broken on an Ubuntu host then you can’t sudo.

$ sudo bash
sudo: unable to resolve host gvl: Resource temporarily unavailable
[sudo] password for nelson:
hostname: Temporary failure in name resolution

I’ve seen discussions of this problem going back to 2006 and vaguely recall it being even older than that. It’s not clear if it’s even a bug; /etc/sudoers does have network-based restrictions. But it sure makes it hard to fix a system with a broken network if you can’t become room in the first place.

The usual advice / workaround for this problem is to add your system’s hostname to /etc/hosts. That way you can always resolve the name via the file even if networking / DNS is down. The dumb advice suggests adding it as an alias for 127.0.0.1, the smarter ones have you using the real IP address. However Ubuntu 18.10 doesn’t seem to have any way of adding that hostname for you, neither at install time nor at boot time via netplan. I’ve added this manually, is it a bad idea? I do worry it could get out of sync if I renumber my network some day.

Confounding this problem is DNS is kind of complicated on Ubuntu 18.10. My 18.10 system has an /etc/resolv.conf that lists “nameserver 127.0.0.53”. (Which is sort of equivalent to localhost, 127.0.0.1, but a different number.) systemd has grabbed this port and is providing DNS service via systemd-resolved. That’s a name service daemon that mostly just forwards requests to an upstream name server. The configuration for that is confusing because a lot of files in /etc get rewritten at boot time by Netplan, but in my case it boils down to “we get our DNS servers from DHCP”. All well and good and I think systemd-resolved may even be answering the host’s own name internally, not forwarding it to the DNS server.

The problem is I stopped systemd-resolved via systemctl (while I was experimenting with Pi-Hole DNS). Then I had no way to sudo to start it again. Oops.


DNS ad blocking, Pi-Hole

I’m fooling around with Pi-Hole, the DNS server that also blocks ads by refusing to answer DNS requests for ad servers on various black lists. It was originally designed to run on a standalone Raspberry Pi server but it runs fine on any Ubuntu box. (Beware, the install script is a bit aggressive and will reconfigure your network if you let it.) Unforunately running Pi-Hole on a hacker-friendly router is not easy.

Anyway, Pi-Hole seems to work OK for me. I’m using it as the DNS server for my Windows desktop and for the Linux box itself. The funny thing is I have enough ad blockers installed in clients on Windows (uBlock Origin, Privacy Badger) that very few ad DNS requests get through to Pi-Hole.

The real reason I’m interested in using this is for various devices that can’t easily block ads. Like my iPad; Apple added some support for ad blockers but it’s not very good. Or my Roku, or my PS4, or... I like the idea my whole home network is a black hole for advertising.

The huge drawback here is that DNS is really the wrong place to be injecting policy like this in a network. DNS should be a simple caching service that does its one thing very directly. I’ve never been a fan of policy DNS systems like OpenDNS because they add so much complication. I’m looking with dread at the first thing in my house that doesn’t work in a confusing way because it can’t connect to something that Pi-Hole thinks is an ad server. I’ll never figure it out.

The other drawback is redundancy; what happens if my Pi-Hole server goes down? You can configure secondary DNS for most operating systems as a backup (including via DHCP) but it turns out most systems treat that second server as an alternative server, not just a backup, so it’ll get half the requests. I guess I could run two Pi-Hole servers? Lol, no.

Pi-Hole as a software package also feels a bit like overkill. At it’s core is pihole-FTL, a daemon based on dnsmasq plus extra code. dnsmasq is fine but that extra code implements a bunch of weird stuff. Maintaining the blocklists, OK. Logging every DNS query to a world readable file? Not a great idea (albeit configurable). There’s also a fancy web interface implemented in PHP which is nice, but more surface area. It also listens on localhost:4711 for its own API. It’s just doing a lot of things on top of being a DNS server. I think it’s reasonable, but it is a lot.

(To be fair, Pi-Hole is very well documented. Also the default install seems to be smart, like running as its own user, etc. Whoever built this distribution made an effort to do a good job. It also seems to autoupdate its own binaries, which sure offers an exciting new attack vector to my Linux box.)

One limitation of Pi-Hole is it only works if you can configure the DNS servers of your device. A lot of Internet-of-Crap devices apparently just hardcode a DNS server; see Paul Vixie’s recent rant against Google Chromecast. One solution is to capture and redirect DNS requests back inside. Yes, you can act like your own hostile wifi network! I’m anxious about the complexity this introduces.

I imagine this is only going to get worse with DNS-over-TLS or DNS-over-HTTPS. The Pi-Hole can make its own upstream DNS requests via Cloudflare’s DNS-over-HTTPS, but I’m not sure there’s a way to have the Pi-Hole work as a secured DNS server itself. Not an issue now, there are precious few secure DNS clients, but maybe in a year or so.

Another drawback of Pi-Hole is there’s no good way to temporarily disable it. I mean you can via the admin interface, but it disables ad blocking for everyone. Also it requires a separate web page. I like the way uBlock has a simple UI in the browser for me to temporarily turn it off.

Plan 9 rides again; WSL file access

There’s a handy new feature planned for WSL in Windows 10 v1903: “Accessing Linux files from Windows”. Previously there was no way to get to your WSL Linux files from Windows, the host Windows OS didn’t know how to interact safely with the LXFS files in the WSL system. Now you’ll be able to mount the Linux files as a network share.

The cool part is how it works: “a 9P protocol file server facilitates file related requests, with Windows acting as the client”. Before they edited the announcement they called this “a Plan 9 file server”, which is accurate if a bit overstated. 9P (aka Styx) is a Plan 9 network filesystem technology.

It makes sense to use a network filesystem to bridge Windows and Linux. I’ve been doing something similar, network-mounting the Linux files via SFTP. You could also imagine running a Samba server inside WSL that the host Windows system accesses. Either way the Linux process gets to mediate the file access, at the expense of a network file system.

Plan 9 is the wacky part. There’s been a little discussion about why, hopefully Microsoft will write a blog post explaining the tech. My guess is they chose 9P because it is very simple to implement. IIRC part of the Plan 9 design is that many applications implement a filesystem as their API, so they built a simple embeddable filesystem any program could control. Wikipedia’s summary of the protocol certainly looks straightforward, roughly what a FUSE filesystem implementation has to implement. Still, a tiny bit surprised they didn’t go with their own SMB, or NFS, or something new and proprietary and super simple.

There’s obscure precedent for using Plan 9 this way, see this discussion. QEMU’s VirtFS uses 9P to share files between guest and host operating systems. (Which led to at least one security issue in a QEMU user.) And there’s some 9P code knocking around: the old u9fs code presumably hasn’t entirely rotted, there’s v9fs (looks abandoned?), someone took a crack at 9P in GoLang, and there’s probably useful 9P code in this Plan 9 port. Also Wikipedia mentions Styx on a Brick which looks like a way to control a Lego Mindstorms robot via something that looks like a filesystem.

Update: Chromium OS also contains a 9p server, I think also used to bridge over VM boundaries.

Bad ethernet cable

Just had a real life experience of a bad ethernet cable hurting my network. My Linux server (or rather, the 4 port switch it is connected to) sometimes gets gigabit ethernet, sometimes 100 MBit. I couldn’t figure out why, but today I was frustrated it was stuck at 100 MBit so I found the actual cable in the patch panel and replaced it. Boom, gigabit ethernet.

I’ve got fairly elaborate-but-janky ethernet wiring in my house. Some 20 cables in the walls punched down into a cheap Leviton patch panel. Then short patch cables from the panel to the switch. In retrospect the patch panel is probably overkill; I’m never gonna repatch it. And it adds two more connectors, some circuit board traces, and a patch cable to every cable run. Still it mostly seems to do gigabit ethernet fine, just wish we hadn’t used cheap patch cables. They don’t have any rating printed on the jacket at all, just some numbers that boil down to basic Underwriter Lab type building codes. They’re flat, and in my experience flat cables tend to be crap.

Time to replace all the patch cables. Happily I found some gay pride Cat6

Update: success!

ssh: Resource temporarily unavailable

I got a weird error message today:

ssh: connect to host example.com port 22: Resource temporarily unavailable

In my case I had an open ssh connection working from my Windows box running WSL to my machine at home running native Linux. Then it dropped unexpectedly. When I tried to reopen it I got this error message. The connection had a few ports forwarded, but nothing weird. It normally works fine.

A bit of Googling around finds lots of instances of this error but all happening to WSL users. Then it gets confusing. Half the messages are from people running an SSH server on WSL, the other half are an SSH client. A lot of folks with permanent problems like a bad firewall setup. I have a transient error.

I still don’t really know what the error means. I’m wondering if port forwarding is related, maybe the Windows’ listening port is stuck in a half-closed state and isn’t available to be re-bound? I also don’t know what’s causing the drops, it’s a new problem. It’s happened twice now, both times I’ve had active SSH sessions get dropped when my SSH server completely flooded its 250MBps Internet link with a parallel download. I wonder if my cable modem or router are doing some thing dumb, or if ssh is sensitive to 3s of bufferbloat delay.

Ubuntu 18.10 install notes

I’m updating my venerable home Linux server to Ubuntu 18.10. Installing on an SSD, and I figured I’d take the advantage to start over rather than bring along this Ubuntu install I’ve been coddling since 2011. Nothing like a little spring cleaning.

It’s remarkably tough to tell what all is running on a crusty old barnacle server like mine. I found the output of “ps -xaf” and looking at crontabs to be most useful. systemctl’s output is so noisy to not be very helpful. nmap is a good backstop for checking out network services.

All told it took about 2 hours to get the software environment set up more or less like I used to have it. That seems incredibly fast to me! It took 2-3 more hours to install more persnickety things and I am still apt installing various random command line tools I’m missing.

Boy SSDs are nice. The machine boots in about 6 seconds. Really 3, but then we waste 3 seconds (or more) waiting on the buggy r8169 Realtek driver for the ethernet to come up. I tried ordering a replacement Intel NIC but the one that arrived from Amazon was counterfeit.

The drive I’m replacing has run for 61289 hours, or just about 7 years. Been turned off and on 41 times. Smart has logged 0 errors for it. Not bad, li’l WD Blue!

Things I did and random notes

“curtin” is the name of the Ubuntu installer. It leaves a couple of little named turds behind in /etc/apt/, /etc/cloud, and /etc/default/grub.d.

A lot of Ubuntu wiki docs are seriously outdated, often describing things that were only relevant in 2014 in the pre-systemd days. Caveat lector.

Configuration change

Immediately run apt update; apt upgrade. No idea why this isn’t done automatically.

Add a static IP configuration in /etc/netplan, removing the old 50-cloud-init.yaml that was there. The default DHCP configuration is perfectly reasonable but I want my server to work even if DHCP is down.

Edit /etc/default/grub to add fsck.repair=yes to the kernel command line. I’m not certain but I think this is the systemd way to ensure the boot disk is really fscked at boot time. Note there’s a bug in Ubuntu where /etc/default/grub.d/50-curtin-settings.cfg overrides the setting of GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub. I swore a little and then edited the offending 50-* file. This bug may be fixed in December 2018.

Stuff I installed

python3.7 and python3.7-venv. Cosmic (18.10) defaults to 3.6.

chrony to replace the crappy systemd NTP implementation.

plexmediaserver from their Ubuntu repo. Bless their hearts, this is still buggy so many years later, but it mostly works. Ignore any weird warnings about “Conflicting distribution”.

postfix as a local machine. this means mail stays entirely local, so mostly useless, but lets cron errors get through

munin. good ol’ system monitoring. I love the inscrutable graphs.

rsnapshot for backups both local and remote. I like the idea of Duplicati but after its last install corrupted itself I’m not in a hurry to install it again.

samba. This just worked?! I borrowed bits of my config from before but that was pretty simple, just set up a couple of shares. Samba used to be such a heartache to get working, amazing.

SABnzbd for Usenet downloads. This turned out to be remarkably complicated. Ubuntu 18.10 has a recent version in the repo, but the setup script is not great.

  1. Install sabnzbdplus. Ignore the suggested packages
  2. Create a nzb user. useradd -r nzb; usermod --lock -s /usr/sbin/nologin nzb
  3. Edit /etc/default/sabnzbdplus. You have to change USER. Default port is localhost:8080, I changed that too.
  4. service sabnzbdplus start
  5. point a web browser at the instance, use the configuration wizard
  6. if you had an old config, it’s stored in ~nzb/.sabnzbd/sabnzbd.ini. Server passwords are helpfully in plaintext.

Stuff I didn’t have to do

Some things I’m used to doing on new systems, but weren’t necessary.

Install locate, the doodad that lets you do a fast find for a filename. Ubuntu 18.10 comes with mlocate already installed.

Set up unattended-upgrades for security fixes. It was already installed for me.

Set up powersaving. The default configuration is powersaving for the CPU, you can verify via cat /sys/devices/system/cpu/cpu$FIRSTCPU/cpufreq/scaling_available_governors. (To configure this see systemd ondemand or else cpufrequtils).

Change the I/O scheduler. CFQ looks to be the default now.

Monitoring EdgeOS bandwidth with Munin

Ubquiti’s routers are reliable and flexible, but they lack a certain.. consumer polish. One thing missing from the graph is any sort of historical bandwidth tracking or graphs. There’s no way to see what bandwidth you used in the last 5 minutes, much less the last year.

But EdgeOS does support SNMP. So you can collect the SNMP data on a Munin node running on another computer and graph it.

Step 1: turn on SNMP following something like these instructions. I did this via the router GUI instead using the Config Tree wizard. The two settings that are important are

snmp {
     community public {
         authorization ro
     }
     listen-address 192.168.0.1 {
         port 161
     }
}

Note there’s no real security in this kind of SNMP, anyone with access to that listen-address will be able to read a bunch of state off your router.

I was able to test SNMP was working with snmpwalk but I forget exactly what command worked. SNMP is a mystery to me.

Step 2: configure your Munin node to read the SNMP data. I used this guide. It basically has you use munin-node-configure to detect what SNMP data is available and then symlink a bunch of plugins. Then you add a “virtual node” for the router to your munin.conf.

The resulting config is overkill; I’m not sure I need to measure my router’s disk usage, thank you. Also there’s like 8 graphs for the network and I haven’t quite figured out which opaquely numbered interface is the WAN I care about monitoring. I figure after a day’s data is collected it’ll be clear what’s useful to keep.

Update: here’s what I kept

snmp_192.168.0.1_cpuload
snmp_192.168.0.1_if_2
snmp_192.168.0.1_load
snmp_192.168.0.1_netstat
snmp_192.168.0.1_uptime

The graph shows a big upload I did out of my network maxing out at ~10Mbps. Incoming bandwidth maxes out at 250Mbps so if I ever saturate that the scale on this graph is going to go to hell.

EXIF in Python

I’m working on using my Flickr export. I naively thought that working with EXIF metadata from images in Python would be easy in 2019. I was wrong. Particularly if you want to write EXIF data. I’m tentatively trying PyExifTool, a wrapper for a Perl command line program. More on that below.

PyPI has 126 packages for EXIF. But a closer look shows a lot of them are bad in various ways and there’s no one consensus package. Lots of version 0.1s, stuff that was abandoned 4 years ago, etc. PIL/Pillow has EXIF support but it’s very low level and a clunky API. Piexif looks somewhat promising as a pure Python thing but also very clunky API.

Turns out the real problem is EXIF is a mess. When we say EXIF we actually mean three separate metadata formats: EXIF itself, the older IPTC tags, and the more modern inlineed XMP tags. Some of these formats have overlapping metadata in them. EXIF itself is a real mess of a binary format. For instance the GPS location info looks more like raw data from a GPS chip than a simple WGS location. For instance it supports multiple formats for lat/lon. Want decimals? minutes? seconds? Some mix? You can write anything!

The gold standard for good EXIF+others support is ExifTool, a 15 year old Perl library / command line program. It has an active community of developers who’ve spent a long time fiddling with all the weirdness in image metadata formats and making a bulletproof tool that can read and write them. So why try to rewrite all that code in Python?

Enter smarnach’s pyexiftool and the several separately packaged versions of it on PyPI. It’s four years old and as far as I can tell there is no active fork. Fortunately the code is pretty simple.

The main thing it does is fork a single exiftool process with the -stay_open flag. That causes the Perl program to keep reading commands. The rest of the Python code is a little wrapper around the JSON api and some convenience code if all you want is to read metadata. It seems to work.

So there we go; I’m gonna be writing EXIF tags by passing command line arguments over a file descriptor to a running Perl program. It’s a kludge, but if it works I’ll take it.

mintty/wsltty: Ctrl+Shift+Letter

TIL; mintty, the venerable Cygwin terminal emulator, has an option so you can use Ctrl-Shift-C to copy and Ctrl-Shift-V to paste. mintty has been around forever and has a second life as wsltty, a very specifically adapted to easily launch Microsoft’s WSL environment. No cygwin required.

To enable it, right click a mintty window, go to keys, and tick on the box “Ctrl+Shift+letter shortcuts”. The full list of shortcuts is in the mintty man page.

– Ctrl+Shift+A: Select all
– Ctrl+Shift+C: Copy
– Ctrl+Shift+V: Paste
– Ctrl+Shift+N: New
– Ctrl+Shift+H: Search scrollback buffer
– Ctrl+Shift+W: Close
– Ctrl+Shift+R: Reset
– Ctrl+Shift+D: Default terminal size (rows/columns)
– Ctrl+Shift+F: Full screen (not zooming font despite Shift)
– Ctrl+Shift+S: Flip screen
– Ctrl+Shift+O: Toggle scrollbar
– Ctrl+Shift+P: Cycle pointer styles
– Ctrl+Shift+T: Cycle or tune transparency levels

Some of those are insane (“close window”?!), but the copy/paste shortcuts are lifesavers.

(I finally figured this out after finally mustering the encourage to install Windows 1809, which includes Ctrl-Shift-C for stock WSL consoles. A whole OS update for a keybinding! Then I realized I don’t use stock WSL consoles anyway. oops.

Update: while I’m here, mintty has a nifty feature I’d never heard of before.

Flip screen
Applications such as editors and file viewers normally use a terminal feature called the alternate screen, which is a second screen buffer without scrollback. When they exit, they switch back to the primary screen to restore the command line as it was before invoking the application.

The Flip Screen menu command and Alt+F12 shortcut allow looking at the primary screen while the alternate screen is active, and vice versa. For example, this allows to refer to past commands while editing a file.

30 years of using ttys as my user interface and I’d never heard of this. You know how you run less or emacs or whatever and lose whatever was on the screen to the fullscreen program? Alt-F12 shows what’s hidden. Amazing!

The virtual tabs feature is neat too. The mintty authors don’t want to add a full tab UI, but they do have a quick session switcher built in via Mouse Button 5, Ctrl-Shift-I, or the menu.

It also supports SIXEL graphics. Sadly, no Tektronix 4014.

Kernel module blacklist

Ran across a fun part of my Ubuntu system today, /etc/modprobe.d/blacklist*. It comes from the kmod package and contains a list of kernel modules which are included in the Linux sources, were compiled and shipped with Ubuntu, but nevertheless are being banned because someone made the choice they didn’t like the module. It’s kind of hilarious.

I can’t find a web-linkable version of the default Ubuntu files, but here are some gems from them. I suspect each entry here is a series of hard-earned lessons.

# causes no end of confusion by creating unexpected network interfaces
blacklist eth1394

# ugly and loud noise, getting on everyone's nerves; this should be done by a
# nice pulseaudio bing (Ubuntu: #77010)
blacklist pcspkr

# Framebuffer drivers are generally buggy and poorly-supported, and cause
# suspend failures, kernel panics and general mayhem.  For this reason we
# never load them automatically.

# Many less commonly used network protocols have recently had various
# security flaws discovered. In an effort to reduce the scope of future
# vulnerability exploitations, they are being blacklisted here so that
# unprivileged users cannot use them by default. System owners can still
# either modify this file, or specifically modprobe any needed protocols.

I was looking for this because I’m reinstalling Linux on my server and there’s still some drama about the r8169 driver, with some suggestions to lacklist it and build a vendor driver from source.

In the grand old days I used to build my own Linux kernels. But I always statically linked them, no loadable drivers, no init ramdisks. One kernel carefully sculpted to work on my one particular computer. It’s kind of a dumb way to make a system work.

SF Internet upgrade to 250/10

I’ve been using Wave (formerly Astound) as my ISP in San Francisco since June 2014. When I first got their 100 Mbps / 5Mbps cable modem it seemed so fast I could see through time. But network tech keeps improving, at least in urban areas. Sonic now offers $50/mo gigabit fiber and both Astound and Comcast have tried to match with upgraded cable modem speeds.

I’d prefer to switch back to Sonic but it requires running a new wire, which is a bit complicated for me. OTOH I could simply fill out a form with Wave, agree to pay an extra $10, and poof: I get 250 / 10 speeds. Which I did today, and it seems to work fine.

The real surprise here is I’m getting 250 all the way to my desktop. I’d been putting this upgrade off because I thought my home network wiring limited me to 100 Base T, so anything over 100 Mbps wasn’t so exciting. I guess the wiring in the house (particularly the patch panel) is better than I feared. (I’d planned ahead with the cable modem, an Arris 6141 which maxes out about 343 Mbps.

250/10 is hugely asymmetric, I wish they wouldn’t do that. I read somewhere that 19:1 was the maximum reasonable asymmetry, more than that and there wasn’t enough upstream bandwidth for ACKs to to clock the download. No idea if that’s really true and I bet that varies depending on window sizes, etc.

As always when I first got the speed boost it didn’t seem to work because I forgot I’d configured my router to do traffic shaping. I’m using an EdgeRouter X and their “smart queue”. It does an excellent job managing bufferbloat, but you do have to configure your max bandwidth correctly! Once I’d done that I was still only getting 190 Mbps down. Turns out that’s a limitation of the EdgeRouter X; once you enable QoS the CPU has to touch every packet and unfortunately it’s just not fast enough to keep up. One solution would be to upgrade the router, maybe an ER-4. What I’m doing now is only doing smart queueing on the 10 Mbps upload. Realistically that’s probably enough; saturating 250Mbps is hard.

I did get a nice practical demo with this game update. 30 MBytes/second, I remember when that was as fast as a hard drive could go! Unfortunately this nirvana only lasted about a minute until EA’s horrible servers crapped out and/or throttled me, real throughput over the whole download is more like 2MB/sec. Speed tests show I’m still getting 250 from my ISP.

Let’s Encrypt refresh

Back in 2016 I did a half-hearted attempt to enable SSL on my web servers, by using Let’s Encrypt. At that point all the scripts were relatively new, I think I used certbot 0.27. The little project is all grown up now and is already deprecating a protocol I relied on (ACME TLS-SNI-01). They were nice enough to send out a warning email about it, although dumbly the sent the “Action Required” email before the site’s docs have been written.

I read enough docs to realize that changing protocols basically means getting a new certificate. Also realized I needed to upgrade certbot, or at least really should, so basically I started over. Here’s what I did

  1. Removed the old certbot. Bits of it were in $HOME/ssl, $HOME/.local/share, /etc/letsencrypt, /var/log, and root’s crontab. Kind of a mess.
  2. Follow the Ubuntu instructions to follow a PPA for the new certbot
  3. apt-get install python-certbot-apache
  4. apt-get install python3-pyasn1
  5. Run certbot --apache and trust its configuration
  6. Test with ssllabs

Really all was super simple, hats off to EFF and Let’s Encrypt for building such a turnkey tool. The only wrinkle in my config is that all my server’s domains share a single SSL certificate with a bunch of different domain names on it. It’d be cleaner to have those separate, I imagine there’s some way I can do that.

I haven’t tested that all my sites work right under SSL. Both Windhistory and Logs of Lag are complaining about mixed SSL/nonSSL content. Meh.

noUiSlider, a nice Javascript control

Just wanted to give a shout out to noUiSlider, a nice Javascript library for building slider controls. We just used it to add a time-range slider control to Wanderings, my little location tracker. Now you can restrict what data is shown to specific date ranges. Our control looks a lot like this demo.

There’s a zillion slider controls implemented in Javascript. Most of the well known ones are 5+ years old and require jQuery. There’s some fancy new ones that require React. What I like about noUiSlider is it’s standalone, doesn’t rely on any other frameworks. It’s not tiny but it’s pretty small, about 90k uncompressed or 25k gzipped.

noUiSlider is also remarkably professional. It’s quite flexible; you can have any number of handles, linked or not. It’s straightforward to restyle. It gives off a nice collection of events when the user interacts with it. It works thoughtfully on touchscreens. And it’s all well documented! Nice library.

The one thing I haven’t figured out how to do in my app is add a nice UI for “filter to one month” for “one year”. It’d be easy enough to add buttons but the UI would be so cluttered then. Want something less obtrusive. For now we have a bunch of hotkeys defined on the main window (YQMWD for ranges, also HL to pan back and forth) but that’s pretty mysterious.

Edit WSL Linux files from Windows with SFTP

I just hit on a way to edit files in WSL that in retrospect seems really obvious. I’m wondering if there’s some reason it’s a bad idea. It seems to work!

The problem I’m trying to solve is editing files in the Linux partition of WSL from Windows. Ie: editing $HOME/.bashrc with Notepad. We’re told to absolutely never change the Linux filesystem files from Windows because things can break.

So my solution is to run the sshd daemon under WSL. Then use that to connect to my Linux files via SFTP running as a Windows app. I’m using SFTP Net Drive to mount my Linux files as a Windows drive, there are other options. Then use any Windows program to edit the files in that drive, like Notepad or Sublime Text.

All the actual file I/O is happening under WSL thanks to SFTP, so it should be safe. SFTP imposes some overhead but it’s not a big deal for just editing files. One nice thing is SFTP seems to do a pretty good job at preserving Unix file permissions even when editing from Windows.

Update: I’m now doing this regularly, all the time, with the Linux partition mounted as W: in Windows. It’s great! Makes a big difference having easy access to the files over there.

Update 2: this trick works but is no longer necessary. WSL in Windows v1903 includes support for accessing your WSL files via Windows paths like \\wsl$\Ubuntu-18.04\home\nelson. Underneath the scenes it’s using a Plan 9 network filesystem to bridge things.

(originally posted to Reddit)

New release of Wanderings, in which I learn to love Webpack

Brad and I pushed our first new release of Wanderings since the big release last January. No user visible changes, but we upgraded all the versions of third party packages and build tools we were using.

The real thing is I had to get over being whiny about webpack and npm. Right after we finished 1.0 Brad stepped in and reorganized our code to use fancy web tools. Previously we just had a big ol’ wanderings.js file we imported on every page, along with a bunch of third party minimized redistributables included one after the other in the HTML file. You know, the old school way. Brad redid everything nicely in webpack and npm so that third party modules were fetched from a repository and bundled together. Our code was refactored and then combined into the bundle. All with nice frontend scripts like “test” and “deploy” and “start development server”.

Unfortunately I don’t know anything about these fancy new fangled tools, I live or die by press-F5-in-the-browser. And it was kind of a big hump for me to get over it, learn the tools, and use them. I have a categorical problem any time someone tries to inject a “compile” or “link” phase into what should be simple interpreted code. It always slows me down. npm is very hard to love, too.

But webpack solves a lot of problems too. Managing distributing the right versions of things. Bundling them so they distribute efficiently. Minimizing the code for obfuscation + network savings. Keeping it possible to still run devel versions with source maps, etc for easy debugging.

The fancy devel server we get from webpack is pretty nice too. It seems to automagically arrange for things to recompile and reload when they change. I had a problem with this at first because our devel bundle is like 4.5 megabytes and I was running my devel server remotely, on another continent. That’s a bad idea; once I got the devel server running locally on my laptop it was much better. (We might want to split our bundle into two pieces though, a big one of third party code that seldom changes and a small one of our own code. Just to keep reload overhead down).

I’m still grumpy about some things. I’ve lost all my global variables I used to reach into to inspect the state of the running system in the console. I’m not sure I can get the Firefox debugger working at all, the source maps or something aren’t working. Chrome seems better though.

I still hate imposing any overhead in the “change code, reload, run” loop. But all this build stuff solves real problems in the Javascript ecosystem so I think it’s best to play along.