Some Bits: Nelson's log

103 posts in 2016

Progressive web sites and service workers

Awake early I read this interesting blog post about making a very fast modern website. Lots of good stuff in there, like React alternatives that are lighter weight, avoiding polyfill overhead for modern browsers, the value of server side rendering, etc. Also two things that were entirely new to me: “Progressive web apps” and “Service Workers”. Also new-to-me: Google’s web fundamentals instructional material.

Progressive web app is the buzzword for a web page that works like a little application. Like Gmail in the days of yore, or Google Docs, or any modern / complex site like Twitter or Facebook or whatever. Or my own single page apps like WindHistory and LogsOfLag. Web apps are nothing new, but the “progressive” is meant to suggest a site that works fast even on mobile devices with slow and unreliable networking. Key ideas are rendering quickly and handling unreliable networks intelligently. They also have a neat tool called Lighthouse that audits a web app for progressiveness. A lot of what it checks for is mom-and-apple-pie, deferring script loads etc.

But Service Workers are the key magic. They are “a programmable network proxy, allowing you to control how network requests from your page are handled”. Basically it’s a background Javascript thread running asynchronously doing all the network for your web app. The web app page installs a service worker once the first time the site is loaded. Then it lives in the background doing things for your app like loading resources, receiving push notifications, synchronizing data to the server, etc. It communicates asynchronously via messages to the Javascript in the browser page.

It sounds pretty powerful. Basically it gives the developer control over the browser’s network, how stuff is cached and when it is loaded, etc. It also sounds pretty complicated, and I imagine 95% of developers won’t code to this API themselves and instead use a framework that takes advantage of it to optimize performance.

The big problem is service workers aren’t fully supported: on desktop Chrome and Firefox support it, but not MSIE/Edge nor Apple Safari. Mobile support is not good either. And this feature is so complex I don’t think you can polyfill support in, certainly not in a meaningfully performant way. I don’t have enough perspective to see whether service workers have momentum. Chrome has supported it for two years, which in a way is a bad sign that it’s been that long and there’s no clear consensus for implementing it everywhere. OTOH it solves a real problem and Apple and Microsoft are certainly not known for leading the way in web development.

 

Bonus links from reading that blog post. The fetch API is a modern alternative to XMLHttpRequest, etc which is nicer to use. Polyfills exist. And speaking of polyfills, polyfill.io is a nice CDN service that delivers optimized polyfills to browsers based on their User-Agent. Finally freegeoip.net does free geolocation of IP addresses and powers a polyfill for the HTML5 location API. It runs as a free service with usage limits, or you can download the IP database and code and run your own.

Ubuntu 16 NTP notes

I love NTP. What’s it look like in Ubuntu 16? ntpd is pretty much the same, but some change or things I’ve never noticed before.

Debug mode 7 queries are now entirely disabled. The ntpdc program basically doesn’t work; you use ntpq instead. Given the number of times this protocol has been used in a UDP amplification DDOS, it’s a necessary change.

ntpd is started with the -g flag. This flag allows NTP to set the system clock once no matter how far out of sync it is. The default behavior is to never move the clock more than 1000s as a sort of sanity check. In practice it’s usually the client that’s insane, not the server.

servers are now configured like this

pool 0.ubuntu.pool.ntp.org iburst

“iburst” means the ntpd will try 8 times in 16 seconds to reach an unreachable server. The “pool” directive is not in the man pages, but these docs explain it. It tells ntpd to use DNS differently, to look up random new IP addresses every time. I’m not positive but I think ntpd still isn’t smart enough to look up a new pool IP address every few days or when a server goes offline. But at least it’ll get different IP addresses for the same hostname.

In addition to ntpdate/ntpd, Ubuntu also now provides timedatectl and systemd-timesyncd, part of the systemd hydra. It’s not very well documented; see Arch’s docs and this announcement. It’s a lightweight client-only time synchronizer. That seems like a good idea for security / client footprint. But it may be a bit too lightweight. It sounds like it only gets time from one server, for instance, and I wonder if they’re doing the PLL clock syncing that makes ntpd so good. systemd’s stuff gets out of the way if you are running ntpd.

Verizon tethering experiment

I need a backup for Internet in Grass Valley for when my WISP goes down. (Which is frequently, every Sunday morning lately.) Verizon now enables tethering on iPhones at no extra charge, just data used, part of the new simpler service plans. So I tried it briefly.

Quick result is it’s not bad. I have two dots of signal on my iPhone. I get 4Mbps down, 130kbps up on a DSLReports speed test. Latency to somebits.com was 130ms average, compare 90ms on my WISP link. But the jitter was terrible, some 400ms+ pings. At $5-$10/GB I’m not going to want to use this regularly, but it’s fine as a backup.

One oddity. My tethered network connection is genuinely IPv6, and my Mac automatically uses it. Yay! The downside is the first time I tried this I could only connect to IPv6 sites; v4 only sites like my own blog wouldn’t work. I originally tested this by configuring my ethernet to “off” in the Mac network preferences, and maybe somehow it retained the IPv4 route through the wire? Explicitly unplugging the wire worked fine.

I’ve been considering getting a mobile hotspot; Wirecutter recommends Verizon’s Jetpack AC791L for $200 (or $50 with a two year contract). It looks pretty reasonable if I want a dedicated device and not just use my phone. Main reason I see to do that is for travel, so I can keep my US SIM card in the phone. Verizon’s plan seems to allow extra devices on my account for $10 / device and I can turn it off and on. Or just buy the Verizon device with the contract.

                                                        Packets               Pings
 Host                                                  Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. 172.20.10.1                                         0.0%   158    2.7  18.9   1.8 303.4  43.4
 2. 69.sub-66-174-31.myvzw.com                          0.0%   157   37.5  77.4  28.2 319.4  70.9
 3. 20.sub-69-83-164.myvzw.com                          0.6%   157   41.1  81.8  26.2 400.8  75.2
 4. 170.sub-69-83-164.myvzw.com                         4.5%   157   36.7  81.5  25.2 323.5  78.8
 5. 2.sub-69-83-164.myvzw.com                           5.7%   157   35.1  77.9  30.4 382.5  71.4
 6. 12.sub-69-83-163.myvzw.com                          8.3%   157   41.4  72.9  30.1 455.9  69.5
 7. 33.sub-66-174-29.myvzw.com                          2.5%   157   42.1  83.5  29.6 380.4  81.1
 8. et-2-0-0.GW11.SAC1.ALTER.NET                        8.9%   157   28.1  71.8  28.1 349.4  65.8
 9. ???
10. 0.ae1.BR3.SJC7.ALTER.NET                            3.8%   157   46.5  94.3  35.6 394.6  71.2
11. 204.255.168.26                                      8.3%   157   56.1  80.3  32.7 289.6  61.7
12. 100ge12-2.core1.den1.he.net                        10.8%   157   76.8 120.1  76.8 509.8  60.7
13. 100ge14-1.core1.mci3.he.net                        21.7%   157   99.9 124.2  86.2 310.3  45.4
14. 10ge4-1.core1.mci2.he.net                          49.7%   157   93.1 120.8  84.0 454.4  58.9
15. wholesale-internet-inc.10gigabitethernet1-3.core1. 38.9%   157  105.2 125.4  79.4 336.2  61.4
16. lag-to-oak.edge-b.clay1.mci.us.as32097.net         39.7%   157   94.2 130.1  77.5 377.2  64.2
    lag-to-oak.edge-a.clay1.mci.us.as32097.net
17. lag-core-a.dist-1-3.clay1.mci.us.as32097.net       34.4%   157  101.9 122.1  82.0 333.8  54.4
    lag-core-b.dist-1-3.clay1.mci.us.as32097.net
18. wk.somebits.com                                     0.6%   157   97.5 135.5  77.6 436.9  72.9

127 packets transmitted, 127 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 79.470/131.121/471.344/69.791 ms

Ubuntu 14.04 to 16.04 notes

I had a moment of foolish optimism and decided to upgrade my development machine from Ubuntu 14 (Trusty) to Ubuntu 16 (Xenial). “Just run do-release-upgrade”, the motd has been encouraging me for months now. So I did.

And it failed. And then I tried to fix it by hand and I thought I did. And then the machine didn’t reboot. So that’s discouraging. But then the second time I tried to reboot (after hauling the machine over to a monitor) it rebooted fine. And now the machine is fine. No idea what that was about, but yay for Ubuntu robustness! My reboot problem may have nothing to do with Ubuntu, but rather be a problem with my ethernet. Anyway, some notes.

On the upgrade scripts

  • do-release-upgrade runs in a screen session. Some of the upgrades prompt you to compare changes in config files, and will helpfully propose spawning a shell to let you inspect the situation. But your tty is occupied in some weird way with screen and/or scripts running in the background. I was getting all sorts of random crap on my screen and I panicked and aborted the upgrade script. Do not make this mistake.
  • You can’t run do-release-upgrade a second time. The system thinks it was already upgraded and it aborts.
  • Fortunately mostly do-release-upgrade does stuff up front, then relies on apt and dpkg to do the real work. Those tools are robust. I’m not really clear on what all do-release-upgrade does, but here’s a reference. I sure hope there wasn’t anything crucial that didn’t happen because I aborted.
  • I fixed things by running dpkg-configure by hand, then running apt-get upgrade a bunch of times. apt-get dist-upgrade is probably not a bad idea either.
  • I also improved things by removing a bunch of PPAs from /etc/apt/sources.list.d.
  • There are some install logs in /var/log/dist-upgrade, including a full screen recording.

On changes in Ubuntu 16

  • Welcome to systemd! Everything about how the machine boots is different. I mostly noticed this with warning messages printed at boot time about funky scripts in /etc/rc that weren’t up to snuff. These came from me or PPAs, not the core code.
  • “systemctl” seems like an important new command to learn. Useful commands: enable/disable, start/stop, status. Also “journalctl” to see systemd’s logs.
  • some init scripts were broken / old / weird. I have a bunch of old cruft! I fixed these by purging the packages and reinstalling them. Culprits included screen and mongodb.
  • My 2012 lm-sensors install included some kernel modules that no longer exist. Fixed by re-running detect-sensors and removing the old entries from /etc/modules
  • I’m getting an error about mount options in dmesg that I can’t understand. It doesn’t seem to be hurting anything though, so ignoring it.
  • grep thinks my syslog is a binary file, it has some nulls in it (which is terrifying!). So i have to use “grep -a” to see the whole thing.

On user programs

  • I run Crashplan which makes extensive use of inotify. The default Linux settings only allow 8192 files/directories to be watched, not enough. Here’s how to update the limit.
  • I had to manually install python3-venv with apt. Then my existing venv directories were broken and I had to rebuild them.
  • My plex server was broken. Difficulty level: systemd. I finally traced the problem down with help from here; “systemctl status” told me it was having a problem with the group. Turns out the server wants to run as group plex, not just user plex, but no one had set up a group plex. BTW hooray! The Plex team finally has an official apt repository
  • I somehow ended up with Postgres 9.1, 9.3, and 9.5 all on my system. With 9.3 and 9.5 daemons fully running. I don’t have any permanent data on the development machine so I went with a full wipe and reinstall of all Postgres. The stock Ubuntu 16 versions of GDAL and PostGIS seem to work nicely.

Testing Amazon S3 CORS headers

Resources served from AWS S3 can have CORS headers set, useful for JSON data intended for inclusion. But testing it from the command line is not simple.

Plain old “curl” doesn’t work because it doesn’t show headers. “curl --verbose” works, but even if CORS is configured on S3 you won’t get CORS headers. You have to set an Origin: header in the HTTP request to induce Amazon to set a CORS header in the response.

curl -H 'Origin: http://example.com' --verbose http://s3.amazonaws.com/data.openaddresses.io/machine-stats.json > /dev/null

Also doesn’t work: “curl -I”. That’s supposed to be curl’s “print headers” option but it also switches to doing a HEAD, not a GET, and S3 doesn’t set the CORS headers for HEAD requests.

 

Global surface water map

Nathaniel Kelso tweeted about an interesting new map of global surface water, derived from classifying Landsat images. Here’s an article, another article, and the paywalled Nature paper.

Best of all, here’s the data! Very nicely prepared for use. I tossed some of the California occurrence GeoTIFFs into QGIS for a quick plot. This view is centered on Engelbright Dam with Sacramento to the west, where the American and Feather rivers meet. Blue is year-round water; pink is intermittent (and seems to highlight farmland.)

Screen Shot 2016-12-09 at 9.19.03 AM.png

At a scale of 30m per pixel this dataset doesn’t show small rivers or creeks. But what this map does show is the history of water over 30 years of Landsat imagery. In addition to the basic occurrence map there are also several data layers highlighting changes in the surface water. One showing before and after Jan 1 2000, one showing seasonality, one showing yearly recurrence, and some other more technical measures.

It’s a solid piece of work and nicely packaged. And all free!

Python Pyramid framework

Interesting conversation on Reddit about scalable webapp frameworks. Lots of endorsements for Pyramids, the successor to the old Pylons project. After a brief review it looks like it’s similar to Flask. The Reddit discussion says it scales better, that it’s thread safe and there’s a hope of running it async.

I like what Pyramids says about philosophy:

Megaframeworks make decisions for you. But if you don’t fit their viewpoint, you end up fighting their decisions. Microframeworks force no decisions, making it easy to start. But as your application grows, you’re on your own.

In both cases, the focus is on the start: either too much or too little. Either way, finishing and staying finished is hard. You need a finishing-focused framework with an architectural design that scales down to getting started, then up as your application grows.

It seems to mostly be focussed on URL dispatch, with a structure for web views and sessions. And support for logging and testing! Also has some connectivity to various template libraries in Python. No database code at all, but there’s extensive docs on using SQLAlchemy. Also the note “Pyramid has a strong orientation towards support for transactions”.

small Wikipedia text for inlining

Reddit Enhancement Sweet has a neat feature where if someone links to a Wikipedia article you can click on an expando button and a div pops up showing just a small bit of the Wikipedia article right on top of the page, a sort of quick preview. Here’s the code for it.

It works by using the Wikipedia API, specifically the “parse” method. (So named because it parses Wikimedia source data and returns JSON, the article contents). This URL is a sample query for the JSON contents of the Round-robin DNS page. There’s a zillion options for configuring what it returns, section=0 seems like a useful one to only get the first section of an article, typically the summary. And here’s how to get only the first paragraph.

The Wikipedia API has a sandbox for designing queries.

BTW I’m having a hard time with Chrome Developer Tools lately. I can’t find that Reddit page + RES loading this JSON anywhere. Maybe because it’s happening in a Chrome extension, out of site in a background page or something? Dunno.

Weird cable modem routing

Here’s a strange mtr report:

                                       Packets               Pings
 Host                                Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. router.nelson.monkey.org          0.0%   234    0.3   0.3   0.2   0.6   0.0
 2. 10.21.156.1                       0.4%   234   21.9  15.9   9.6  42.3   4.1
    104.220.254.153
 3. 10.21.156.1                       0.9%   234   24.4  16.5   9.6  71.3   5.6
    104.220.254.153
 4. 104.220.254.153                   0.0%   234   14.7  16.1  10.2  33.0   4.1
    cr1-200p-a-be-100.bb.spectrumnet.us
 5. cr1-200p-a-be-100.bb.spectrumnet  0.0%   234   23.3  17.2   9.8  42.5   4.6
    cr1-9greatoaks-te-0-5-0-13.bb.spectrumnet.us
 6. cr1-9greatoaks-te-0-5-0-13.bb.sp  0.0%   234   23.5  17.7  10.7  57.0   5.7
    72.14.204.109
 7. 72.14.204.109                     0.0%   234   13.9  17.6  10.5  37.9   4.4
    108.170.242.241
 8. 108.170.242.241                   0.0%   234   17.1  17.6   7.8  44.2   4.3
    216.239.49.83
 9. 216.239.49.83                     0.0%   234   15.0  17.2  11.4  36.6   4.5
    google-public-dns-a.google.com
10. google-public-dns-a.google.com    0.0%   233   12.5  17.3  11.1  47.6   4.8

It’s hard to read that at first, but what’s going on is the path is changing at hop 2. Sometimes my packets go directly to 104.220.254.153, sometimes they go through 10.21.156.1 first. And the packets take 4 or 5 hops before they get out of the local ISP and in to spectrumnet.us, suggesting sometimes they visit those other two addresses more than once. (I wish traceroute would break this out for me, show which fraction of packets take which route.)

That’s a capture from home in San Francisco, my ISP is Wave Broadband (aka Astound). They provide good clean 100Mbps without any of Comcast’s bullshit and have mostly been reliable. I had some problems yesterday (massive packet loss, lag) which got me looking. The problems went away when I rebooted my cable modem (which itself is WTF), but this weird routing remains.

I can’t tell if that reported 0.9% packet loss is real, or an artifact of mtr’s TTL trickery or reporting. A straight up ping to 8.8.8.8 showed 0 loss in 1500 packets, so it may not be real.

I have some vague theory that what’s going on is there’s local congestion and if stuff gets buffered, 10.21.156.1 becomes visible. But I have very little evidence for that.

League of Legends rank distribution over time

Just finished a small longitudinal data project. Not real happy with how it turned out, but figured I should document it anyway. Frustrated it doesn’t look better, also that it didn’t get more attention.

Here’s the deliverable: a Reddit post. It’s a visualization of rank inflation in League of Legends over the course of the last year, Season 6. I collected the data by hand out of curiosity. The resulting visualization more or less confirms what people who pay attention already knew; there is inflation. Only 15 upvotes which is crappy engagement for something I spent several hours on.

7mmsnc2

I tinkered with the visualization for awhile. The colors are meaningful, they represent Bronze / Silver / Gold / Platinum to folks who play the game. (There’s also White for Diamond+). There’s 5 divisions within each tier, that’s the black lines. And then some ugly caption text because I wanted to condense the whole thing down to a single shareable image.

I produced it using iPython, Pandas, and matplotlib. I really like Pandas’ abstraction of a DataFrame, it’s a very powerful tool for working for a matrix of numbers. Even so I have a lot of data massaging code to get from my original spreadsheet to a clean list of numbers. Deleting extra rows, transposing rows/columns, converting “93%” to 0.93, etc etc.

I really don’t like matplotlib. I’ll paste my graph generation code below, it’s super ugly. There’s like seven ways to set options. Flags passed to the Pandas plot() function, functions called on the global matplotlib object, functions called on the global pyplot object, functions called on the axis objects, two different ways to modify RC parameters, etc etc. Just a mess. Maybe this is my ignorance though and there’s a way to simplify / rationalize it all.

# Plot
plt.style.use('seaborn-whitegrid')
matplotlib.rc('axes', grid=True)
matplotlib.rc('grid', color='w')
matplotlib.rcParams['font.family'] = ['Liberation Sans']

# Filled area for the tiers
ax = tdf.plot(
    kind='area', stacked=False,
    figsize=(10, 6),
    legend=False,
    linewidth=0,
    alpha=1.0,
    color=('#ffffff', '#87fffd', '#ffdb57', '#dce2f2', '#b2a07e'))
ax.set_yticks(numpy.arange(25,100.01,25))
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%.0f%%'))

# Lines for every division
df.plot(ax = ax, legend=False, color='k', linewidth=0.5)

# Configure the chart a bit more
ax.set_axisbelow(False)
plt.title('Season 6 distribution of ranks in NA')
plt.text(0, -35, '''There is a general trend of rank inflation...''',
        linespacing=1.4, size=12)

Setting up a new Jupyter data exploration notebook

Been a month since I had to set up Jupyter for a new project. Here’s all the steps, which seems awfully complicated for a “standard setup”. Some of that is idiosyncratic to me though.

  1. newvenv
    a shell alias I have. What it does:
    python3 -m venv venv;
    source venv/bin/activate;
    pip install -U setuptools pip
  2. pip3 install jupyter
  3. pip3 install matplotlib numpy pandas seaborn requests
    these are standard visualization libraries, plus a sane HTTP client. Fortunately these install from precompiled wheel files so it’s quick
  4. jupyter notebook --no-browser >> jupyter.log 2>&1 &
    Jupyter really, really wants to be an interactive program. This sort of makes it headless.
  5. ssh -L 8888:localhost:8888 my-server.example.com
    I’ve installed and run Jupyter on a server. I run this command on my local development machine to forward the port to access it.
  6. open http://localhost:8888/ in a browser
  7. %matplotlib inline
    Be sure to run this as the first command in the notebook

 

Django + lolslackbot, a battle plan

I’m thinking again of doing some work on lolslackbot, in particular adding a web frontend to it. Tired of adding users with ugly SQL hacks, tired of having no reporting views. I experimented with using Django six months ago and even sort of still have the code but have totally forgotten how it worked. I also never came to a conclusion about the path forward. In particular whether I should add Django first, or I should port from sqlite to postgres first.

Well I’m cutting that Gordian knot based on 30 seconds advice on IRC. I should add Django first, Django + sqlite. It should all work fine, the only drawback is sqlite database level locking will suck with multiple web users. Which is fine for now. Adding Django lets me add new features to the product, which is what motivates me. I’ll port to sqlite later if I open the webapp to multiple users and need better locking. A rough plan:

  1. Get some basic read-only views of the database
  2. Related: sort out my problem with representing many-to-many relationships. I fear this might require changing my database schema to be compatible with Django’s way of doing things.
  3. Focus on the social tables: People, Groups, Destinations. Create views like “who is in which group” and “where do these messages for this group go?”
  4. Also do some reporting, like “show last 10 messages sent” and “how many messages total are we sending a day?”
  5. Implement some basic tests for the Django code so I have a test environment for Django database code.
  6. (Cautiously) add some write capability for the social tables. Like “Add this person to be tracked” and “add this person to a group”.
  7. Take a deep breath! Stuff is working!
  8. Work on a plan to let other people log in and add users / groups.

 

Ubuntu name lookup: DNS vs NSS

Usually when I want to look up a domain name, I use the “dig” or “host” command. This issues a live DNS request to the configured DNS servers and you get a response from DNS. Sometimes I use “whois” on the domain first to find the domain authority, then do a “dig @server name” to find the actual live authoritative response, bypassing whatever cache my usual resolver (Google DNS) has.

But client programs on Ubuntu don’t issue DNS queries directly. They use NSS, the Name Service Switch, as configured in /etc/nsswitch.com. (In the long long ago a similar system was named YP, for Yellow Page). NSS often ends up using DNS to resolve a hostname. But it also uses local files like /etc/hosts. I’ve always had some fear it did its own caching too, although I don’t think my system does. There’s a daemon called nscd that would do caching, but I don’t have it installed.

Anyway, ordinary programs like “ssh” or “ping” don’t use DNS directly, they use NSS to look up IP addresses. So how do you query what NSS would do? The getent program.

$ getent ahosts google.com
216.58.194.142 STREAM google.com
216.58.194.142 DGRAM
216.58.194.142 RAW
2607:f8b0:4000:80d::200e STREAM
2607:f8b0:4000:80d::200e DGRAM
2607:f8b0:4000:80d::200e RAW

That’s returning a lot of data! “getent hosts google.com” returns a single address, which is generally what you mean. But for Google that gives you an IPv6 address. The “ahosts” command prints all possible matches, which is useful for debugging.

I’m digging into all this because of a frustrating problem with a freedns dynamic DNS name I use for my home machine. Every six months they decide I’m inactive and change the address to some domain parking page. In theory they email me a warning but it never gets through. So it breaks scripts I have that use the name to access to my home network. And I dutifully log in an re-enable my account, but it takes awhile for the changes to propagate.

After I re-enabled my account, “host” and “dig” would show the right address but “ping” or “ssh” would use the wrong address. Turns out if a domain is disabled freedns sets its A records to both 127.0.0.1 and 87.98.255.18, their parking web server. So that’s confusing. On top of that they set a TTL for one hour, which is kind of awful for something you’re trying to update. But I think my real problem was that one Google name server had cached the old bad address but another had cached the good new address, so queries were giving me random ones.

I’m going to just add a manual entry to /etc/hosts for now until that hour period is up.

Hawaiian Homelands: slippy map

I got curious about the details of the Hawaiian Homelands geography so I made a slippy map version. Patience on the first load; the basemap takes awhile. Purple overlay are the homelands (click for name), white lines are the historical Ahupuaʻa divisions. The basemap is Mapzen’s Walkabout style, a nice terrain map.

I’m feeling super ignorant looking at this data without really understanding the history or current situation of the Hawaiian Homelands. A friend recommended the book Hawaiian Blood. As a humble mapmaker I realize really what I need to do is work with an expert on Hawaiʻi, keep myself confined to journeyman geoprogramming.

But anyway I looked around, some interesting sites:

  • Waimanalo on Oʻahu. I love this shape, the terrain map shows how it tracks the ridgeline.
  • Honokawai. Google’s aerial imagery shows the hole is a reservoir. Not sure about the meandering slice out of the middle, it looks like a wooded ravine or river.
  • Waiohinu. Some individual parcels in a golf course development.
  • Airports: Hilo and Kalaeloa. It looks like the airport was dropped on top of the homeland, I have to think there’s some history there.

Production notes

I cobbled this together starting with Mapzen’s excellent one minute map tutorial. They’ve built a Leaflet extension that makes it super easy to add Mapzen’s base maps (vector rendered!) and map search. On top of that I just added a couple of custom GeoJSON layers with Leaflet-AJAX.

As before, data comes from the State of Hawaii Office of Planning. I converted it to GeoJSON like this:

ogr2ogr -f GeoJSON -t_srs crs:84 a.geojson ../ahupuaa.shp/ahupuaa.shp
python liljson.py -p 6 a.geojson ahupuaa.geojson

Hawaiian Homelands

I made a map of Hawaiian Homelands. This Reddit post about a map of American Indian Reservations and Alaska Natives inspired me; it left off anything about Hawai’i. The history of native Hawaiians and land ownership is totally different from the history of American Indians on the mainland. But the Homelands are somewhat analogous to Indian reservations in that they were land set aside by the US government for native people. I don’t believe they have any form of partial sovereignty though, and I think these land are even more sparsely populated than mainland reservations are.

Anyway, really I just wanted a nice picture; this one was the best I could find online. So I spent an hour or two with QGIS and came up with the image below (see full size). Totally unfinished draft, but this here is my secret work blog so up it goes.

pc.png

The data comes from the State of Hawaii Office of Planning which has absolutely awesome GIS data for download. Very well done site.

The green shapes are the Homelands themselves, the point of the map. I drew in major roads in orange to try to give some context to location. I wasted a lot of time trying to draw a few labels for towns but Oʻahu is so densely populated no simple rule works. I’d need to place town labels by hand for it to work right and I got lazy.

I also rendered the historical Ahupuaʻa in very light grey. That’s a fascinating division of the land from historical property rights. They seem to have been designed to give each owning aliʻi a mix of lowlands and highlands, with both farmland and some forest. I’d wondered if the Homelands followed the old ahupuaʻa boundaries but I think mostly not, except for the one large one in South Maui.

I wouldn’t mind spending more time to make this publication-quality. But I’m so ignorant of what the Hawaiian Homelands really are that I don’t feel comfortable doing any interpretive mapping. OTOH the Wikipedia page would benefit from any sort of picture, even this simple one, maybe I should look into what’s required to submit there.

Why are there 86,400 seconds in a day?

Pondering the question of why the second is defined as 1/86,400 of a day. I’d always thought it was because a second was about the length of a heartbeat, and thus measurable with the body. (Just like inches and feet and the like.) But that doesn’t really explain the exact number of 86,400 so I did some reading.

Between Wikipedia and this Scientific American article I have a basic answer.

  • Egyptians used base 12 math for some astronomy related things. Why 12? Either because you can count to 12 with your finger joints or maybe because 12 = 2*2*3. Or maybe because there’s ~12 lunar cycles in a year.
  • Egyptians divided daytime into 12 hours and nighttime into 12 hours. Note these hours were of variable length depending on the season.
  • Sumerians and Babylonians used base 60 math. Why 60? Not sure, but 60 = 2 * 2 * 3 * 5 which makes it convenient for a lot of math.
  • Greeks borrowed the Babylonian math when they did astronomy, so it was natural to divide an hour into 60 minutes and then later to divide a minute into 60 seconds.
  • The etymology of “minute” is from “partes minutae primae”; first small division of the hour. Same word as the adjective “minute”, as in tiny.
  • The etmology of “second” is from “partes minutae secundae”, the second division of the hour.
  • Some languages have a unit of time called the “third”, 1/60 of a second. Polish (tercja) and Turkish (salise).

There’s also a nice StackExchange discussion on the history of decimal time, a sensible 100,000 seconds in a day or what have you. Including this awesome French Revolution clock, my new coveted possession.

yzpyy

 

Documenting obscure bugs helps!

Had a real pleasure today; someone found a description of a League of Legends networking problem I wrote up a year ago and it gave him the clue to fix a problem he was having. (Long story short; specific actions in the game cause bursts of high network traffic, which can trigger lag or disconnects.)

I spend a lot of time writing up details of bugs and software problems. I do this partly for clarity, writing it up is a way to make sure I really understand the problem. I also do it so I can find my notes later in case I have a similar problem. And finally I put those descriptions online in case they help other people. And about once a year, they do!

 

Windows 7 update fixes

I dusted off the old Bootcamp partition to run Windows to play Civilization VI, impatient for the Mac release. Every time I do this I’m reminded how bad Windows is. This time around it was 90 minutes spent trying to install and run the game and failing. I gave up and went to bed, then fixed it in the morning.

The symptom was the installer would hang while installing the Microsoft VC 2015 redist. Cancelling the installer didn’t help. Manually killing the wuas.exe process that was hung did allow the install to complete. But then the game wouldn’t run; you’d launch it and it’d quit immediately with no error. Launching the program manually (bypassing Steam) revealed the error, “api-ms-win-crt-runtime-l1-1-0.dll is missing”.

So then begins the cargo cult debugging. Googling for answers and trying various incantations to fix the mysterious problem.

The first thing I tried was manually installing the VC redists. These installers have always sucked. The end result is it’s copying 20MB worth of shared DLLs into a system directory. Why does it take five minutes? Why does it hang entirely? Running by hand (as opposed to via the game installer) sometimes helps. It didn’t this time, it kept hanging.

So the second thing I tried was fixing that error about the crt-runtime. There’s a consensus in the cargo cult about how to fix this; run Windows Update. But Windows Update wasn’t working for me. This is the moment I confess my copy of Windows 7 isn’t registered with a valid license, I’ve been using the grace period for the very rare times I want to run Windows. My bad. So is it the lack of activation that’s causing the problem? Windows is popping up a nag when I try to run the installers. But there’s no explicit error, the installer just hangs. Trying to install it manually didn’t work either, same hanging on Windows Update stuff.

And then the scales fell from my eyes. Windows Update is broken. A fix was released in April 2015; or maybe not until July 2016. Not sure. Anyway the first step in installing that fix is to stop the Windows Update service. Once I did that the crt-runtime installer worked, copying it’s 800kb file successfully without hanging. Congratulations, l’il fella! And that was enough to fix the problem.

So let me rant and describe all the failure-by-design, from top down:

  • The game crashes on startup with no message.
  • The game installer hangs with no explanation. You can quit the install, but then it’s broken.
  • The underlying VC distributable installers hang with no explanation. Its job is to copy 20MB of files, but it can’t do this.
  • The underlying underlying CRT runtime installer is hanging with no explanation. Its job is to copy 800KB of files, but it can’t do this.
  • The root cause is Microsoft screwed up Windows Update somehow and fixing it is awkward, because it requires Windows Update to install the Windows Update update.
  • And worming its tendrils through all this is Windows Activation DRM, which may or may not be interfering and causing problems. With no explanation.

It really is an awful system.

 

certbot bug and fix (NoInstallationError)

I’ve got a Let’s Encrypt SSL certificate on http://www.somebits.com. They expire every three months, so I set up certbot to renew the certificate. It wasn’t working though, the cron job got the error

NoInstallationError()

I think this bug is now fixed in certbot. But if you follow common instructions, the cron job runs certbot with “--no-self-upgrade” so you won’t get the update. Running certbot by hand will have it upgrade itself with the fix.

The underlying bug was that certbot couldn’t find the apache2 command in the PATH, because it’s in /usr/sbin and that’s not in root’s path. (:facepalm:). The committed fix has certbot checking a couple of extra directories in addition to PATH.

League of Legends stats: some findings

I’ve been noodling with some League of Legends data as an excuse to learn more data analysis tech. I’ve blogged about the software, here’s the actual results I found.

League of Legends is a huge game, some 100M a month playing 1M+ games a day. And the data for those games is readily available. I took a look at third party summaries of game statistics from champion.gg and na.op.gg and tried to divine some meaning. The dataset mostly is for ranked games by Platinum+ skilled players in North America for patch 6.17. But I also looked at players of different skill and trends across game patches.

The most interesting conclusion I found was that some champions win much more in the hands of skilled players. Nidalee, for instance, has a 45% win rate in Silver but a 54% win rate in Diamond. That’s not exactly a surprise, she’s known to have a high skill cap, but it’s good to see hard data. And there are surprises; I would not have guessed Pantheon also was highly improved or that Dr. Mundo suffered at higher skill levels.

Despite looking, mostly I didn’t find any unusual trends or big shifts in the game over patches. To me that’s a testament to the quality of the game, in particular Riot’s game balance team.

Below find some analysis and graphs. I’ve put my notebook output online for viewing here:

Basic stats for patch 6.17

The first thing I did was look at the basic champion.gg stats for patch 6.17. Each row in my dataset is one summary line for all players of a champion in a role. For instance Nami / Support. Note there’s a bit of bias here; champion.gg omits rare cases like Nami / Jungle.

There’s relatively little diversity in ADC and Support champions. Simple result: there are only 17 regularly played ADC champions and 25 Supports. There’s ~50 champions played Top/Middle/Jungle. This fact skews a lot of my later statistics, particularly with the ADC pool where a single champion (Lucian) dominates with a 32% play percentage. The top mid, by contrast, is Ahri with only 13%.

download (1).png

Players generally don’t pick champions with higher win rates. This surprised me a bit; I thought there’d be a clear bias towards the OP champs. There isn’t.

download.png

Players do tend to win more on champions they have more experience with. No big surprise here, but more games = more wins. The stat “experience” here is average games played on that champion. (It’s in the champion.gg dataset, but not displayed on the website.) The correlation coefficient is +0.24 with a p value of 0.0005, which seems likely to be significant to me. The causation is less clear. For example Galio-Top players have an average of 107 games on the champ and a 55% win rate. Do people win on Galio because they play him a lot, or do they play him a lot because they win? (Or in the specific case of Galio; do relatively few people play him but the ones who do are really good?)

download.png

Stats for players of different skills from na.op.gg

I was curious how these statistics varied by tier, so I went to na.op.gg and downloaded stats for players at all skill levels. I mostly focussed on Silver through Diamond, since those are the most “normal” player populations. This data is for the month of Aug 15 – Sep 15 2016 and spans patch 6.17 and 6.18.

Some champions have much higher win rates at higher tiers. This result is the most interesting I’ve found. I feel like each player at the extremes has a story. I’m not surprised that Nidalee’s win rate goes up 9.37% from Silver to Diamond; she’s hard to play well and so presumably does better in the hands of a skilled player. Aurelion Sol goes up 5.8%, maybe because he depends on skilled teammates? But why does Pantheon go up 7.5%? He seems so simple! I’m guessing Aatrox and Garen do worse in higher tiers because players know how to exploit their weaknesses. And Amumu’s 4.1% drop may be as simple as Diamond players being less vulnerable to Amumu cheese. But there’s more to say here and I’d like to develop this data further. Here’s the 10 most improved and 10 who suffer the most.

Screen Shot 2016-09-21 at 4.32.54 PM.png

Some champs are significantly more popular at higher tiers. The companion result to win rates; what about pick rates by tier? Janna is the most more frequently picked, she goes from 0.8% to 2.9%. (As a frequent Janna player my theory is she is much more rewarding to play when your team is more skilled.) Leona drops from 1.6% to 0.6%. The ADC champion pool attenuates at higher tiers too; Lucian dominates and Jinx drops off, for instance.

Screen Shot 2016-09-21 at 4.37.11 PM.png

Silver-to-Diamond win rate is correlated with Silver-to-Diamond pick rate. In the previous section I reported that for Platinum players, win rate is not correlated with pick rate. However the champs that have the most improvement rate from Silver-to-Diamond also tend to have higher pick rates from Silver-to-Diamond. This suggests that higher tier players are picking champions that have more impact at their skill level. Well maybe; I have a suspicion this effect is pretty small.

download (2).png

 

Trends across patches

Finally I was curious how stable the game statistics were over patches. I collected historical data from champion.gg’s GitHub going back to patch 5.10, over a year ago. These are all ranked Platinum games.

Stats are pretty stable between patches. In general there’s not a lot of change in the game since 5.10. For instance, players averaged a 2.55 KDA in 5.10 and a 2.48 KDA now in 6.17. There is a general trend up in some of the cumulative stats like “goldEarned” or “totalDamageTaken”. That could easily be a symptom of games just taking longer over time; unfortunately I don’t have stats on game length to normalize with. Two highlights though. Experience has a big drop at the beginning of Season 6. I take this to be new accounts and/or people changing up how they play. Also totalHeal had a big bump up around patch 5.22. That could be the same general cumulative stat effect, but I think it may also indicate the addition of more healing abilities and the rise of healing supports like Soraka and Nami.

download (2).png

Champion diversity is pretty stable between patches. Up above I showed the distribution of playPercent across 5 roles for patch 6.17; here’s an animation of that distribution across patches. It’s pretty stable. So are the distributions for all the metrics I’m most interested in; goldEarned, KDA, winPercent, in general the distribution across champs looks the same between patches. I find that a bit surprising because I think of LoL game balance being pretty dynamic with a constantly changing meta. But it’s not really reflected in the stats.

 

Better Jupyter charts: animation

Well this is neat; matplotlib supports generating animations, and you can inline HTML5 video right in Jupyter. The only wrinkle I hit is the stupid Ubuntu ffmpeg/avconv kerfuffle. Trying to produce the animation by default produced the error “KeyError: ‘ffmpeg’”; I solved it by setting

matplotlib.rcParams[‘animation.writer’] = ‘avconv’

There’s a GitHub comment saying that avconv may not be reliable, but it seems to be working for me in Chrome.

Now to figure out how to make this work with Seaborn. Some hints here.

Update: the Seaborn hints mostly just worked. Hilariously the inline video solution is to encode the whole MP4 file in a data64 blob right in the HTML, some 130k worth in my case. Hey, it works.

Better Jupyter charts: Seaborn

Took a quick tour through Seaborn, the enhancement library for matplotlib. It’s very good! It does two basic things. It makes the default matplotlib charts prettier, and it gives you an easy API to do some fancier types of statistical visualization. I’d say it’s a no-brainer to use Seaborn if you’re doing exploratory data visualizations. It still just renders raster images in Jupyter, so it doesn’t fulfill my goal of having nice SVG interactive charts in the browser, but Seaborn is solving a different problem.

Prettier

“Drawing attractive figures is important”, the docs say, and I couldn’t agree more. Seaborn reconfigures matplotlib so the default charts look better. I don’t just mean nice anti-aliasing, but also reasonable grid ticks and color choices. Seaborn has good perceptual palettes which are really important. I believe stock matplotlib has recently improved in part with input from Seaborn.

The other part of “attractive figures” is the Seaborn API is DataFrame-aware and will label your plots using the labels in your DataFrame. Getting nicely labelled axes and titles and stuff takes several lines of manual code with matplotlib; with Seaborn it’s a single line of code.

Fancier statistics

The meatier part of Seaborn is it has more complex chart types built in.

Distributions are mostly what I’ve used. In detail:

  • distplot: 1 dimensional distributions, an enhancement of matplotlib.hist. It adds a continuous kernel density estimate to the bars, and also has a rug-plot option.
  • jointplot: 2 dimensional distributions, an enhancement of matplotlib.scatter. Adds correlation coefficient, histograms on the side, a sort of quicky ggplot. Can also do continuous contour plots. One drawback is there doesn’t seem to be any easy way to set the hue of the individual dots, so no sneaking in a third dimension of data. Pass in kind=”reg” to have it try to fit a regression curve to the scatter.
  • hexbins: 2 dimensional histograms
  • pairplot: pairwise jointplots for your N dimensional dataset. So nice to have this in a single command, although it’s unwielding for N > 5 or so. (Note this does have a way to set the hue of individual dots.)

Regressions are for fitting various kinds of statistical models to your dataset.

Categorical graphs are for looking at statistics for qualitative categories, plots like swarm plots and violin plots. They’re really quite beautiful. Here’s a sample visualization of the distribution of a variable (y axis) for each of 5 categories (the x axis). I’ve used a violin plot which shows a KDE continuous approximation, along with a swarm plot to show the actual dots on top of it. (The data set is # of games players have for each of 5 roles in League of Legends. That one crazy outlier is Fiddlesticks Jungle; players tend to have 220+ games on him!)

download.png

Finally data-aware grids are used for making small multiples plots of the same dataset. I already mentioned pairplot, for doing NxN visualizations of N variables, pairwise. FacetGrid is a tool for quickly generating a bunch of graphs comparing across multiple categorical variables.

Conclusion

I like Seaborn. I like that it looks good out of the box. I also like that it allows me to make more sophisticated graphs very simply, with little effort. It may be a little too easy; I’m not sure a violin plot is really the right treatment of that data above, for instance. But it sure looks good!

Better Jupyter charts: mpld3

As much as I’m liking Jupyter, I don’t much like that matplotlib is the default charting library. I mean matplotlib gets the job done, and it’s powerful and popular. But end of the day you’re rendering raster images with 10+ year old software. (Even if seaborn has made the raster images better.) We’ve got a fancy browser viewer, why not have fancy SVG/Javascript graphs?

That’s what mpld3 provides. Using it is as simple as importing it and calling mpld3.enable_notebook(). All (most?) of your old matplotlib API code will still work. mpld3 emulates that charting API but renders to SVG using D3, instead of rendering to a static image. It’s kinda nutty that it just works. The resulting pixels look good, although admittedly matplotlib’s raster backend (agg?) looks pretty good too. 

The real advantage is the graphs are manipulable with Javascript. Out of the box every graph is now pannable / zoomable, right in the browser window. You can do fancy linked brushes across multiple figures.

There’s also plugins to add more capability. PointLabelTooltip plugin is particularly nice, it adds an easy way to have HTML tooltips on a scatterplot when you hover the points. There’s also MousePosition (useful for images).

And... and that’s about it. After a bunch of work a couple of years ago development seems to have stalled. That’s OK, it’s useful as is. Particularly since it’s such a simple drop-in upgrade for matplotlib.

Probably time to look at alternatives. Bokeh is the “better matplotlib” and includes a bunch of browser / notebook stuff. However it’s still rendering raster images (albeit in an HTML5 canvas). The examples sure are pretty though. I also see frequent references to VisPy, which is GL based, but although there’s some noises made about WebGL and notebooks I can’t find a working demo. Other options I’ve run across are pygal, bqplot and Altair. People also talk about Plotly but it’s a hosted system and costs money.

Some other thoughts on this topic: The future of visualization in Python, In defense of Matplotlib, Overview of Python Visualization Tools

While I’m here, ipywidgets is kind of nutty. It lets you add interactive controls to a notebook like sliders and input boxes, to turn your notebook into an interactive app.

 

Pandas DataFrames: MultiIndex and slicing

Diving more in to using Pandas DataFrames, I spent some time learning about MultiIndex. Long story short it’s a way to have a composite key for your data, to say “these two columns of my CSV file are the name for the row”. Or more complex things.

Pandas has some fairly powerful mechanisms to subset your DataFrame based on aspects of its MultiIndex composite key. They’re a bit confusing though, the slicing syntax is abstruse. Also there’s a hidden gotcha: you really have to sort your DataFrame before you can slice it if it has a MultiIndex.

Anyway, there’s a demo notebook program here. I also uploaded the ipynb file as a gist but GitHub’s viewer is buggy.

For the search engines: if you see any of the following error messages, this sample notebook will help you figure them out. Summary; call DataFrame.sortlevel()


PerformanceWarning: indexing past lexsort depth may impact performance.

KeyError: 'Key length (1) was greater than MultiIndex lexsort depth (0)'

KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'

PS: if you want to get the series of index labels for a DataFrame with a MultiIndex, use get_level_values(). I keep forgetting how to do this.

How to win Stack Exchange: come early

Screen Shot 2016-09-17 at 9.33.13 AM.pngI’m in the top 6% of Stack Exchange users, despite seldom contributing to the site. How? I got in early.

I didn’t do anything clever. I just happened to have asked a well-worded question seven years ago that’s been popular with Google searchers ever since. It helps that I got a great, surprisingly simple answer.

It just keeps paying off, a reliable karma trickle. Something like half of my reputation points come from the one question.

I think the Stack sites are terrific, btw. I now go to Stack Exchange first for questions on new libraries like Pandas, before I even go to the code’s own documentation.

Notes from a Jupyter/Dataframe project

I’m looking at some League of Legends data; champion win rates by player tier. I’m curious which champions have higher win rates with skilled players, and/or which are more popular. You can see the resulting report here, notebook (without nice CSS) is here.

Learning me some Jupyter and Pandas

Really I’m using this project to get more comfortable with using Jupyter and Pandas DataFrames to analyze data. The DataFrames part is overkill; I’ve got about 10k of data, not the 10G of numbers DataFrames’ highly optimized code is for. But DataFrames have lots of functions that replicate SQL’s analysis capabilities and they display nicely in Jupyter, so here I am.

My data starts as web pages of HTML tables. I imported those into a single Google Spreadsheet with multiple tabs.For a single sheet, rows are champions (120 or so) and columns are statistics like win rate or games played (5 of them). There’s 7 sheets, one per tier Bronze / Silver / Gold / ... I then exported those sheets as CSV files, one per tier, for analysis. (Google Spreadsheets turns out to be a remarkably good HTML table data scraper.)

I then played with various forms of Python code for reading those CSV files and doing some statistics on them. Starting with simple raw Python data structures, a bunch of dicts and tuples all the way up to a full Panda Panel. Along the way I learned how to analyze the data using Pandas a bit, and to format the results nicely in Jupyter. My real goal here is to make interactive reporting as natural as if I’d loaded all the data into a SQL database. Being able to do natural things like sum all values, or get the average of numbers grouped by some criterion.

Data loading

One thing I found is that the more I whipped my data into Pandas shape, the simpler my code got. I finally settled on doing all the parsing way up front, when I read the CSV files, to make clean DataFrame objects with well named columns and rows. That makes the later analysis code much simpler.

The read_csv() function has a lot of options to configure parsing, it’s worth the time to set them. “thousands=,” for instance will allow it to parse things like “1,523,239” as an integer and not a string. I also ended up doing “header=0” and specifying my own “names=[...]” for columns, just so I could make the names valid Python identifiers. (You can access named things in a DataFrame with attribute syntax; either df[“winrate”] or df.winrate.)

But the most important thing for read_csv was index_col. The concept of index in a DataFrame is particularly important. That’s the unique key that names each row; in my data the index is the champion name. In a CSV file this would probably be the column named “label” or the like. In a database table it’d be the primary key. The word index is used all over the docs and it confuses me all the time. Once I set up my data index correctly the code got a lot better.

The thing I find most confusing is the shape of data. DataFrames, for instance, mostly seem to want to treat a column of numbers as a single feature. But I really need to work row-rise most of the time. Slicing a DataFrame is particularly bizarre. df[n] gives you the nth column from the dataframe df. But df[n:n+2] gives you rows n to n+2. I find I often have to transpose my dataframe to make operations convenient, or use the “axis” parameter to functions like sum() to indicate whether I want to sum over columns or over rows.

The final fillip was using a Pandas Panel to store my data. A Panel is a collection of DataFrames; in my case one per tier. This 3 dimensional data structure is a bit confusing, the docs apologize for the names and it’s not clear that Panel adds a lot of value over a dict of DataFrame objects. But it’s Pandas’ way of representing a collection of spreadsheets, so I am going with it. My panels “items” are the tier names, the major_axis is champion rows (named by the index) and the minor_axis is the stats (the columns.)

Data analysis

So now I have my data loaded into a panel, time to analyze. The pattern I’ve settled on is generating a new DataFrame that’s a report table. For instance I’m interested in average statistics per tier. So I start with a 3d Panel of tiers x champions x stats, and I boil that down to a 2d DataFrame of tiers x average(stats). When I do ad-hoc Python report generation I usually just iteratively print out report lines, or maybe make an array of dicts for my data. Those are still fine too, but I wanted to go full Pandas.

I started out by writing lots of laborious loops over panel.iteritems() and the like. See cell 7 and how I first build up a dict named ‘spreads’ and then converted it to a DataFrame. Over time I’ve refined to simply doing operations like dividing a DataFrame by a Series and the like. Cell 8 shows that style, the creation of pick_rates is about the same computation as spreads before, but it’s less code. The whole process feels a lot like vectorizing code, like I did for my machine learning class in Octave/MatLab. The code gets shorter, which is nice, but it should also be more efficient which matters for large datasets.

Presentation

My final goal was to make nice-looking reports right in Jupyter. That proves to be quite difficult. Pandas is amazing at inlining graphs and visualizations with matplotlib and friends. But it’s not quite as good at textual reports. I mean Jupyter will display any HTML you make in python, but I haven’t found any good HTML generation convenience libraries out there for, say, DataFrames.

Fortunately the default DataFrame presentation HTML is pretty good. Labelled columns and rows, decent formatting of numbers. All that’s really missing is right alignment of numbers (and why is that not the default?!) But I want more control, for instance rounding floating point numbers to specific precision. For that I used the DataFrame.style object, which gives you a D3-esque ability to apply per-datum CSS styles to cells. I mostly used .format() to control text formatting of numbers and .set_table_styles() to add some CSS to the HTML table. The .applymap() function is the really powerful one that lets you control things per-datum.

I also threw in the background_gradient style, to give a sort of heatmap coloring to the number cells. That required installing a bunch of crap like python-tk and numpy just to get the colormaps. But it’s pretty painless in the end.

Conclusion

Pandas + Jupyter is a pretty good platform for ad hoc exploration of data, and with some learning and effort you can produce pretty clean code and reports. I love the way notebooks are reproducible and shareable. I think using SQL for this kind of work is probably more effective, but there’s a lot of overhead in getting set up with a database. And the interactive exploration isn’t as nice as a Jupyter notebook. (Hmmm, there’s no reason Jupyter cells couldn’t contain SQL code!)

DNS ANY requests are deprecated?

Saw something new in DNS recently

$ dig reddit.com any
reddit.com.    		3788   	IN     	HINFO  	"Please stop asking for ANY" "See draft-ietf-dnsop-refuse-any"

Huh. Turns out there’s an effort afoot to refuse ANY requests. CloudFlare’s post on their reasoning is instructive. Long story short ANY was mostly only used for debugging, not in real applications. But it’s also expensive to serve and easy to abuse, particularly in DNS amplification attacks. So out it goes.

Too bad, but I see the dismal logic of it. Chalk it up along with AXFR DNS queries and NTP’s monlist command for “why we can’t have nice things that use UDP”.

NFS vs Samba

My music stops playing when I write a large video file to my server.

More technically, when I write 10MB/sec via NFS to my Ubuntu 14.04 server, the Samba server on the same host (and same disk) stops serving files reliably to my Sonos system.

The server’s definitely not CPU bound, nfsd is taking 5% of one CPU. It’s probably IO bound though. The NFS client doing the writing is MacOS with the automounter, so I’m guessing it’s UDP. I wonder if I’m simply flooding my 100Mbps ethernet with NFS traffic and the TCP Samba packets can’t get through?

This happens rarely enough I’m not going to put more time into figuring it out. Sure is an interesting failure mode though.

 

Setting up motion and an Axis camera

A few months back I bought a simple network camera for low-key home security and then never set it up. Well I set it up now and it works. Some notes.

The camera is an Axis M1034-W. It mostly works well. Right out of the box pretty much; acquires an address via DHCP (ethernet first, until you configure wifi). Immediately serves a video stream once it’s up and has a straightforward web configuration interface. That’s the good part. The bad part is the only video stream that works is Motion JPEG (ie: a bunch of JPEGs). There’s support for H.264 but it requires a Quicktime plugin to view, a nearly dead technology. Also a video stream is all I can get. The camera has its own motion detection stuff but it requires a Java applet (!) to configure. So that’s all dead web technology. But the basic camera and HTTP viewing works.

I ended up using motion to monitor the camera and publish images and movies of motion. My original idea was to use ZoneMinder, but that install uses PHP and MySQL and seemed like overkill. motion just writes image files to a directory (and optionally, a database). It does depend on avconv / ffmpeg, but that’s all.

Configuration of avconv was pretty simple. Install it in ubuntu, set up a /home/motion, set up a /home/motion/.motion/motion.conf with the config. The key configuration directive was “netcam_url http://192.168.0.XXX/mjpg/video.mjpg”, to tell it how to find the Motion JPEG stream. You can also have it poll static JPEGs via a URL like http://192.168.0.XXX/axis-cgi/jpg/image.cgi?resolution=1280x800 but I’m imagining the motion JPEG stream is better. I also had to set up the username / password for the camera, and some output options. There’s a lot of choices for tuning the motion detection algorithm, file writing frequency, etc.

The main tuning I did was set the Axis camera itself to only serve 640x480 @ 10fps. Sad to lose the quality, but I don’t want to flood my wireless network with 18 mbps. We’re pushing about 2 mbps as it is; motion JPEG is a really stupid way to send video when you expect nothing to change. My Mac Mini is chewing about 6% CPU processing this data.

When I have more time I’m going to look to see if the Axis camera itself can usefully do the motion detection and video encoding. I think it can, just gobstopped by the Java applet requirement. I mean, really?

Non-cryptographic hashes

 

About once a year I need to hash some data to give it a name / short checksum. I don’t need a cryptographic hash. But I end up using SHA-1 or MD5 anyway because it’s so available. A non-crypto hash should be ~100x faster to process data, which could actually matter. But finding a standard, portable, non-cryptographic hash with optimized implementations for Python, Node, etc is a challenge.

A lot of history of hash functions is producing 32 bit values on 32 bit CPUs. That stuff is mostly obsolete. 32 bit hashes are not useful for many applications; you expect hash collisions after just 2^16 ~= 65,000 objects. And 32 bit CPUs are largely irrelevant now. You really want a micro-optimized machine code implementation for AMD64 that is aware of cache geometry, pipeline optimizations, etc. It may be now that you want a GPU implementation; you certainly do for high throughput crypto hashes. Not clear if it matters as much for non-crypto hashes and deployment realities mean you may not have a GPU at all.

Stock Python has the hashlib library, which includes crypto hashes like MD5 and SHA-1. It’s highly optimized. There’s also CRC32 and Adler32 hiding in the zlib library, but they are only 32 bit hashes and therefore not useful.

MurmurHash3 is the usual recommendation for a non-cryptographic hash. It’s been around a long time and widely implemented. It’s also a bit confusing, with both 32 and 128 bit versions and multiple Python implementations.

There’s a bunch of “nextgen” hash functions out there. Metrohash and xxHash both look promising on first glance.

SMHasher is the standard test and benchmark suite for hash performance. I’d love to read a carefully done comparison of hash functions out there in contemporary languages and deployment environments.

some ffmpeg bash functions

I’m doing a lot of trashy video editing on the command line. I’m taking FLV files from a screen recorder, trimming them to a time frame and converting them to MP4. And then I’m concatenating multiple MP4 files. This is all very confusing to remember how to do in ffmpeg so here are two shell functions I use to do the work for me. There’s nothing particularly clever here except the <() process substitution for the catmp4 program, which creates a temporary file (or named pipe or something) with the output of a command.

function tomp4 {
    ffmpeg \
      -i "$1" \
      -c:v libx264 \
      -preset slower \
      -crf 19 \
      -ss "$2" \
      -to "$3" \
      "${1%.flv}".mp4
}

function catmp4 {
    ffmpeg \
      -f concat \
      -safe 0 \
      -i <(for f in "$@"; do echo "file '$PWD/$f'"; done) \
      -c copy \
      out.mp4
    ls -l out.mp4
}

Ubiquiti cranky customer

Very happy with my Ubiquiti network hardware. Unimpressed with the software experience. Just sent this cranky email to their support, where I’m sure I will get a canned “thanks for the note” reply and nothing will improve.

Your products have three problems that harm the perception of security. Y’all make excellent network hardware, but your software should be as excellent. I’ve already worked around these problems, just registering a complaint.

The Unifi Controller Mac application is not signed. MacOS refuses to launch it until I disable Gatekeeper security.

The Unifi Controller does not come with a valid SSL certificate. I realize this is complicated, but it’s a bad experience to require users to disable Chrome SSL checks to use the product.

Your reset password links from ZenDesk are being flagged as spam by Gmail. They say “Why is this message in Spam? It has a from address in ubnt.com but has failed ubnt.com’s required tests for authentication. Learn more”.

Thanks for listening,
Nelson

Bash arithmetic syntax

For years I’ve been doing bash arithmetic like this

echo $[2+2]

TIL I’m supposed to be doing it like this

echo $((2+2))

Who knew? Everyone, and apparently since 1996 with the release of bash 2.0. The $(()) syntax goes back to the 1988 Korn Shell, which predates when I learned Unix. But I learned most of my fancy shell scripting in the 1989–1994 time frame, when bash was the new hotness and it felt edgy using advanced features unimagined by Bourne (blessed be his name). And I preferred bash to ksh.

I learned this when someone edited one of my StackOverflow karma factories, on how to generate random numbers in bash. I updated the syntax in my answer. (Stack’s moderation review decided it was a bad edit. They were wrong.)

Ubiquiti Unifi access points

Boy, bad first impression of a product. I got a Ubiquiti wireless access point. Figured I could set it up in 10 minutes and go; what could be easier? Lol, joke’s on me. They now require a 200 megabyte “Unifi Controller” running on some machine on your network to configure the devices; no more simple web interface. Instead the controller talks some magic protocol to the devices and then runs its own web server on port 8843 with a fancy web UI. Did I mention the Mac binary is not signed, so it won’t even run without working around Mac’s security system? And the SSL certificate doesn’t work? Awesome.

The software itself seems useful but complex. The manual is 154 pages. It provides group management of all Ubiquiti devices on my network. This seems like it would be great if I had a complicated network with a bunch of Ubiquiti devices. Maybe that’s their market. I just have one device, though, and it better play nice with the rest of my network. Fortunately this is just an AP, and stumbling through I got it working without much effort.

I think it was as simple as going through the basic config of the controller software (username, password, wifi settings), then choosing the Devices tab and clicking “adopt” on the access point.

Sitting 6 feet from the AP I’m getting a full 100Mbps according to DSLReports’ speed test. (Link layer claims 216Mbps). Putting the AP where my old one was gives more like 20Mbps, but I think it’s still better WiFi than the Asus RT-AC66U that I use. But the whole point of this is I want a second AP for upstairs, so I’ll end up running both.

Not a fan of the Power-over-Ethernet brick they provide. I’m confused about POE, there seems to be multiple standards for voltages and which pins are hot. I have no idea if it’s feasible for me to run POE for my whole house, particularly since this punchdown board everything goes through is some Levitron piece of crap that can’t even reliably do gigabit.

Factory Idle

I’ve been hooked on Factory Idle, a well made little puzzle / idle game that runs in the browser. You lay out factories from modular components. It’s basically a casual version of Factorio, with deliberate periods of idleness built in where you let it run in the background and do its thing. Designing factories feels a lot like programming.

Below is a screenshot of my current research factory. I’m at tier 3 of factory research, where I have metal labs and oil&gas labs (left and bottom) both generating reports and feeding them to analytics labs when then deliver them to the research centers on the right. It’s not at all space efficient, as managing flows gets more complicated I’ve been deliberately leaving space to make it easier to design and refactor. The complex piping in the center room is particularly subtle, a system to mix awkward rates like the 11/20 output of the blue metal labs feeding the 32/40 orange inputs of the analytics labs.

(Note this layout has a bug; one of the gas labs in lower left is missing its gas input.)

Screen Shot 2016-06-02 at 12.54.44 PM.png

Moving forward with lolslackbot and Django

I’m very encouraged with how my little Django experiment has worked out. I’m ready to start using it with lolslackbot. A big breakthrough was realizing that I can start using Django as soon as I trust it not to corrupt my database. Keep the existing Python cron job in old code, not using Django, and then have a separate webapp that also uses the same database. The cron job and the webapp will be reading the same tables but in general not writing the same tables. It seems like a good transition plan.

Only now I really have to face the sqlite question. I’m confident that ultimately I need to be using PostgreSQL. I’m envisioning thousands of web users updating the database; there’s no way that works with sqlite’s database-level locking. Even with low traffic the cron job and the webapp will be stepping on each other. I need to switch. But when?

Do I switch databases first, porting my cron job code over to a Postgres-backed system? That seems really painful and not much fun. Lots of backend work with no visible features.

Or do I use Django first, having it talk to the sqlite database? The lock contention won’t be a real problem if I’m the only webapp user. It lets me build fun / useful features sooner. And it gives me some more experience with data modelling. I’m pretty sure I’m going to want to refactor the schema along with the Postgres update, it’d be better to do that after doing some of the webapp work. The risk with Django-first is I do a lot of sqlite-specific work that is ultimately wasted. But Django’s ORM insulates you from the underlying database pretty well, so maybe that doesn’t matter?

Also curious how the Django ORM is going to work for me. I use a couple of non-standard SQL things now. Mostly “insert or replace”, which is sqlite’s upsert-like extension. Does the ORM expose those? Also very curious how testing will work. sqlite is so simple when managing test environments. But I know the Django folks have thought this through.

adding lolslackbot to a new slack

I had to add my bot to a new Slack today (8 new users!) and forogtten how. My bot isn’t a full Slack App, it’s just a bot user, which in Slack terms is a “custom integration” tied to my personal user account for Nelson. Here’s the steps to set it up:

  1. Log into the Slack as Nelson, in the Web UI
  2. The account needs permissions to add custom integrations. You get this by default if you’re an Admin, otherwise it needs to be added under Team Settings / Permissions
  3. In upper left corner, click the down arrow near the Slack name to get to the menu for preferences / etc. Choose the “Apps & Integrations” option under the Slack team’s menu.
  4. Ignore the confusing app directory. Click “Manage” in upper right.
  5. Click Custom Integrations
  6. Click Bots
  7. Click Add Configuration
  8. Fill in the form and save it. Also copy the API token.
  9. I had a problem with a new Slack where I couldn’t add a Bot user, I think the UI acts differently for the very first integration. I managed to create the bot though by hitting this link: https://my.slack.com/services/new/bot
  10. Create a channel for the reports to go to. (Or use an existing one.)
  11. Invite @gamebot to that channel.

That’s the Slack UI process for adding my bot. Kind of a mess, but it’s because I’m using the old bot interface and not the new fancy Slack App integration system that I should be.

After all that setup, then it’s on to Python code to find the channel token. Then set up the destination and subscriptions via code / SQL. All so manual, must build tools.

Speaking of tools I’m pretty convinced Django is the way forward. With a web UI, not some Slack interactive thing.

Apple UI geniuses at work

I accidentally clicked something Keychain related in my menu bar and this popped up

Screen Shot 2016-05-24 at 4.28.06 PM.png

Notice the lack of a red close button? Cancel causes the window to respawn middle of my screen. Over and over again. Did I mention the window floats on top of everything else?

I particularly like that apparently the only way to get this to go away is to type my password to it. That’s good training for users; “type your password even if you don’t know what it’s for because it’s the only way to make the dialog go away”.

Update oh god it’s reproducing. A second one just popped up

Screen Shot 2016-05-24 at 4.34.16 PM.png

Update 2: apparently I’d locked my login keychain by accident. That’s cool, rebooting unlocked it without me ever having to type my password.

Django learnings: models

I’m soldiering on with trying to apply Django to my lolslackbot project, I thought I’d take a stab at letting Django try to use my existing database. My specific goal is to set up a read-only set of views on the primary social tables I have. People, Groups, Destinations all name entities in my system, I also have GroupMembership and Subscriptions tables which are many-to-many relations between the three primary tables. So far so good, at least for the primary tables; still working on the relations

Turns out starting with a legacy database isn’t too hard; you can use the inspectdb command to build skeletons of Django model classes from an existing database. Then hand-edit the resulting code. As a bonus this is an excuse for me to start learning more about Django models. Some random things I learned:

  • Django model classes define both a database schema and the UI validation behavior in HTML forms.
  • Every Django model class must have a primary key. The Python field is named “id”, not sure renaming it is possible or a good idea.
  • A model can have the option “null” set to true or false; this is whether empty values are stored as nulls in the database. (Why would you ever not?!) There’s also a “blank” option which has nothing to do with the database, but is whether the field is optional in autogenerated forms like the admin interface.
  • You have to hand-add each model class to admin.py to get it to show up in the admin interface.
  • Django coding style is lowercase_with_underscores for field names, CamelCase for class names. ¿Porque no los dos?

That’s the easy stuff. On to hard stuff.

I’m not sure how to translate my existing many-to-many relations tables to however Django implements relationships. I thought maybe the extra fields support (using the through keyword argument) might do it, but that seems like overkill and possibly awkward. I think I need to just adapt the ManyToManyField to my existing schema.

I’m a little scared to let Django start writing data to my database.

inspectdb sets up things with managed = False by default. That seems wise; it prevents Django’s schema management stuff from messing with tables someone else defined already. But some day I’m going to want Django to take all this over for me, can I later change managed to True and make sense out of it?

I haven’t even begun to think about testing in the Django world. I know there’s a lot of support for tests, maybe that’s my next learning.

lolslackbot postmortem

Had a significant outage for my lolslackbot project yesterday. A few different things went wrong and I’m still confused for what the problem is.

The behavior

The problem manifested as me seeing the same message being delivered every time the program runs, every 3 minutes. That’s bad; I’m spamming my users. At the same time I was seeing errors in my logs from trying to deliver messages via Slack. No useful message mind you, but at least a hint.

I was busy last night when I spotted the error so I just shut the whole system down until morning. Then in the morning I tried a quick fix and run the script but that went badly, so I had to look closer. I finally got it fixed after two hours of work.

The delivery bug

This morning first thing I did was add more logging and reproduce the problem. I discovered the error was one of the Slack channel IDs no longer existed, which caused an exception in the Slack messaging module, which then broke things. The underlying problem was a design flaw in my error handling; I was trying to deliver all Slack messages at once and only then updating the database indicating those messages had been processed. The result is if there were 3 messages to be delivered at once and the 2nd one caused an error, the 1st one would get delivered but not marked processed and so would get delivered again.

So I fixed it by refactoring the logic that marks messages processed. I still deliver all the Slack messages at once but now individually flag whether each one worked or not. I also mark a message processed whether there was an error in delivery or not. The underlying problem is basically a distributed transaction. I’d rather err on the side of occasionally losing a message than sending the same message many times.

Rate limiting problem / match commit semantics

A second problem making all this diagnosis difficult was that my system was downloading match objects but they weren’t ending up in the database. I finally figured out my script that downloads all missing matches was crashing before it finished. And I only was calling commit on the database when the script finished, so all the work was getting lost. Derp. I fixed it to now commit after every single match object is downloaded. Also put in some better error handling.

So what’s causing the errors downloading matches? I’m not really sure, but I think it’s Riot’s rate limiter. I have some very high rate limit that I shouldn’t be getting near, but I’m still getting 429 responses for my meagre stream of requests, being told to wait. And this problem has been going on for days. I had chalked it up to a networking problem with their servers, but it turns out it’s my client waiting politely like it’s been asked to. So why am I being throttled?

I don’t know. The thing that triggers it seems to be a few odd matches that are returning 404 errors indicating the match doesn’t exist. (Even though it should, since I saw a reference to it from another API call.) Perhaps they have extra rate limiting for clients that make repeated requests that generate 404s? Part of the problem here is that I treat a 404 as “no meaningful response, try again later”, so I’ve accumulated 10-15 of those over time. I should clear them out, and change the code to stop trying if it gets the 404.

Lessons learned

Man, debug logs are a big help. Fortunately the same time I was having this problem I’d just committed new code to write debug logs more usefully to a file. Couldn’t have figured out what was going on without it.

A broad thing I learned here is be smarter about error recovery logic when working with third party services. I think when interacting with Riot or Slack or whatever, I want to do one small bit of remote API work and then immediately commit that work to the database before trying the next remote thing. And handle errors from remote services robustly, continuing even if it fails.

Unfortunately some of my code is now squelching exceptions, logging them and continuing instead of crashing the program. This is necessary to make my code more robust to errors, but is scary. Anyway I found I was having a hard time logging exceptions properly, here’s the way I’ve settled on:

try:
    someFunction(data)
except Exception as e:
    logging.error('Something went wrong %s' % data, exc_info=True)

The key thing here is the “exc_info=True”; this gets Python to include a stack trace. Before I was trying to actually log the exception object e itself, but that only gets you the message, not the stack. My use of % is an anti-pattern, I’m really supposed to use a comma and let logging do the substitution, but for some reason I find that error prone. And the worst thing about errors in a logging function like this is unless you are superhuman you often don’t have test coverage for the exception cases, so this line of code only ever executes in production when something else already went wrong and it’s very confusing.

Django part 1 what I learned

I sat down and wrote my first Django app (in a very long time) yesterday using this tutorial, parts 1-3. Here’s some stuff I thought and learned:

  • Django has amazingly good documentation. That tutorial is fantastically written, clear and concise and elaborating where necessary. And an actively interesting toy app, it’s not just a dumb toy.
  • The polish is very good. Everything worked just as described with no weirdness. I particularly like that sqlite was the default database, that’s the right place to start for learning.
  • The distinction between a “project” and an “application”seems like needless complexity. The theory is that a single Django project instance might contain a mix of several independent applications. I wonder if that’s done in practice? I suppose so right away, the default project has the admin, auth, contenttypes, sessions, messages, and staticfiles projects. I wonder if many Django projects contain multiple third party / homegrown applications?
  • If you use the wizard to make an application and a project you end up with 12 files and 185 lines of text. I’m not a fan of codegen, it usually betrays an unpleasant complexity, but it’s not too bad in this case. The only big file is settings.py and that’s basically a declarative setting of what’s included in the project. That’s gotta go somewhere.
  • The good thing about Django is it comes with its own ORM and HTML template system. The bad thing is end up using their ORM and HTML templates. I don’t have enough experience with them to have an opinion other than some initial crankypants reactions.
  • The data model / migration / database agnostic stuff is pretty slick. I wonder if it works in practice.
  • I hate choosing between CamelCase and underscore_separation and forcedlowercase. The latter is particularly alarming; my database table names seem to be coerced downcase. Perhaps that’s a compatibility thing?
  • The auto-reloading of code is nice.
  • It appears that Django has no favored CSS UI framework. I imagine it’s easy to drop in Bootstrap or whatever, but part of me was hoping for some default styles that would make it easy to make things that look OK.

I ended up having 7 files open in my editor

  • project/settings.py to register my app
  • project/urls.py to register my app’s urls,
  • app/admin.py to register my models
  • app/models.py to define my data model
  • app/urls.py to define my webapp URLs
  • app/views.py to define my webapp views in response to URLs
  • app/templates/app/index.html as an HTML template for my view

Those first three files feel like make-work but the other four are actual real code I care about. That’s pretty good!

Overall I’m pretty pleased so far. I already know the pitfalls of going down this road, the way an ORM can betray you on performance in heavy traffic situations. But that’s not a road I’m worried about right now, and if I do ever get there I’m guessing there are ways to build special hacks bridges around the ORM overhead.

 

MacOS third party graphics drivers

I did something I never thought I’d do and installed third party graphics drivers for my Mac, which has an NVIDIA GeForce GTX 660M graphics card. I was motivated to do that because the new game Stellaris was crashing frequently. The cargo cult advice for another game from the same publisher was that the third party drivers seem to have helped and I’ll be damned, they do.

NVIDIA couldn’t make it more confusing what these drivers are for, saying “This driver update is for Mac Pro 5,1 (2010), Mac Pro 4,1 (2009) and Mac Pro 3,1 (2008) users.” I don’t have some ancient Mac Pro with a video card, I have a modern iMac with a stock apple GPU. But the fine print indicates that really these drivers are for pretty much any Mac with an NVIDIA GPU. Also it’s called the “Web Driver”, which is an insane name for a kernel module. Note that there’s no index for all NVIDIA releases; you have to go this reseller page to find all the versions. And don’t be confused by the CUDA drivers; those are for high end number crunching, not graphics and gaming.

The installer seems well behaved. Worked fine on reboot for me, and the drivers have only seemed to be an improvement so far. Also it includes a control panel where you can switch back to the default MacOS drivers or uninstall the NVIDIA stuff entirely.

No idea what’s going on with Apple and MacOS that the stock El Capitan drivers aren’t good enough. Or with Paradox, the game publisher, that their games are sold for Macs without testing on standard machine configs. The whole point of paying the Apple premium is this stuff is supposed to work out of the box.

Update Dec 2016: the NVidia drivers are responsible for some graphics lag in League of Legends. With them installed, when Thresh drops a lantern my FPS drops from a solid 60 to 45 FPS or so. With the stock OS X drivers there’s no FPS drop. I don’t know if this is a bug in LoL or the drivers or an unfortunate interaction between the two. It may also be related to vsync.

sqlite: Unix epoch times

I store all my timestamps in the Unix epoch, as Thompson and Ritchie decreed. sqlite doesn’t really have a date type, instead it has date functions that can work with text or numbers. Unfortunately the numbers are defined with respect to two different epochs.

sqlite’s preferred date format is “Julian day”. This is a floating point number, the number of days since November 24, 4714 B.C., with hours/minutes/seconds being reported in fractional. Ie right now it’s 2457524.189894016. A single second is roughly .00001 in this time scale. sqlite3 reals are 64 bit, so we get 2^52 days or about 140M years of dates where individual seconds have distinguishable timestamps. No practical maximum :-P

Unix and Javascript’s preferred date format is an integer, seconds since Jan 1 1970. Right now it’s 1463330612. Unix times are generally 32 bits and therefore limited to the range of 1970–2038, although we’re all hoping we’ll see an extension to 64 bits before the apocalypse. sqlite3 already seems to have extended support and notes it will work on Unix dates from 0000 to 5352. The sqlite functions also seem to be OK with real number Unix epoch timestamps, with the fraction naming subseconds.

The thing that’s confusing is the sqlite functions like date and strftime operate on Julian day numbers by default. If you want calculations in the Unix epoch instead, you have to pass the flag ‘unixepoch’ to the function.

Some examples:

-- Julian days
select julianday('now');
2457524.19912943
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 2457524.19912943);
2016-05-15 16:46:44.783  Julian:2457524.199129433  Unix:1463330804

-- Unix epoch
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 1463330612, 'unixepoch');
2016-05-15 16:43:32.000  Julian:2457524.196898148  Unix:1463330612
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 1463330612.34, 'unixepoch');
2016-05-15 16:43:32.340  Julian:2457524.196902083  Unix:1463330612
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 0, 'unixepoch');
1970-01-01 00:00:00.000  Julian:2440587.5  Unix:0

-- Max sqlite Unix epoch
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 106750000000, 'unixepoch');
5352-10-09 09:46:40.000  Julian:3676119.907407407  Unix:106750000000
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 106760000000, 'unixepoch');
-141-03-01 13:07:12.700  Julian:1205032.046674768  Unix:-106751991168

-- Gotcha with 'now' and Unix epoch
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 'now', 'unixepoch');
1970-01-29 10:38:44.197  Julian:2440615.943567095  Unix:2457524

That last example is confusing; the time stamp ‘now’ is always the Julian day, even in the context of Unix epoch conversions. So it makes no sense to mix ‘now’ and ‘unixepoch’. I’m sure that’s the source of surprising bugs.

I’m not clear why the year 5352, integer 106750000000 is about the limit of sqlite’s Unix date implementation. That number is about 2^36.635, so it’s not some obvious integer rounding problem. Probably doing calendar arithmetic in floating point somewhere?

Stack traces from running Python programs

My lolslackbot program occasionally hangs forever and I’d like to know what failed when I kill it. Starting with Python 3.3 it’s relatively easy using the faulthandler built-in library. You have to set it up ahead of time (it’s not on by default), but once you do you can send the process a SIGABRT and it will display a slightly spartan stack trace and abort the program.

You can get a stack trace without killing the Python process by registering another signal, like faulthandler.register(signal.SIGUSR1). That signal is not entirely unobtrusive; it interrupts time.sleep() for instance. But the program does seem to keep running after printing the stack trace. All the signals registered by default seem to also kill your program; USR1 won’t. (Unless I’m confused.)

It’s all implemented in C to enable printing useful stack traces even if the Python VM itself is broken. Also you can enable it just by setting an environment variable, before any Python code is run, which I imagine is useful for debugging problems at startup.

There’s also an interesting faulthandler.dump_traceback_later() function which seems to basically be a watchdog. It sets a timeout with a separate thread that results in a stack trace dump and, optionally, your program exiting. It calls _exit() which is the hard exit, which has pluses and minuses.

It’s sure a lot easier than the only other way I knew to do this, which was to attach gdb and inspect the interpreter’s state. But I wish it were enabled by default like Java’s old built-in behavior on SIGQUIT (Ctrl-\). Maybe they were afraid it was too radical a backwards-incompatible change.

180 new lolslackbot users

I just set up lolslackbot for Learning Fives Session 2. Some 180 new users. Kind of an exciting day for me, before I only had 30 or so users.

My test infrastructure continues to pay off in spades. All sorts of firsts today. First time running with users a new region (Latin America). First time where I got a game where all 10 people were in my cohort I was tracking. Etc. And AFAICT it all worked as intended. Really no problems running it other than some scutwork and some unintended consequences.

The scut work is I still have no UI for administering users in my system. I spent half of today writing 150 lines of Python + tests to set up the new users. I have to create entries in five tables: People, Groups, Channels are all primary data entities, I also have “GroupMembership” and “Subscriptions” which are basically tables joining IDs from other tables. And all this crap is injected with command line tools. I do have scripts to at least populate them from CSV and JSON datafiles, it’s not raw SQL, but it’s close.

I really need a proper web GUI for editing these data entities, regrettably in Django, and I’m still dragging my feet on taking that leap. I have an idea for a new product I can do in Django though, a quick spike for something related to the existing code

The unintended consequences is I neglected to account for how unusual this first run would be after the import. Basically I was catching up, getting info on past games those 180 new users played. It took 15 minutes to download 10 match records for each of my 180 new users. And then that generated 177 messages which it immediately delivered, in a few cases spamming 10+ messages to a Slack channel. Those messages were all correct in some sense, but in retrospect it would have been better to suppress the past and only start delivering new messages instead. Oops.

MacOS unzip is ancient and busted

Tracked down an OpenAddresses problem with our primary data product, a 3GB zip file. MacOS unzip can’t unzip it, producing errors like this:

skipping: us/il/macon.vrt         need PK compat. v4.5 (can do v2.1)

The underlying problem is MacOS El Capitan (10.11.4) distributed the ancient unzip version UnZip 5.52 of 28 February 2005. This version does not work correctly on files > 2GB big. The usual recommended solution is to install p7zip via Homebrew and use that to unzip the big archive. A lower impact option is to install the Homebrew dupe for unzip, which is UnZip 6.00 of 20 April 2009. That’s a bit awkward since being a dupe, Homebrew won’t symlink the binaries by default.

This is not the first time I’ve wasted working around Apple’s awkward user space tools. The less file reader is also an outdated version, and last I checked was compiled with weird options like not respecting the LESSKEY environment variable.

I really should just stick to Ubuntu.

date +%s

Sharing a quick hack I use all the time

while :; do
  wget -q -O `date +%s.json` example.com/data.json
  sleep 60
done

Very simple shell hackery to download a URL once a minute and save it in a file named with a timestamp. The only midly subtle thing there is date +%s: that is a date format which is seconds since epoch, which is a conveniently sortable thing for filenames and timestamps and stuff.

(The while : instead of while true is idiosyncratic and anciently historical. In some very bizarre contexts true is the program /bin/true, the : is always a builtin.)

I have a bad habit of leaving scripts like the above running and forgetting about them, only to come back to a directory with 100,000 files in it.

 

Things I learned about systemd

systemd is the Linux startup system for Ubuntu 16.04, so I figured it’s time I learned about it. I’m very late to the party; systemd started some 6 years ago and became a real thing many Linux distributions used years ago. Ubuntu is the last big distro to include it by default except Gentoo, and even Ubuntu switched last year with 15.

There’s been a years-long debate in the Linux community about systemd. A younger me would have cared about that, maybe participated. These days I don’t care, I just want to use the consensus tech. The bummer is the flamewars dominate the conversation, it’s hard to learn just what systemd is. Here’s my effort to just understand it.

Disclaimer:  I’m not an expert and have undoubtedly made a mistake here somewhere. I reiterate my reminder that I really only write this blog as notes for myself. You’re welcome to comment, but please don’t waste my time with heated opinions.

References

I don’t have more links on actually using systemd in practice because I don’t yet have a system running it myself. That’s how out of date I am. The key pragmatic thing seems to be the unit files which configure how systemd launches services. systemd can also still launch stuff with old SysVInit-style scripts, including parsing the LSB headers.

Stuff I learned

systemd is init, the first user process on a Linux system, PID #1. Once the kernel is done it runs PID 1 whose job it is to then run all the other user stuff that makes a Unix system; mounting filesystems, configuring networking, starting daemons, etc.

The init most of us know is SysVInit, the shell scripts in /etc/rc.d. It hasn’t aged well in a modern era of multiple cores, dynamic devices, etc. Upstart is another Linux init system that Ubuntu has used for a long time, but no one seems to love it. Launchd is the MacOS init and deserves some respect for its speed and power; the systemd authors explicitly acknowledge launchd for inspiration.

systemd is a full rewrite of the idea of init. The primary goal seems to be mostly about efficiency. In the bad old days a Unix system could take 90 seconds to boot. With systemd (and MacOS launchd) < 1 second is possible and < 10 seconds is common. systemd is faster because it can do things in parallel. Also it avoids all the overhead of interpreting shell scripts. And supposedly it’s just modern and new and “better”, which I can’t really evaluate but can believe given the mess of stuff that preceded systemd.

systemd is Linux-only. It uses a bunch of non-POSIX APIs to do things like work with devices, configure security capabilities, etc.

I still haven’t used systemd hands-on so I haven’t learned much else. But my understanding is a whole bunch of Unix config gets consolidated into unit files in one place, which then tells systemd how to configure and launch user space programs.

I’m a little terrified of the Ubuntu 14 to 16 upgrade, it has to replace all the old stuff with the new. Will it work? Particularly reminded of an Ubuntu 12 to 14 upgrade I did where I manually installed something that changed the name of my ethernet device, making the machine unable to reboot with networking. Oops.

Opinions

I really don’t care about the history of the controversy; systemd’s a fait accompli. But it’s helpful to look at the debate to understand better what systemd is.

The big complaint about systemd everyone has is complexity. It does a lot of stuff in one big nest of 60+ interlocking binaries. It’s not just forking daemons. It’s got udev inside it to manage devices. It’s got its own logging system (in a binary format), a cron equivalent, an inetd equivalent, an atd equivalent, virtual terminals, a login daemon, watchdogs, etc. When you look at all the old Unix software that’s replaced it’s sort of astonishing and I can understand why believers in the “lots of little tools” philosophy don’t like it.

OTOH, the way the old components fit together in sysvinit was quite a hairball too. The shell hackery required to mount devices, then filesystems, then get networking up so you could access other filesystems and start other daemons in the right order and blah blah blah. Sure udev and mount might have been separate software, but they could only run correctly in one specific relationship to each other. That complex set of interdependencies had a lot of cost and somewhat made a lie of “lots of little tools”. Also there’s something to be said for unifying init and cron and inetd and login and the like; they’re all about launching programs in response to events, why not share the code?

There’s still a cultural concern that systemd, being a monolithic project, comes from one mindset only. Some of the choices seem odd to me; a binary log format for instance. That’s the part of the debate I can cheerfully withdraw from. For whatever reason most Linux distros have agreed on using systemd, and I trust that they all have the influence to shape it the way they need. That seems like a reasonable path to working software.

 

freedns annoyance

I’ve been using freedns.afraid.org for years for dynamic DNS, to access my home machines on dynamic IP addresses. Nice little service, valuable but not quite valuable enough to be paying money for.

Or so I thought. They have a thing where my domain name gets marked “dormant” and they change the DNS records to point to a static advertising site. I have to log in again to say “no I’m really using this still”, then wait for the one hour TTL expiration for things to work again. Ugh. Shades of DynDNS, the slow decline from being a useful free service to being crap.

I get it, they want to make money on me, OK. But their business goals are so modest it seems odd to inconvenience 2,500,000 free users in hopes of signing up 1000. Verification is useful; maybe they need to somehow clear out old unused names. Just wish there were some better way than “we broke your name good luck!”. Like a reminder email or something. The news page from 4 years ago says he’s working on a graceful notification. Guess that didn’t work out. (They seem to have been sending emails at one time but I’ve never seen one.)

The other DNS host I use is Hover, as part of their domain registry. They still don’t support any dynamic IP option.

Machine Learning study

My old colleague Karl Rosaen is taking time off from working to study Machine Learning. He’s meticulously documenting his curriculum and day to day work, good resources there.

One big part of Karl’s studying is Raschka’s book Python Machine Learning. It looks like a nicely practical book, I was looking for something like that last year and it wasn’t quite out yet. His example code is online. And his blog post about writing it is nice.

My biggest regret from my machine learning work is not applying it to real problems. Karl mentions that the Kaggle competitions are a good set of problems and datasets to work on.

wordpress.com code bug

I like posting source code on my blog. Wordpress.com has a bug where it re-escapes my code every time I edit it. I am creating this blog post to file a support ticket, because I’m now a paying customer.

The code I want to post is the Python code

int(“1”) & 2

Ie; take the string 1, cast it to an int, then bitwise and it with the integer 2. I chose this because both the ” and & may get HTML escaped.

I’m following these instructions for posting code. Note they dont’ tell you which editor mode to do this in; Visual or HTML mode. I’m going to do both.

Both of these displayed correctly the first time. But the moment I edited the post again and saved it, it escaped the ” to be &quot; and the & to be &amp; It will keep adding more escaping every time I edit it. It’s very annoying.

Visual mode

int(&amp;quot;1&amp;quot;) &amp;amp; 2

HTML Mode

int(&amp;quot;1&amp;quot;) &amp;amp; 2

Notes

This bug is 4+ years old and yet still with us and seems to have been carried over to WordPress’ new visual editor, Calypso. I suspect they’re doing something naive like re-escaping every single time the editor switches modes. I tried asking wordpress.com front line support and just got a “need to look into this more” reply with a promise of an email followup.

Update: got a reply from support saying it was a known issue they were looking into and that “For now the solution is to stick to the HTML editor when writing code in blocks.” Well, that’s clear. I wonder if any of Wordpress’ own engineers use Wordpress to blog about code? Doesn’t this drive them crazy?

Sending SMTP email: a decade approach

I decided it’d be handy to be able to send SMTP email from my server in a datacenter. You know, like we’ve done since 1982? Only in modern times it really sucks to do this because of protections against spam, email spoofing, etc. Also I don’t want some giant network mail thing running and creating security headaches, I just want to be able to send mail off-host.

It turned out to be easy on Ubuntu 14.04. I followed this guide which boils down to “configure Postfix to be an Internet site, then make the daemon only listen on the loopback interface”. The other setup that’s important is a PTR record, so reverse DNS works. I think even without that mail should in theory work, but everyone might assume you’re a spammer.

With that setup mail to me @gmail.com worked and I’m sending email like we did back in the 1980s. But it also got classified as spam, and monkey.org was refusing to talk to me at all. The problem turned out to be that postfix was configured to use the hostname “ubuntu”. I fixed it by using the same FQDN as the PTR record (which also resolves to the same IP). Both Gmail and monkey.org will deliver my mail and it shows up as non-spam.

So now we’re up to 1990s email. Still, Gmail complained the mail it got was unencrypted. That was fixed by enabling “smtp_tls_security_level = may”. No idea why that’s not the default; the Postfix docs warn “You also turn on thousands and thousands of lines of OpenSSL library code. Assuming that OpenSSL is written as carefully as Wietse’s own code, every 1000 lines introduce one additional bug into Postfix.”. Which is a bit snide but fair enough given the OpenSSL history.

And now we’re up to 2000s email. Our modern era is much more complicated, with SPF and DKIM and other half-assed DNS based solutions to making email a bit more authenticated, but not really fixing it entirely. Those measures don’t yet seem mandatory, at least for low volume email, so I don’t yet have 2010s email configured.

One thing I left unsolved; the From: address. Mail is showing up as being from “nelson@wk.somebits.com”, which is an address you can’t deliver to. I’m OK with that, could fix it by spoofing the email, changing the Postfix from header, and/or adding MX records to enable mail for somebits.com.

(The other option to all this falderall is to give up on SMTP and mailer daemons entirely, just use a proprietary mail API. GMail has something for sending mail based on OAuth, and Amazon has SES.)

MacOS 10.9 to 10.11 upgrade

I upgraded my 2011 iMac from Mavericks to El Capitan. Partly on a whim, partly because a lot of apps no longer work with 10.9. Mostly pleased with the result, Apple really does a nice job on not breaking systems on upgrades, migrations, etc. Still some notes:

  • Apple removed my fucking software. As part of the new security model Apple decided it was OK to delete all my files in /usr it didn’t approve of. Including my Homebrew install. Thanks, Apple! I found my purloined programs in /Library/SystemMigration/History/. I was going to rebuild Homebrew anyway because reasons, so meh, but... Weird to also find stuff from /System put there, stuff I never created.
  • MenuMeters broke. No surprise, it was using a weird hack. There’s a port of MenuMeters to 10.11 which works fine and no longer needs the hack, at the expense of losing the ability to rearrange the menu bar.
  • Seil didn’t break! That’s a funky kernel driver that lets me override CapsLock, was sure it was going to stop working.
  • I can no longer move the Dock to a corner. Thanks Apple.
  • The alt-tab popup  now shows on my secondary monitor. Apparently it shows up where the Dock is. I want the Dock on my secondary, but the Alt-Tab on my primary along with the menu bar. Sources: 1, 2
  • League of Legends isn’t running completely smoothly. I see occasional 0.1s pauses. It’s not unplayable, but it’s not right. It’s mysterious, not easy to reproduce / isolate.
  • Ever since my iMac got a hardware repair something made noise in the case when high contrast stuff scrolled on the screen. Weird, I know, I assumed it meant something wasn’t properly shielded anymore and EM was leaking into the speakers. That problem is now gone!?
  • Every time I plug in my phone to charge it, the unwanted Photos app launches. Found a solution which requires running the photos app enough to uncheck a thing. Remember when Microsoft used to exploit their operating system to promote their other products and everyone got angry, up to the federal government? Why does Apple get away with even more aggressive self-promotion?
  • my sshd stopped running. I had to renable it via Sharing Preferences
  • Despite the trend to flat design, Yosemite added some tacky transparency effect that makes menus harder to read. Here’s how to disable it.

Homebrew. For my own notes, the output of “brew leaves” from my old system. I’m installing fewer of these things; in particular no octave or gcc. Installing this time to /usr/local/homebrew. I don’t like it installing in /usr/local/bin, etc; been burned by that going wrong.

bash-completion bcrypt clens cloc cloog duti exiftags fdupes ffmpeg
homebrew/fuse/fuse4x gcc homebrew/science/ggobi gist git grc icu4c
iftop iperf iperf3 jbig2dec jq homebrew/dupes/less homebrew/dupes/libpcap
libvo-aacenc mg mobile-shell mp4v2 mtr nmap node homebrew/science/octave
optipng ossp-uuid p7zip par2 pgdbf postgis pv pyqt python python3
q homebrew/dupes/rsync s3cmd homebrew/fuse/s3fs sshuttle unison
unrar wget wireshark

Packages to install this time:

bash-completion bcrypt exiftags ffmpeg gist git grc iftop iperf iperf3 jq homebrew/dupes/less mg mp4v2 mtr nmap optipng p7zip par2 pgdbf postgis pv homebrew/dupes/rsync s3cmd unison unrar wget

Everything installed with no drama except for postgresql (and postgis). It has some bug building in Homebrew related to libreadline and doesn’t seem to build with just the command line tools. Installing the full Xcode via the App Store fixed it.

osxfuse and sshfs didn’t install right via brew cask; simpler to download the installers and run them myself.

TinyDB: is this sqlite for JSON?

Awhile back I wanted sqlite for JSON, some simple file-based JSON document store with a basic query interface. TinyDB looks promising. It’s a Python library. It lets you stuff a bunch of JSON documents into a file database and then query them. The query language is pretty simple, mostly “documents that have property X”, but that’s fine. The underlying file format looks like one giant JSON blob and may not be very efficient for updates, not sure.

I’ve used the JSON1 support in sqlite now. It’s pretty good.

I sure wish it were easy to marry jq to some simple JSON document store.

 

champion.gg and BSON data

A potential League of Legends nerdy project; analyze stats from games to determine which items are winning the most. champion.gg is an excellent site for stats like this, but it’s reports are focussed on champions. Which champion wins the most? What items do they build?

I want to know what items win the most. There’s a theory that Iceborn Gauntlet and Sunfire Cape are both overpowered right now, for instance. Has the win rates for people who buy those items gone up in the past month? I think that’s a well defined question.

Unfortunately champion.gg doesn’t answer it. But the website is open source, and the author even kindly publishes analyzed data blobs. Still not sure it has quite everything I need to do my item analysis, but it has potential

The data is in bson format. Here’s a quick and dirty way to extract, say, the data that is presented on this page

bsondump webchampionpages.bson | \
jq '. | select(.key=="Janna")' | less

2016 Python webapps

I want to build a webapp for my lolslackbot project. What do I use?

Django is the clear consensus choice for large, grownup projects. I used it once a couple years back and thought it was fairly good, if not exciting or lovely. But I have in the back of my head the Django ORM doesn’t play nice with homegrown schemas, that it really wants to control the schema itself. Also I have the impression that Django is kind of big and clunky, although maybe that’s unfair.

The cool kids all use Flask. I like the idea of a microframework, something simple. Flask doesn’t inspire a lot of confidence though. The last release is 0.10.1, released nearly three years ago. And while Python 3 is supported its use is discouraged. That may have made sense in 2013 but it’s a backward opinion in 2016 (IMHO). (The author reiterated that opinion as much as 8 months ago.) OTOH my friends who use Flask say not to worry about it, that it works fine with Python 3 and it’s simple.

Only no one just uses Flask. They combine it with Jinja2 templates, and WTForms, and SQLAlchemy for an ORM. Add in logins, sessions, and some CSS frameworks and you’re looking at a lot of software. Is it better to glue together your own custom assemblage of small components or should you just use a full framework like Django?

Full Stack Python has some useful advice.

My friend Brad G. recommended starting with cookiecutter-flask as a set of components + structure and customize from there. Man, it’s been years since I used a Visual Studio wizard! It looks like a good way to get up and running though.

Successfully installed Blinker-1.4 Flask-0.10.1 Flask-Assets-0.11 Flask-Bcrypt-0.7.1 Flask-Cache-0.13.1 Flask-DebugToolbar-0.10.0 Flask-Login-0.3.2 Flask-Migrate-1.8.0 Flask-SQLAlchemy-2.1 Flask-Script-2.0.5 Flask-WTF-0.12 Mako-1.0.4 SQLAlchemy-1.0.12 WTForms-2.1 WebOb-1.6.0 WebTest-2.0.20 Werkzeug-0.11.4 alembic-0.8.6 bcrypt-2.0.0 beautifulsoup4-4.4.1 cffi-1.5.2 cssmin-0.2.0 factory-boy-2.6.1 fake-factory-0.5.7 flake8-2.5.4 flake8-blind-except-0.1.0 flake8-debugger-1.4.0 flake8-docstrings-0.2.5 flake8-isort-1.2 flake8-quotes-0.2.4 gunicorn-19.4.5 isort-4.2.2 itsdangerous-0.24 jsmin-2.2.1 mccabe-0.4.0 pep257-0.7.0 pep8-1.7.0 pep8-naming-0.3.3 psycopg2-2.6.1 py-1.4.31 pycparser-2.14 pyflakes-1.0.0 pytest-2.9.0 python-editor-1.0 setuptools-20.2.2 testfixtures-4.9.1 waitress-0.8.10 webassets-0.11.1 wheel-0.29.0

Thinking for real about a webapp is making me once again consider whether SQLite is a good choice going forward. The lack of fine grained locks is going to make multiple writers unacceptable. I sure wish it had per-table locking, that would probably be good enough for now.

Simple app metrics: stathat

I’m looking for some simple application metrics. I want to track some basic things like “time it takes to make an API call” and maybe “number of interesting events over time”. The big boys awhile back converged on statsd + graphite for this, or now Grafana, and those are great technologies. They’re also too complicated for my little project. I just want something simple that will work. And hopefully nicer than rrdtool+mrtg :-/

Ian D recommended StatHat so I gave it a try. It’s pretty nice. You make REST HTTP calls giving it data and it aggregates the data and makes reports. It’s pretty basic, but then it’s simple to use and requires no extra work on my part.

The biggest drawback is that it requires an HTTP call in your app, which tends to be synchronous. The supplied client libraries don’t even have timeouts! I think this can be worked around with some async or thread implementation, or maybe even an offline stats collector, but there was nothing off the shelf.

I also found posting one stat value at a time with an HTTP call is very slow. I was able to post approximately 8 records a second. And I think that’s using HTTP keepalives! Fortunately there’s a bulk import API using JSON that is much faster; about 999x faster if I insert 1000 records at a time.

Data records have an optional timestamp. Those have to be an integer. If you pass in a floating point with milliseconds like 1460076429.905 it will be silently ignored and the data will be timestamped with the current clock time instead.

The biggest problem I’ve run into is that my data is getting lost. It looks just fine when I import it, then an hour or two later my data is gone. I’ve written asking if this is something I’m doing wrong. Update: my data reappeared. There’s some confusing things that happen around updates, etc, maybe the consistency is just eventual.

Here’s a sample report. The number being measured is the milliseconds it takes for Riot’s Web API to answer a request. This tells me the average time is 320ms and it spiked around 9AM. The reported min, max, 95% and 99% don’t seem correct to me, but maybe those are describing the averages in 15 minute windows instead of individual events. (Which makes it less useful).

It’s a neat product though. I may stick with it if I can figure out the data loss problem. Sure beats setting up some complicated stuff myself.

Screen Shot 2016-04-08 at 3.26.45 PM.png

Update: I’m using stathat in production now and am very happy with it. I just collect all the stats I care about in memory during a run of my job, then post them all at the end with a 10 second HTTP timeout. Seems to work just fine. The disappearing data problem seems to only be a temporary quirk in an initial bulk import, hasn’t been an issue since. And it’s really nice having the charts!

Python3: no len() for iterators

Python 3 has an odd oversight; there’s no function for finding the length of an iterable. You can do len(aList) of course, and len(aTuple). But there’s no len(anIterator). What’s really surprising is there’s no itertools.len(anIterator), some function implementation.

The naive solution is len(tuple(anIterator)). But that’s inefficient because it constructs a tuple in memory. This discussion suggests sum(1 for e in anIterator), which if I understand generators correctly should be pretty efficient and involve no allocation of new collections. Surprised this function isn’t in itertools.

Update: see also cardinality.count() for a clever faster implementation.

Update 2: I had some yak-shaving time, so I made an iPython notebook timing three different solutions for counting the length of an iterable.

  •  1x: len of tuple of iterable
  •  7x: deque an enumerate of iterable
  • 11x: sum 1 over the iterable

The results are roughly the same for iterables of size 1000 to 1,000,000 to 100,000,000 and hold whether the iterable is a list or an ephemeral itertools iterable.

What’s astonishing is how much faster the len(tuple(iterable)) method is than the others. Naively it should be slower, it’s doing a lot more work building that tuple in memory. But perhaps this is a highly optimized codepath in Python. The tradeoff is it temporarily allocates memory to consume the whole iterable, so it’s using O(n) memory compared to the O(1) memory for the other solutions.

A library of trained machine learning models?

I wonder if machine learning is mature enough that people can start sharing trained classifiers? Ie: instead of training neural networks to do character recognition yet again, why not just download the consensus Recognizer library that everyone uses and just apply it? The question is deliberately provocative.

I think applied machine learning may not be mature enough to support standard library usage. What does it mean to “download a trained model”? Models are expressed in terms of specific software libraries; sklearn, TensorFlow, whatever. Probably specific to minor version releases of those libraries, for that matter.

Also every machine learning application I’ve seen is highly customized to the specific task. it’s never as simple as “recognize characters in an image”, it’s always carefully tuned to the specific source of images (ie: camera artifacts, etc). And the use of the outputs: numbers only, English text only, with confidence intervals or without. And the larger context of use: are you recognizing zip codes on an envelope? Turning scanned documents into text? Breaking CAPTCHAs?

Also the whole idea of “consensus software library” is pretty rough sledding even in traditional instances. I mean we can’t even agree on a common malloc(), or a common regexp recognizer.. OTOH some things are highly standardized, like compressors or crypto libraries or the like.

The idea of “open source” on a trained model is also a bit wonky. There’s not really source code you can read in a trained model; it’s not like I’m going to read a diff of neural network weights and learn anything about the submitted patch. So maybe the source code open source artifact is the program that does the learning along with the training set, and you also distribute the trained model output as a sort of pre-compiled convenience.

(Inspired by reading this post, in which a student builds a classifier for American  name gender. It’s a very nice exercise but it got me wondering; if I really want a gender classifier, why can’t I just download one some expert already built and tested?)

Update: with many thanks to the awesome Julia Evens, I’ve learned that Caffe, an image processing machine learning project, has explicit support for sharing trained models. Here’s her blog post about playing around with a trained image recognizer.

youtube-dl for music playlists

Google has amassed the world’s greatest library of music. Here’s how to download the music from a playlist nicely if you’re not worried about licensing questions:

youtube-dl -o ‘%(autonumber)s-%(title)s-%(id)s.%(ext)s’ -f 140 PLAYLIST-URL

The -o option names the file something nice. Note I left the youtube ID in there so you could find the file again.

The -f 140 option means download the 128kbps AAC audio stream only. There may be higher quality audio available but this sounds fine to my tin ear, also it seems to work with absolutely everything.

I tried --write-thumbnail for nice album covers in the files but it seems to only write the image as a second file, not into the m4a metadata. I’ve also had bad luck trying to use command line tools to add metadata to the m4a file afterwards, stuff like artist or whatever. Ended up corrupting the files. I didn’t try very hard.

 

NTP surveys

Way back in 1999 I did a survey of NTP. I spidered the whole Internet’s collection of NTP servers and published some statistics. From a desktop Linux box in my office at MIT, without permission, which raised a few eyebrows. But it was the 90s Internet and it was awesome.

These days NTP is much more widely deployed. It’s also been the cause of some security exploits and DDOS traffic, so I fear my kind of survey is much harder to do now. But I get requests about it occasionally, I think mostly from students. Here’s an email of answers I just sent today. Shodan’s view of NTP servers looks like an interesting place to start.

First of all,you use ntpq or ntpdc to do the query,is there any other method to do that now?

I mostly used ntpdc for access to the “monlist” command, which shows clients who are asking for the time (ie: downstream links). Both ntpq and ntpdc support “peers” to show where this particular server is asking for time (ie: upstream links). I also have used ntpdate to just query the time.

Secondly considering the Internet security,most of hosts are behind the firewalls,can the final result actually reflect to the true conditions?

Yes, you are right. It was a concern in 1999 when I did my survey and it’s only gotten much worse. I wonder now whether a survey like I did is even possible. There have been several high-profile security problems with NTP in the past few years, including an exploit in ntpd using monlist. Also NTP queries can be used for DDOS queries. The net result is that most servers are much more secure now and may not answer anything other than a basic “what time is it” query. Also I suspect a survey like mine would set off many alarms.

Finally,can I conduct the survey on a computer running Windows operating system?Can you give me some suggestions?

It should be possible on Windows, but I’m not sure how to do it. You want some way to make ~100 NTP requests simultaneously. It’s pretty easy since it’s just a UDP protocol, but I don’t know the best way to do that on Windows.
Two other things you should look into:
The NTP Pool is where most Internet clients get their time today. There’s about 4000 servers total and I’m sure there are plenty of opportunities to survey and research just those servers. The NTP pool developer community is friendly, you should talk to them before doing any significant survey work.
These days it is relatively easy to query every single IPv4 address in the world, all 4 billion of them. One site that does this regularly is Shodan. For example, here is their search result showing 835,000 NTP servers: https://www.shodan.io/search?query=ntp

Python packaging in March 2016

Hooray! I finally finished porting my lolslacktest code over to be a proper Python module, installable with pip, and with a virtual environment. What a pain! Some notes on what I learned. But first, some reflection.

This project has been one of the least fun things I’ve done in a long time. I can tell by the way I’ve been foot dragging. It’s confusing and hard to debug packages. The docs are inconsistent and suffer from years of accretion. Some things are genuinely confusing, like Python’s surprise lack of support for circular imports. And in the end result is my product works just like it did before. No user visible changes. Behind the scenes things are better; the install is cleaner, I have a virtual environment for proper external dependencies, etc. But nothing fun, just slightly less crappy ops.

The state of the art for Python Packaging

As of March 2016 the Python 3 state of the art for package installation is pip, pyvenv, and setuptools. pyvenv and pip comes with Python 3.4 but setuptools is still extra. (On Ubuntu you have to install python3.4-venv with apt.)

The state of the art for managing Python packages keeps changing. This Stack answer explains the landscape as of September 2014. This packaging user guide is updated as of September 2015 and is mostly very good, but even it references things that don’t work such as “python setup.py bdist_wheel”. I also found this guide useful but it was mostly written in 2012 (although occasionally updated).

The pip installed by python 3.4 (Ubuntu) is version 1.5.4, you want version 8.0 or later if you want to do things like install gevent with a precompiled wheel file. setuptools is old too. So first thing you should do after setting up a pyvenv is “pip install -U pip setuptools”.

The setuptools docs are not very good. They assume you know how distutils works. Also they spend a lot of time talking about easy_install and none at all talking about pip.

Honestly all this Python packaging stuff is a big mess, I feel like you have to understand the history to be able to use the current state of the art. It’s a shame Distutils2 didn’t work out for Python 3.3 and rationalize it all. To be fair, packaging in almost every system sucks: npm, rvm, homebrew, they’re all a mess. All but my beloved apt, and that’s because the Ubuntu package management team works super hard.

Some hacks and code things

I had to do a few hacks and other things to make my project work.

The biggest code change was just wholesale replacing absolute imports like “import lib” with relative imports “from . import lib”. I think that’s actually correct, but I was doing it kind of blind for every single file.

I had to modify my code because Python really doesn’t support circular import dependencies. You don’t really notice until you are using relative imports. The accepted solution for circular imports is to break the circularity, refactor code. Screw that. My workaround was to move some of the import statements inside functions, so they execute at run time and not import time. That’s bad and inefficient but expedient.

There’s two similar-looking ways for a Python package to specify dependencies. You can add an install_requires stanza to your setuptools setup() method, or you can use pip to install a bunch of stuff listed in a requirements.txt file. The setup() dependencies are installed automatically when a package is installed, but nothing installs requirements.txt automatically. OTOH the requirements.txt option is more powerful, for instance pip can install things from github URLs whereas setuptools can’t. (The setuptools docs say you can do this with dependency_links, but I couldn’t make it work.) I’ve ended up using a mix of both, preferring setuptools where I can.

I have some shell scripts named in the “scripts” section of my setup.py, so they are installed in the virtualenv bin directory. But I want them to work even if the virtualenv isn’t activated, so those scripts have to source their own virtualenv. Mostly for execution in cron; getting cron to activate a virtualenv is not easy. The hack I did for this was this shim of code at the top of each script:

VENVDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $VENVDIR/activate

The bash magic in the first line sets VENVDIR to be the directory where the bash script itself is. Conveniently, that’s the same directory that has the activate script.

I have no idea how to put version numbers on my program. It’s a private thing only I’m installing, so for now I’m going with the dbschema version. Part of me wants to just put the git commit nonce there.

My deploy script used to be rsync from dev to prod. Now it’s sshing into prod and having it do a “git pull” followed by “pip install -U”. I took this approach at migurski’s suggestion. It means I’m not using any of the fancy distribution builds and versioning stuff that setuptools/pip enables. But I don’t really need those right now, they make more sense for public code hosted at PyPI

Note to self: you can’t move a pyvenv environment once its created. They have paths hard coded.

 

 

Xiaomi Yi Action Camera notes

I bought a Xiaomi Yi camera. It’s a GoPro-knockoff, a small HD camera that takes amazing high quality video and is only $70. Unfortunately it’s also not really made for the US market and is poorly documented and I can never remember how to use it.

Quick use notes:

  • Press front button to turn it on: it beeps and light in front starts flashing.
  • Wait for beeping / flashing to stop. Front should glow blue (full battery).
  • Press shutter button on top to start recording. Beeps once, lights flash while it records. press shutter button on top again to stop recording. Beeps several times.

Status lights:

  • Front ring: battery indicator goes from red (low) to purple to blue (full)
  • Top/bottom/back: flashing red LED indicates video recording, photo taken
  • Side: blue LED indicates WiFi is on

Sounds:

  • One beep: turning on. Also acknowledging image capture start.
  • Two beeps: still turning on.
  • Three beeps: connected to USB.
  • Four beeps: video recording finished.
  • Seven? beeps: turning off

Buttons and controls:

  • Front button: power. Short press to turn on, long press to turn off.
    Can also be used to swap between photo/video mode.
  • Top button: shutter control / start recording
  • Side button: turn wifi on. This takes awhile, wait for flashing blue.

For more complex control the camera connects to an iPhone app. The camera can be put in WiFi access point mode, at which point your iPhone connects to its private WiFi network and can control it. (Default password: 1234567890). Lots of settings, the main thing I did was be sure the camera defaults to video mode when turned on.

IIRC you can also download video this way but it’s unreliable, I ended up popping the SD card to copy my recordings over. Or maybe I used the device as a USB drive.

The phone is hackable, there’s a world of custom firmware etc. Also lots of stories of people bricking their cameras.

more cron fiddling

Update: this doesn’t work, see below.

I still need a better solution for running lolslackbot. Right now it’s a shell script that runs 7 Python programs that run sequentially and usually complete in about 25 seconds. I run it from cron once a minute. The problem is sometimes one script takes too long, typically because a remote API server is hung. Also it’s better (but maybe not essential?) if the script doesn’t run twice at once.

So I set up lockrun in the cron job so that only one instance of the job can run at once. This works pretty well, but lockrun has no solution for timing out a dead job. Despite my best efforts, twice now the script hung for hours (forever?) and my system stopped working.

(I can’t even figure out how to monitor lockrun’s lockfile. It creates the file once and then never touches or updates it ever again, so the file time never changes. I could monitor my underlying program’s logfile or something I guess.)

So now I’m wrapping some bailing wire around the duct tape and using timeout to add a timeout.

timeout 3 lockrun --lockfile=/tmp/lf1 -- sleep 10

Yeah, I know. But it seems to work. What could possibly go wrong?

I think the right solution is ensure my scripts are safe to run twice at once. I don’t think this is too hard semantically, and I do have a database with transactions to help mediate things. The trick is the occasional faux distributed transaction for stuff like “if I find a new row in the database, update some remote service and then mark the row as processed”. I guess I could add three phase locking for that? Ugh. While I’m at it I should make it so the 7 Python programs can run independently, at different frequencies. The very first one is the important one, the slow one, asking “is there any activity for any of these N users?” It’d be nice to run that script in parallel and somewhat out of lockstep sync.

While I’m here I wanted to give a shout-out to cronic, yet another wrapper for cron jobs that improves error reporting. cron mails you if there’s any stdout or stderr, but ignores exit status. cronic fixes it so it mails you if there’s stderr or if the exit code indicates an error. But it ignores stdout. Seems particularly useful in concert with timeout; if timeout kills a job the only way you know is exit status, which cron without cronic ignores.

Update: this timeout + lockrun thing doesn’t work. If the timeout fires then timeout kills the child process, lockrun in this instance. But that kill signal doesn’t propagate to the children. A potential solution would be to kill the whole process group but I don’t see an easy way to do that. I’m also wary of adding hacks on hacks because of the warning in the lockrun docs about how there’s no kill option in lockrun because killing things correctly is hard.

Update 2: after 9 months I think my current solution is stable. I use lockrun to be sure only one version of the cron job is running. It runs a Python program, not a shell script, that runs all my separate Python subprograms (by invoking the main() function on each.) It uses faulthandler.dump_traceback_later to implement a last resort global timeout on the whole Python program. It all feels wrong, but in practice it’s been quite robust.

Python modules frustration

I’m trying to turn my lolslackbot code into a proper set of Python modules, so I can manage the code with pip and venv. That means turning my moduleless code into a bunch of packaged modules. And writing setuptools.

And oh god it’s awful. Python’s handling of module namespaces and imports is confusing, particularly when circular dependencies are involved and/or command line scripts as opposed to Python libraries. I can’t even tell if this caveat applies to me or not

Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.

The other problem is years of cruft that’s accumulated in Python packaging tools. setuptools, disttools, easy_install, pip, wheel, egg, virtualenv, pyvenv.. To some extent this has been rationalized in modern Python: use pip and setuptools and call it a day. But the docs that are out there are hard to follow because they tend to describe the history, not the current practice.

The two best documents I’ve found so far:

Right now I’m hung up on some code where “from . import lib” works in some contexts but not others. I think it may be related to circular dependencies but am not sure.

Update: turns out Python doesn’t actually support circular imports, despite looking like it does in many circumstances. So now I’m having to refactor all my code that worked just fine to not have module A import module B which imports module A. I feel like I’m programming in C again, only without #ifndef macros. One partial solution is to only do the imports inside the running function code. That avoids the circular imports at import time, at the expense of deferring the import code machinery running in your actual execution path all the time. Maybe I’m misunderstanding how to really make this work. (There’s a bunch of arrogant advice which says “if your code has circular imports you should refactor it.” No, imports are how you manage namespaces in Python, and Python shouldn’t have this limitation.)

Unit testing in bash

I wrote a really simple unit test framework for bash. Like 10 minutes, 2 functions, totally half-baked. But it seems to work.

testErrors=""
function assertEqual {
    expected="$1"
    actual="$2"
    message="${3:-Not Equal}"
    if [ "$expected" == "$actual" ]; then
        echo -n "."
    else
        echo -n "E"
        testErrors="$testErrors\n$message: Got $actual, expected $expected"
    fi
}
function assertSql {
    expected="$1"
    sql="$2"
    actual=$(echo "$sql" | sqlite3 $db | sed -e 's/ *$//')
    assertEqual "$expected" "$actual"
}

function testReport {
    if [ -z "$testErrors" ]; then
        echo "Tests OK!"
    else
        echo -e "Tests failed$testErrors"
    fi

DNS glue records

Had a bit of DNS I didn’t understand today. The whois records for google.com say the name server is ns1.google.com. So how do you look up the address for ns1.google.com? That’s a circular dependency!

Turns out the answer is glue records; there’s a good explanation in the first two answers on Stack Exchange, or enjoy this comic strip. Long story short, the same TLD server that tells you that the name server for google.com is ns1.google.com also provides an “additional” non-authoritative A record for ns1.google.com. That short-circuits the circular dependency. You can see this reply yourself with dig +additional. Here’s a (heavily shortened) transcript where I only show the lines along the actual resolution chain:

$ dig +trace +additional google.com SOA

.			13529	IN	NS	g.root-servers.net.
;; Received 397 bytes from 192.168.0.1#53(192.168.0.1) in 31 ms

com.			172800	IN	NS	k.gtld-servers.net.
h.gtld-servers.net.	172800	IN	A	192.54.112.30
;; Received 734 bytes from 192.112.36.4#53(g.root-servers.net) in 279 ms

google.com.		172800	IN	NS	ns4.google.com.
ns4.google.com.		172800	IN	A	216.239.38.10
;; Received 660 bytes from 192.54.112.30#53(h.gtld-servers.net) in 361 ms

google.com.		60	IN	SOA	ns3.google.com. dns-admin.google.com. 117627770 900 900 1800 60
;; Received 210 bytes from 216.239.38.10#53(ns4.google.com) in 36 ms

The key thing there is the third segment. My computer asked h.gtld-servers.net who the name server for google.com was, and it gave me an NS record naming ns4.google.com. But then it also volunteered a non-authoritative A record for that name, 216.239.38.10. That’s the “additional” response that serves the glue record.

The other question is how glue records are administered; who told gtld-servers.net the address for ns4.google.com? How do we keep that IP address updated? I’m not sure. My registrar Hover just lets you fill in a glue record but doesn’t explain how that gets sent to the TLD servers. Gandi’s docs have a good explanation too. My guess is it’s part of the protocol that registrars use to communicate with the companies that maintain the TLDs. You don’t just give them NS records for each domain, but you can give them an A record too. I wonder if they auto-update? I’m guessing not.

Glue records are old: they are explained in RFC 1033, complete with an example at SRI.com. This DNS book notes that glue records can also be an optimization; it’s basically providing the answer to the next question the resolver is about to ask. At the cost of being non-authoritative.

(Reading this whole chain I realize I’m still a bit confused about how DNS works. My computer asks my name server 192.168.0.1 who the name server is for “.”, the root, and is told g.root-servers.net. Note it gets no additional A record. But then my computer already knows that g.root-servers.net is 192.112.36.4, how did it know that? Maybe a cache? Then it asks that root server for the name server for .com and is told k.gtld-servers.net, along with an additional A record. From there it can ask about Google.)

Hat Tip to Andy Fowler for giving me the magic keyword “glue records”.

sqlite3 test suite

I felt guilty complaining about sqlite3’s source distribution, so I went to look at the real source, what the authors work with. It’s not managed by git but rather in Fossil (an SCM written by the sqlite3 author). Happily the web view is quite good.

One of the miraculous things about sqlite3 is its incredible test suite. There are 683,932 lines of test code. Compare to 273,000 lines of C code for the library and all its extensions. sqlite3 has a reputation for being solid and correct. It’s not an accident.

The test size is overcounted a bit because there’s a lot of test data. For instance the test for the Porter Stemmer is 24k lines of code, but almost all of that is a giant list of words and their correct stemming. Still very useful tests! But not quite as much human effort as it looks on first blush.

The tests are written in Tcl! For all I know it is the oldest large large Tcl program still in active development. But other than the string quoting problem Tcl is a pretty good way to script a test. See for example the tests for the JSON module

do_execsql_test json101-1.1.00 {
  SELECT json_array(1,2.5,null,'hello');
} {[1,2.5,null,"hello"]}
do_execsql_test json101-1.1.01 {
  SELECT json_array(1,'{"abc":2.5,"def":null,"ghi":hello}',99);
  -- the second term goes in as a string:
} {[1,"{\\"abc\\":2.5,\\"def\\":null,\\"ghi\\":hello}",99]}
do_execsql_test json101-1.1.02 {
  SELECT json_array(1,json('{"abc":2.5,"def":null,"ghi":"hello"}'),99);
  -- the second term goes in as JSON
} {[1,{"abc":2.5,"def":null,"ghi":"hello"},99]}

Very readable and compact.

As a software project sqlite3 makes a lot of idiosyncratic choices. Tests written in Tcl. Fossil instead of git. Source code distributed as “the amalgamation”. But sqlite3 is a masterwork of code. It’s fast, it’s reliable, it’s simple, and it works well in embedded systems while also providing a lot of very sophisticated database capabilities. I have nothing but respect for it.

Upgrading sqlite3 within Python 3

Python 3 has sqlite3 baked in. That’s great! But it has an old version of sqlite3; my Ubuntu 14.04 system with Python 3.4 has sqlite 3.8.2. I want sqlite 3.9, for the new JSON hotness.

There’s a pip-installable package called “pysqlite” that should be installable in a virtualenv. But it only supports python 2 and explicitly says “use the built-in sqlite3 for python 3”. Thanks but no thanks!

This Stack Exchange thread has details on recompiling python3 with your own sqlite3, but that’s more work than I want to do. Also it appears that python3 is just loading libsqlite3.so.0 from my Ubuntu install, so I should be able to upgrade it by either upgrading libsqlite in Ubuntu or building my own shared library. But the Ubuntu upgrade looks impossible without upgrading all of Ubuntu 14.04. (I couldn’t find a PPA from a quick search).

Compiling sqlite3 into a shared library is an exercise. The source is distributed in an idiosyncratic format and the version with a Makefile doesn’t build shared libraries. I ended up making something work by following the official docs and this note about the shared library.

gcc -c -fPIC -O2 -I. -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS4    -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_JSON1    -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_EXPLAIN_COMMENTS    -DHAVE_USLEEP -DHAVE_READLINE    shell.c sqlite3.c
gcc -shared -o libsqlite3.so -fPIC sqlite3.o -ldl -lpthread
ln -s libsqlite3.so libsqlite3.so.0
./sqlite3 -version
LD_LIBRARY_PATH=. /usr/bin/python3 -c 'import sqlite3; print(sqlite3.sqlite_version)'

It works! But now I’m nervous. Compiling sqlite3 correctly takes more research than I conducted. It has a whole lot of options! Also I get a bit worried about relying on LD_LIBRARY_PATH to override libraries. It’s totally fine to do of course, but it just seems too easy to forget to do it in some environment and suddenly things aren’t working consistently. If I were serious about doing this I think I’d build my own Ubuntu package for real, using Ubuntu’s Makefile as a starting point.

Python / sqlite3 query logging

When debugging database code it’s really handy to have a text log of the actual SQL being executed by the database. This output is remarkably difficult to get in many database drivers. Happily, starting with Python3.3 there is a way

connection.set_trace_callback(print)

The argument is any function, or None to disable the tracing. I think this has no access to the results, nor can you use it to time how long the query took. That requires some more ambitious thing.

letsencrypt renewal

I set up letsencrypt SSL for http://www.somebits.com awhile ago. When I installed it in early January, there was no way to renew the certs and they expired in 3 months. Happily they’ve added a simple renewal command which mostly worked. The first time I ran it I got an error “DNS problem: query timed out looking up CAA” but I just ran it a second time and it worked.

Happily the certificate renewal didn’t touch my Apache config at all, just updated the certificate.

I took the opportunity to fix some redirects in the SSL version of my site config so they redirected to https://, not http://. I’m further regretting the way I have two versions of my Apache config, some 90 lines of complicated redirects and crap now duplicated. And now edited a tiny bit, to preserve SSL. I should refactor all that but IIRC it’s complicated.

I’m a little scared to have enabled SSL without fully committing to it. I suspect Google will start preferentially serving the SSL links, so what happens if I forget to update the letsencrypt certs? So far Google isn’t serving the SSL links though, I wonder if my siteindex URLs (no https) overrides their preference for SSL.

I hate installing Python libraries

(Caution: intemperate angry rant follows.)

I’m wasting more than an hour figuring out the fuckup of building GDAL to run in a virtualenv on Ubuntu 14.04 LTS. This hasn’t worked well in the year+ I’ve been trying, and it’s not working well now.

  1. set up a new virtualenv and activate it
    virtualenv -p /usr/bin/python2.7 venv
    source venv/bin/activate
  2. Install the openaddresses repo I have
    cd ~/src/oa/machine/
    pip install -e .
  3. Manually install cairo cffi (shouldn’t pip have done this?)
    sudo apt-get install libffi-dev python-cffi
    pip install cairocffi
  4. Give up trying to install GDAL with pip. Even after you work through the include path packaging problems, the C compiler starts throwing errors about variable scoping.
  5. Start over with a virtualenv that also uses system packages, which somehow seem to be working.
    virtualenv --system-site-packages -p /usr/bin/python2.7 venv

I shouldn’t publish my angry rant. GDAL is great software, and I appreciate all the volunteer open source effort. But something about dealing with packages and software installation is just so maddening. I think it’s because hiding behind “pip install gdal” is about 200,000 lines of complex code in multiple languages from multiple distributers. When it works its awesome. When it fails all you can do is try searching the error message and cargo culting a solution, which only works 1/3 of the time.

grawr.

 

Turning hacky Python into a real app

I’m about to go on vacation. I just finished a bunch of improvements to lolslackbot. Also I suffered my first real outage since it started as a simple cron job six months ago. So I’m reflective on what I need to do to graduate this service into something more serious and reliable. Some projects towards making the system production quality...

Locking and timeouts. The outage was because I tried grafting lockrun into my cron job to ensure only one update runs at a time. But if the update script hangs (say, because the remote API is down) then it holds the lock forever, or at least until I wake up in the morning. I’ve removed the locking for now, running the update twice at once isn’t too bad. But I’m considering adding back the locking along with some sort of global timeout to the scripts, or at least the network requests, so they can’t hang forever. But that’s a hack on top of a hack. “Run this once and only once, reliably” is a hard problem.

Error recovery. I’m a big believer in throwing exceptions when things go wrong, then fixing the code to handle the error. But at some high level I’d rather the script kept going. I’m processing hundreds of game objects a day; it’d be better to skip a game that’s weird and breaks my code than to have the whole system fail until I can fix it.

Logging. I’ve been using Python’s logging program but I’m not logging to a file anywhere; just stderr. That makes it hard to look back at what happened. Or even notice if I skipped a weird game. I might also benefit from some contextual logging, but that may be overkill.

monitoring. I don’t exactly need a pager for 3am, but I would like some better way of knowing if stuff is working than “did cron email me?” and “have any new messages shown up in awhile?”

virtualenv. I’m naughty and don’t use venv. I should.

make code a module. I’m also naughty and don’t have my own code in a proper module. I should. Would be nice to separate the Python scripts from the precious data files, too.

test suite. A lot of my tests run based on some live data I captured a month or two ago and has baked in it things like “there are exactly 110 game objects”. That makes it hard to add new test cases. I think I’m stuck here and need to just suck it up and hand-edit in new test cases to the JSON blobs I use in my mock framework. And then update all the tests. I also had a hilarious problem yesterday where one of my test cases had enshrined the wrong expected output, basically hiding a bug I sort of knew about. That’s the hazard of starting a test suite with “I think this code is working; let’s assume its current output is correct”. Still that test suite is the single best investment I’ve made in the project, so much value.

indices / SQL performance. I haven’t done any work towards creating indices for common queries other than the implicit indices that primary keys and unique constraints give you. So far my whole database is only 20MB, hardly worth worrying about. But at some point table scans are going to stop being fast. I haven’t seen any evidence of a slow query log in sqlite, I suppose I could build my own wrapper in Python.

Distributed transactions. A closely related problem to locking; I have a sort of distributed transaction problem when I’m delivering messages to Discord. I want to mark the message delivered in my database if the message is successfully delivered to Discord. So I write the “message processed” bit after Discord accepts the message. But sometimes Discord throws an error even though the message got delivered anyway, so the message doesn’t get marked processed and later is delivered a second time. It’s sort of a distributed transaction problem I don’t quite know how to solve.

Web view. Big project, I think I’ve graduated to needing a web view for seeing and editing the objects in my database. Particularly for stuff like “add a player to a team”. I really don’t want to roll this all ad-hoc, way too much work. Currently thinking of doing this as a whole new codebase not reusing much (if any) existing code, to try out Flask and SQLAlchemy. With a plugin to generate the editing UI, maybe WTForms or Flask-Admin.

sqlite3 vs postgres. I continue to have the feeling that I should switch to postgres, but I’m now pretty in love with sqlite’s simplicity. The planned web view will be my first time with simultaneous writers, which previously I assumed was when sqlite may be too limiting. OTOH sqlite does have database-level locking, it’s not going to blow up. As long as the locks are only held for “a few milliseconds” I can live with that. Python’s driver has a 5 second timeout for connections by default. The sqlite3 command tool by default just throws an error if the database is locked, but you can specify a timeout in a somewhat awkward way. (If sqlite3 is compiled wrong, locks can last seconds.)

So that’s a big list of projects. I’m not thrilled to do any of them; they’re not features, and they’re a significant investment for a project that has very few users. OTOH they will make my life better as I work on this.

 

Home-rolled database migrations

Confession time: I’ve never personally managed a whole project that involved a complex, changing database. I’ve certainly worked on projects with them, like Google AdWords, but someone else was in charge of the database management. With this LoL Slackbot I’m working on I’m the guy. Which means I’m the one who has to handle migrating a database when the code changes the schema.

Here’s a sample migration script I’ll discuss below.

Turns out changing database schemas on deploys is complicated. Who knew? It was a blessing in disguise that sqlite’s alter table is so limited, it forced me to take migrations seriously. And since I’m not using a tool like SQLAlchemy I’m writing migration scripts by hand. Here’s what I do:

  • The database has a table “globals” with a value “dbSchemaVersion” that I manually increment on changes.
  • My app has a single connect-to-DB function everything uses. It checks the schema version and refuses to run if it’s wrong.
  • When I write code that changes the schema somehow, I manually increment the version. This step is a bit error prone in that I could forget. I could automate it with a checksum on the output of “.schema”, but I won’t bother until the first time I forget.
  • I use sqldiff to summarize the schema changes.
  • When I write code with a new schema change, I keep manual notes on the migration I’ll eventually need. Then I just develop and test my code that uses the new schema in my dev environment ignoring the need for migration. My test scripts start with an empty database.
  • Once the feature development work is done I then write migration scripts. See a simple example in this gist.
  • run.sh is the actual migration. It validates the schema version is what’s expected, then runs arbitrary shell code. In this case all it does is run 3to4.sql. Sometimes I also have it run custom Python programs that do more complex data filling.
  • 3to4.sql is sqlite code for the migration. I do as much in SQL as possible. The .bail on pragma at the start is essential; see here for why. This example script adds a column and then fills it with a static value, very simple. Often the migration script has to copy some table over to a new table and then rename it, since alter table in sqlite3 is so limited.
  • test.sh is my test suite for the migration. I run this on a copy of the live production database (taken out of backup). It runs the migration, then diffs the schema from a dev database. Then it runs some ad hoc queries to validate the new database is as expected, which is totally hokey. I should make that a proper pass/fail test.

One observation I’ve had from this is “schema changes” are more than just changes to the shape of tables. They’re also changes to global values stored in the database, and sometimes changes to the meaning of the data in some column. This single incrementing version number captures all of that just fine, at least with a single developer.

Having now done this work I’m less excited than I used to be about autogenerated schema migrations. I mean, I should try one, but there’s something to be said for hand-crafting a migration when you have to change column values, rerun programs to fill empty data, etc. The automation around testing and version numbers is really valuable though.

I’m terrified with how ad hoc this is. There’s this temptation doing ops work to half-ass stuff, to just type some code in by hand and throw it out, or test it by visual inspection, or... Part of the devops mystique is treating the ops part as real development too, with real testing and repeatability. I’m about 3/4 of the way there with the migration stuff but not fully.

Timestamp precision

I’m in the habit of recording timestamps as integer seconds. Ie, I’m inserting into my database the result of int(time.time()) from Python. It’s a habit left over from the bad old days where Unix machines didn’t have sub-second clocks. Any modern system has access to at least a millisecond timer, if not a microsecond timer or better, and there’s no reason not to use it.

The only drawback for me with my project is I declared all my timestamp fields as “integer”, and sqlite3 does in fact round them off on storage. It’s harmless enough, at least if you’re not relying on exact timestamp storage, but I should probably do a schema migration at some point for it.

It’s a bit confounding that Javascript’s time precision is integer milliseconds, although it seems like a reasonable practical choice.

 

Success! lolslackbot

Big Success! My League of Legends Slackbot has had two major upgrades in the past two weeks. And both have gone quite well, with no serious bugs. I’m so, so glad I invested in a serious testing regimen. I’ve had automated tests for about a month and it is like night and day for development speed. Even on a small project, even working alone.

First, a quick description of the project. It’s a social monitor for League of Legends players. It watches the Riot API for games played by a select group of people. If someone plays a game, it reports the game result to Slack or Discord. A form of social presence. I built it first for a group of about 6 friends playing together and chatting via Slack. I’m now expanding it to a group of about 500 people on another Slack, which is what necessitated me evolving this from a quick hack to a real thing.

The first big change was 10 days ago. I added the notion of “groups”. Previously the list of players I was watching was hard-coded and I assumed everyone was interested in everyone. Now there’s Person and Group database tables and the game reporting is able to collect stats for all the people in a specific group. I still have a design flaw here I need to fix; currently doesn’t work if people from two different groups play the same game.

The second big change was today. I added message routing and delivery. Previously I had hardcoded a single Slack and Discord channel. Now I have Destinations, Subscriptions, and Messages tables so that the game results from various groups can be delivered to various different Slack and Discord channels. A lot of complexity, made doubly hard to test because the end result is actually writing messages people see on a live service. I ended up using unittest.mock for real to mock out the last bit of message delivery in various places.

I wish I’d thought to abstract out a Messages table earlier. Before I was just generating text messages from game objects, but then the game processing code got too deeply entwined with the message delivery code. Now I place create messages in the DB with one program and deliver them in a separate program. Much simpler.

Next major product feature I need to add is some sort of web interface for managing Groups, People, Subscriptions, etc. That sounds really tedious, but necessary. I think this is the step where I’ll graduate and use some higher level Python frameworks, maybe Flask for the webapp and SQLAlchemy to mediate database access. I don’t want to port all my old code over to SQLAlchemy just yet, but I would like to get my feet wet.

I should also productionize the python code. I’m not using virtualenv, my code isn’t even packaged in a proper module. Time to clean that up and add some logging, monitoring, etc.

May also be time to invest more in the test infrastructure. My automated tests are great but they rely on a test dataset I can’t really augment. I generated test data once and have no way to do it again. Also I’ve been running a separate test system for database migration scripts, much more manual and inspection by eye. I think that may be fine actually, but it’s worth examination.

 

Am I crazy? Modern Unix security

This Python library I’m using (deliberately left nameless, not well known) has what I think is a security problem. It takes a password and generates a login token. It then writes that login token to a file in /tmp. A world readable file. That token can then be used by anyone with access to the Unix system to impersonate the user. That seems bad.

What’s baffling me is I reported the bug and the author of the code and other users of the library don’t see the problem. “If someone can read files on your computer you’re screwed anyway.” I think they’re wrong, but maybe this is just me being old?

I grew up in the era of shared Unix systems. We regularly had 40 people all logged into one machine, so of course file permissions mattered. But modern Unix systems are generally single user. Single application, for that matter. And the rise of VM and container technology makes that doubly so. So maybe it doesn’t really matter?

Of course it matters. And it’s easy enough to fix; just make the file private. Although.. Doing that correctly in Python is remarkably complicated. You can’t just create the file and then chmod it, because that creates a race condition where the file is briefly world readable. I think setting umask is better, but that’s per-process state so you can’t really do that in a thread safe manner without locking. os.open() with a file mode is also a possibility but complicated because you’re dealing with file descriptors. The tempfile package in Python does this nicely, but unfortunately I can’t use it because I need a persistent file. tempfile’s code is remarkably complex!

Python is fast opening sqlite3

I’ve got a lot of code calling sqlite3.connect() in my program now. Particularly in my test suites. In MySQL and Postgres this can be slow and you end up needing connection pooling. I had a feeling it shouldn’t be in sqlite3 given its simplicity, but I wasn’t sure.

A bit of work with timeit later I can report it’s taking about 18usec to open a database. My connection function is more complex too, doing a select into a “globals” table to test the schema version. Even with all that work it’s 170usec, or < 2ms. That’s not super fast but it’s not a problem if my test suite does it 100 times.

$ python3 -m timeit -s 'import sqlite3' "sqlite3.connect('games.sqlite')"
100000 loops, best of 3: 17.6 usec per loop

On JSON and nothingness

Python’s JSON module serializes the Python value None as the JSON value null. This is correct. However it causes odd bugs if you are not aware of it.

Specifically, I had code like this:

db.execute('insert into table values(?)', json.dumps(foo.get("bar"))

I was trying to insert a database NULL if foo didn’t have the key “bar”. But foo.get() returns None, which gets turned into the string “null”, which results in the string ‘null’ being inserted into the column. Derp.

>>> json.dumps(None)
'null'
>>> json.loads('null') == None
True
>>> json.dumps('null')
'"null"'
>>> json.loads('"null"')
'null'

>>> json.loads(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'NoneType'

A simpler explanation of asyncio

Reflecting on my previous effort to understand asyncio, I think I have a simple summary:

asyncio is a cooperative multitasking system for Python based on generators. You implement your program as generator functions that yield control periodically. The asyncio event loop manages running all of your generators.

That’s it, it’s really simple. This understanding lets me build on my existing knowledge about generators / coroutines and understand what asyncio is doing.

What’s confusing is all the syntactic sugar and extra library stuff in asyncio gets in the way of understanding the simple thing. Also the Python docs are not written from the point of view of “explain the basic idea”. And the API is still in transition; in Python 3.5 they are no longer generators, they are coroutines, but the principals are the same.

Here’s a really simple program:

import asyncio

@asyncio.coroutine
def sleeper(loop):
    for i in range(10):
        print(i, loop.time())
        yield from asyncio.sleep(0.1)

loop = asyncio.get_event_loop()
task = sleeper(loop)
loop.run_until_complete(task)

That’s a toy example. In real work, you have multiple tasks running simultaneously. And instead of yielding on a sleep you yield on something more useful, network IO or something.

The confusing part is the line 10, task = sleeper(loop). Naively you’d expect that to invoke the sleeper function and do the work right then. But because it’s been decorated as a coroutine, really what calling that function does is return a generator object that encapsulates calling the function. We then pass that generator to the event loop to ask that asyncio call it for us. (In Python 3.5 using async def and await, that object is no longer a generator, it’s a member of the new type, coroutine.)

There’s a lot more complexity of course. I’m still confused about the melange of coroutine, Task, and Future, and when to use which. Combining multiple coroutines in various ways can get complex, although once you commit to the model it is easier to reason about than thread locking. And then there’s a lot of auxiliary libraries that make asyncio useful, things that help you yield from network IO or external processes or whatever. Not to mention libraries on top of asyncio like aiohttp.

But the core concept there is really simple. Generator functions that cooperatively multitask. That’s the magic, there’s not too much of it really.

Need a database abstraction

My little lolslackbot project has grown big. 11 different tables! I’m hand-writing ORM code now, silly things like “class Person” which wraps a row for the people table. The meat of the work is still hand-crafted SQL with proper relational queries, but I’m increasingly doing some really basic “get me the row with property X” and writing it all by hand is tedious. And oh boy I added some caching using functools.lru_cache, which I know from experience at Google is the beginning of the end for understandable correctness. And I continue to write increasingly elaborate schema migration scripts as I upgrade stuff.

It’s all kind of a mess. I wish now I’d started using some Python ORM tool. I still think ORMs are kind of evil, but they are a useful evil.

I’m out of date on where Python is but my impression is everyone likes SQLAlchemy. The basic tools are just a really nice upgrade from the basic Python database driver stuff. And the ORM looks like it’s made the right choices, at least based on what I read.

But do I want to port all this code over? Hell no. Hrm... I’m accumulating technical debt. I also need to wrap all my Python code in a proper module structure, and set up a real virtualenv, and...

At least I have a test suite. Although Guido help me if I ever have to regenerate the test dataset.

 

Understanding Python 3.4 asyncio

Working with discord.py has made me realize how I really don’t understand asyncio, the modern way to do asynchronous code in Python. Truthfully I barely understand any sort of async programming at all. I can sort of bash away at NodeJS a little bit. And I once wrote an asyncore program that did some neat network stuff. But mostly I’ve used threads or processes to do concurrency. It doesn’t help that I generally am starting with a single threaded synchronous program and then trying to later shoehorn it into some async context.

But soldiering on, here’s some resources:

  • Python 3.4 asyncio docs: the core reference. As with all Python docs it is well written, but unlike some Python docs it’s hard to follow. Much more of a reference than a tutorial.
  • Module of the Week: asyncio: a heroic effort to provide an overview tutorial of the complete module with lots of examples. It’s good, but I’m still confused after reading it.
  • Exploring Python 3’s Asyncio by Example and The New asyncio Module in Python 3.4: Event Loops, two more tutorial articles that just hit the highlights.
  • A Web Crawler With asyncio Coroutines: a thorough explanation of how asyncio works, building it up from first principles with generators.
  • How the heck does async/await work in Python 3.5?: a more low-level explanation focussed on the await/async keywords in Python, includes an example of implementing your own framework instead of using asyncio
  • PEP 3156 is the proposal that resulted in asyncio, written in the Python 3.3 era with a reference implementation called “Tulip”. I haven’t read this yet.
  • PEP 0492 is the proposal that resulted in the “async def” and “await” keywords being added to the language in Python 3.5. Also “async with” and “async for”. To normal coders, this is mostly syntactic sugar for stuff that worked in Python 3.4. But behind the scenes Python added a whole new concept of “coroutines” to the language, to accompany generators.
  • PEP 255, PEP 342, and PEP 380 are 5+ year old PEPs related to defining generators in Python. (The “yield” keyword.) Generators are the basis of coroutines, and coroutines are the foundation of asyncio.
  • aiohttp is the popular HTTP library for use with asyncio.

Here’s my understanding of today, with the massive caveat that I’m totally new to this and may have important aspects wrong.

The key concept in Python asyncio is the event loop. When you are writing an async program you no longer are executing functions imperatively. Instead you are creating objects that ask for your functions to be called. (The “async def” keyword or the @asyncio.coroutine decorator do this for you; they wrap your imperative functions with an object, so when you invoke the decorated function it doesn’t actually run but instead returns the callback object). You then supply these objects to the event loop through functions like “call_soon()”. Finally you set the event loop running with run_forever() or run_until_complete(), which gives the event loop control over the CPU where it blocks while it runs your code via all the callback objects you gave it.

The other key concept in Python asyncio is coroutines and/or generators. That’s where the “yield” keyword comes in, and it’s actually the same old yield keyword we’ve had since Python 2.3. It’s the way for a Python function to return CPU control back to the thing that called it, yet also keep its stack state so if that function is called again it picks up where it left off. asyncio in 3.4 is literally implemented just as a bunch of fancy generator functions and lots of yielding everywhere. 3.5 adds the new syntax support with “await”. It also makes async functions into “coroutines” instead of “generators”. But the basic concept is still the same.

So that’s the core async magic. It’s really just a sort of process scheduler for cooperative multitasking. The event loop is the CPU scheduler that invokes tasks in a single Unix process/thread. Tasks politely interrupt themselves by calling yield when they can.

But there’s a lot more in asyncio. A key thing is that there’s convenience functions for places where you are most frequently going to want to yield. Ie: waiting for a socket, or a stream, or a subprocess, there’s convenience code for saying “get me the next bytes from this socket and oh by the way go ahead and yield control until there’s something to read”. There’s also a higher level wrapper for “protocols”.

And beyond that, there’s a lot of building blocks. There are Tasks and Futures to wrap some asynchronous thing in a structure. There’s a “wait()” method for collecting results from multiple asynchronous things. There’s locks and semaphores. Many of these convenience objects seem to basically be wrappers for the basic yield/await syntax.

So I think that’s how it all fits together. Now to translate that theory into actual working code to see if it’s right.

Update: thanks to a reader comment from Luciano Ramalho I read A Web Crawler With asyncio Coroutines and basically have my understanding above confirmed and deepened. Despite the title, the article is really building up a full asyncio implementation from basic Python generators, explaining in detail how everything works. Now that I understand this much better I look forward to forgetting entirely how asyncio works and just embracing and using its abstractions. If it’s well designed, it should be usable without knowing how it was implemented.

Update 2: see A Simpler Explanation of asyncio

Discord API first use

My gaming group is switching from Slack to Discord. It’s a nice product. It’s sort of a Slack clone with voice channels as the big added feature. It’s also a product aimed at gamers, not corporate use, so there’s some hope the pricing and features will make more sense for gamers. I like the product, it’s worth a look.

So now I need to make my Slack bot post to Discord, too. Discord currently has no formal API. There is a fantastic group of hackers doing an Unofficial API project, though, and the company seems OK with it. Compared to most hacking projects this one is particularly well documented and organized. I dove in this morning and figured out how to write my own bot that works with the Discord API.

First, some resources:

The Python client is very nicely documented and organized. If you’re starting afresh you want to get version 0.10.0a, the alpha, directly from GitHub. PyPI currently has 0.9. 0.10 has reorganized the API, no reason to use the old one now.

The client itself is entirely based on Python 3.4’s asyncio (with preference for the new 3.5 syntax if available). That means you basically have to do everything through an event loop, which is a bit of a nuisance for simple things but absolutely necessary for building real software that’s going to interact with a Discord server. it also means discord.py only works with Python 3.4 and later. I think that’s all the right choice.

Here is my demo program. It took me a couple of hours in total, half of which was me reminding myself how asyncio works. All in all pretty straightforward, once you figure out the basic paradigm of how it fits together. There’s one choice embedded in my code here, which is I subclassed discord.Client instead of using the function decorator syntax for declaring event handlers. Either works fine.

The unofficial API also makes me understand the Discord product a little better. Unlike Slack, Discord has a notion of a single User that is logged into Discord with an email/password. That user can then be a member of various Servers, each of which has its own Channels. Slack doesn’t really have a cross-Slack notion of User, every Slack is an independent domain. The Discord API’s handling of public/private/DM channels is also a bit more straightforward than Slack’s.

quicky python continuous tests

pytest-watch is a fine quick “continuously run my tests” thing for Python in a tty. It’s nothing fancy, and the default UI is not perfect. But with -c and --no-beep and using --runner to run a custom command for your tests, it’s fine. Nice to not have to switch from my editor window to a console just to run the tests.

I’m envious of the NodeJS folks and their hipster test runners, they are very nice. Alternately I wish there were a good way to turn SublimeText into a bit more of an IDE with debugging and test output parsing. But after years of trying IDEs and going back to plain text editors, I think I’m not going to try to board that ship again.

 

sqldiff for sqlite3

Learned about a nice tool today: sqldiff. It shows differences between two sqlite databases. Particularly nice with the “--schema” flag, so you can just compare schema differences. I’m in the middle of database versioning hell as I keep iterating my lolslackbot project. Beginning to regret rolling all the database stuff by hand instead of using some ORM.

Mac sound capture, take 2

Awhile ago I wrote up some notes on recording League of Legends videos using OBS. I still mostly follow that horribly manual workflow, but I was having a hard time getting sound to work reliably. I think I have it sorted out now.

  1. Install Matt Ingalls’ SoundFlower 2.0b2 from GitHub
  2. Reboot. Not clear this is necessary, but I think it may be.
  3. Follow these instructions for configuring audio. However, Soundflowerbed is no longer included. Fortunately you can ignore that if you Audio MIDI Setup yourself (standard Mac software)

The key thing here is you use Audio MIDI Setup to create a new “Multi-Output Device”. That’s a virtual sound device that can send output to more than one place, in this case both “Built-in Output” (your speakers) and “Soundflower (2ch)” (the capture device).

Then you use the Sound preference panel to tell the Mac to play output to that new Multi-Output Device. Now every sound your Mac plays will both come out the speakers and be sent to SoundFlower.

Then you set up OBS to accept audio input from the SoundFlower device.

Unfortunately setting the default sound output to Multi-Output Device will break the volume control from the Mac keyboard. You can still set the volume for each output in the Sound panel though, just be sure to leave Multi-Output Device selected when you’re done. You want to modulate actual volume using Internal Speakers’ control. Set the Soundflower and Multi-Output Device volume to maximum, so that sound is passed through at full volume to OBS.

In previous versions of this setup I found cases where OBS could record audio correctly, but only if it was launched after the program playing the sound. No idea what that was about. I don’t think that’s happening any more.

If you’re serious about doing more fancy audio routing, the commercial Loopback program is pretty good. At $75 though it’s a bit pricy for what I’m doing.

CNAMEs at a DNS root

It’s common wisdom that you can’t use a CNAME at the root of your domain. http://www.example.com can be a CNAME pointing to something, but example.com can’t. That makes hosting websites on naked domains awkward. Only confusingly you actually can do this, it’s just a bad idea. And some DNS services make it look like you’re doing it in a good way, but really they’re faking it. It’s all pretty confusing but I think I understand what’s going on in detail. This post was motivated by this Hacker News thread.

A reading from the holy text, RFC 1034

A CNAME RR identifies its owner name as an alias, and specifies the corresponding canonical name in the RDATA section of the RR. If a CNAME RR is present at a node, no other data should be present; this ensures that the data for a canonical name and its aliases cannot be different. This rule also insures that a cached CNAME can be used without checking with an authoritative server for other RR types.

So if you make example.com a CNAME, you can’t put any other DNS records on it. AFAIK you can actually do this and it will work as well as a CNAME will. The problem is you often want other DNS entries at the apex domain. You want an MX entry so you can redirect mail at example.com. You want a TXT entry to verify you own the domain name to various services. You might want special funky records for DNSSEC or other stuff. It really doesn’t work to make your apex domain an alias for some other domain.

Confusingly, a lot of the big DNS providers do let you set up a CNAME at the apex domain. But behind the scenes they aren’t really serving it as a CNAME; it’s more of a synthetic alias implemented by their DNS server. Typically it looks up the destination host address and quickly substitutes that IP in with an A record for your apex domain. That breaks the end-to-end principle of the DNS lookups, which causes problems for geographic load balancing, fast cache expiry, and probably DNSSEC. But it’s not a terrible solution.

Here’s a list of some of the DNS vendors’ aliasing technology

Long story short, if you want to serve a website from an apex domain it requires compromises and/or protocol fiddling.

Looking at all this I wonder if the world would be well served with a special DNS entry just for web servers. It’s weird to put something application specific in DNS, but there’s a strong precedent in MX entries, for mail delivery. Probably a bad idea to extend that to the web, but maybe it’d all some useful tricks?

 

sqlite3 vs postgres: uneasy feeling

I continue to write my LoL Slack bot with sqlite3. I can live with the primary drawback of sqlite3, which is that writes require a database level lock (ie: no table or row locking). In normal use I should only ever have one writer to the database anyway. But I still have a nagging feeling I should use “a real database”. Ie: Postgres

The nervousness is I’m writing more complex code that’s wedded to sqlite. I’m using sqlite’s upsert equivalent, for which there is no standard syntax. I’m also using sqlite’s Python convenience feature of not using cursor objects. And just now I’m starting to pay attention to Python’s weird transactional semantics, which I suspect might be different in Postgres. In short my code has been dating sqlite for awhile but now things are getting serious and I’m getting commitment anxiety. Also Postgres has some alluring features I could use, like JSON and array types.

The underlying question is whether Postgres is really “better” for my kind of application. I suspect not, and part of why I stick with sqlite is to test that assumption, but the cost of being wrong is getting higher. The flip side is managing a Postgres daemon is still a PITA. Particularly on Ubuntu where upgrading is scary.

tuple vs list

One small thing in Python3 that continues to confound me is how dict.values, dict.keys, and zip all don’t return real collections but instead iterables. That means you have to wrap them first in a tuple or list if you want to array index the output. It’s not a huge deal, but it’s a nuisance.

So which is better? Tuple or list? Tuple should be in theory, because it’s immutable it should be a little more efficient. Seems to be that way in practice too.

$ python3 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.266 usec per loop
$ python3 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.331 usec per loop

$ python2 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.227 usec per loop
$ python2 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.256 usec per loop

(You know, every time I do a timeit on python2 vs python3, python3 is measurably slower. Some of that is due to Unicode but I don’t think that’s all of it.)

Python HTTP mocking

I need to do a better job mocking out HTTP requests to allow me to test all this web API code I’ve written. Right now I rolled my own bad mocking around a wrapper for all the REST calls, but I think it makes more sense just to mock at the HTTP level.

A quick Google search reveals three modern libraries: requests-mock, responses, and httpretty. After literally tens of minutes I’m left with the opinion any would work. responses-mock looks like the most mature and complete product. I like responses for its simplicity. The main differences between the three are the mechanism they use to intercept HTTP calls. I believe httpretty is the only one that works with an HTTP library other than Requests. OTOH why would you use any other HTTP library in Python?

Update: since doing this exercise I started using requests-mock. I’m quite happy with it.

Some detailed notes below, then my test code.

requests-mock: mocks out Requests by installing a Transport Adapter. (I’m endeared, because I came up with a similar technique on my own for Java back in 2000 or so.) Has detailed support for matching full URLs or parts of URLs or specific query strings or URL regexps. Supports all HTTP methods. Responses can be text, JSON, byte strings, or callbacks. Has a way to inspect which URLs were called. Has great docs.

Responses: mocks out Requests using the unittest.mock library, patching requests’ send function. Supports matching on regex, but no special support for query strings in URLs. Responses can be text or JSON or callbacks. Supports all HTTP methods. Optionally throws an error if not all URLs were accessed. No fancy docs, but the code is easy to read. Motivation in this blog post.

httpretty: works by monkey patching sockets. that’s terrifying, but kinda neat because it can mock out HTTP from sources other than Requests. Oddly they don’t have official Python 3 support (it seems to work though). I didn’t look at all its features in detail.

(BTW, unittest.mock was new to me, a very nice standard library for monkey patching any Python library for unit test mocking. That could come in handy in lots of places.)

Here’s my test / sample code.

#!/usr/bin/env python3

import requests, unittest
import requests_mock, responses, httpretty

def fetch():
    &quot;The method we'll be mocking&quot;
    r = requests.get('https://www.somebits.com/robots.txt')
    return r.text

class TestStuff(unittest.TestCase):
    def test_real(self):
        self.assertEqual(107, len(fetch()))

    def test_requests_mock(self):
        with requests_mock.Mocker() as m:
            m.get('https://www.somebits.com/robots.txt', text='nelson-requests-mock')
            self.assertEqual('nelson-requests-mock', fetch())

    def test_responses(self):
        with responses.RequestsMock() as r:
            r.add(responses.GET, 'https://www.somebits.com/robots.txt', 'nelson-responses-mock')
            self.assertEqual('nelson-responses-mock', fetch())

    def test_httpretty(self):
         httpretty.enable()
         httpretty.register_uri(httpretty.GET, &quot;https://www.somebits.com/robots.txt&quot;, 'nelson-response-httpretty')
         self.assertEqual('nelson-response-httpretty', fetch())
         httpretty.disable()

if __name__ == '__main__':
    unittest.main(exit=False)

    # Verify the environment is left clean
    assert 107 == len(fetch())
    print(&quot;Real requests are working again.&quot;)

Two sqlite3 gotchas

Ran into a couple of odd problems when doing database schema migrations on my sqlite3 database.

Transactions don’t work like you’d expect in the sqlite3 command line tool! I wrote a few lines of SQL to create a new table and drop an old one, then fed that script to sqlite with the command line tool like this: sqlite3 my.db < script.sql. I was clever and wrapped my script.sql in a “begin transaction... commit” so that if there were any errors, nothing would be committed. Smart, right? Wrong. sqlite3 will gladly execute line n+1 in a script it’s fed even if line n fails. This makes sense for interactive use, but is a disaster for a script that wants a transaction; the commit at the end will always run. The solution is to put .bail on in the top of your script so any errors cause execution to terminate. See also this discussion.

I was using an “insert or replace” command to be sure I only had one row per key in my database, along with a unique constraint to tell the DB what the key was. Only I didn’t actually add the unique constraint during my migration, because it’s a PITA to do schema changes like that in sqlite3. unique constraints are only hints, right, it’s like a type checker! Well not if you rely on the constraint violation enabling an “insert or replace” to work. Oops.

 

Progress

Still working away on my LoL / Slack bot. Today’s project was rejiggering all the code to use a new synthetic “personId” as the primary identifier. Previously I was using “summonerId”, but that’s only unique to a single region (like North America) and now I need to make the thing work for multiple regions.

Scary code change because it touches all the files and a lot of assumptions. But no changed types; it’s swapping one int for another. My simple test suite paid off in spades here, giving me the confidence my changes worked. So far so good!

I even had to do a database migration, adding a column to a couple of tables. That I just hacked up by hand but it seems to have done the job. I need to do another now to drop the superfluous column. Unfortunately sqlite doesn’t really support dropping columns, will have to do some more complicated stuff involving creating a new table and renaming it.

 

Testing discipline

One of my successes in my professional career has been advocating for unit testing. I helped lead the charge for automated unit test suites inside Google, particularly for our Java code, and that ended up being hugely useful.

I’m nowhere near as disciplined when I’m working alone on my little hacks. It’s still just too much effort to write tests! It feels like twice the work. For a long lived software project with many users, sure, it’s worth the investment. But a one-off hack you’re not going to ever pick up again? Is it even worth the bother of remembering Python’s baroque unittest syntax to set up a test framework? (I have to look that up every... single... time...)

But small hacks have a way of becoming bigger things, vital projects. I’m continuing to work on my Slack / League of Legends integration. I may even get a bunch of new users, I found a community of a few hundred people who could use it! Yay! But I’ve gotten to a point of paralysis where I was afraid to make changes because I couldn’t tell if I would break things other than pushing it to the live system and then see if cron mailed me any errors. Derp.

Unfortunately this project is particularly thorny to test. I’m integrating with two different online APIs (Riot and Slack). I’m also storing data in a database, and I’ve still never seen a good solution for mocking out a stateful database. For now I’m just going with ugly hacks. I’ve put wrappers around the Riot API calls that will load canned data from a pickle, a sort of persistent memoization. And I’m just accepting the test script needs to create a fresh test database and populate it from scratch. That’s not the ideal of unit tests, but it is still some form of useful automated testing.

I already feel relief and confidence from having even something very basic in place. Now I can type “./test.sh” before deploying and at least know if the scripts are going to blow up on some really stupid error. And I have a place now to add more sophisticated tests for correctness.

Update boy what a difference that simple test suite has made. I’ve felt free to make way more aggressive changes to my code now. Without fear.

 

Slack API: channels, groups, IMs

I’m writing a fancy Slack bot to post messages in a Slack for 500+ users. Fun!

There are at least three different kinds of things a Slack bot can post to:

  • Channels. These are the public channels like #general. Find them with channels.list. Bots can’t call channels.join; I think they’re de facto members of all public channels.
  • Groups. These are private channels. The bot has to be invited via /invite, then it can see the group IDs with channels.list.
  • IMs. These are direct messages. You can see all of a bot’s IMs with im.list. I think someone has to message a bot first before the IM channel is created, not sure how a bot can initiate an IM (if at all).

I mostly like the Slack API but it’s a bit warty for things like this. My impression is it’s grown organically and they’ve never gone through and deprecated old stuff. It’s nice that old code keeps working, but it’s a bit confusing if you’re starting now. I’m also really confused about the various kinds of integrations, bots, applications, etc.

A better Python object for JSON take 2

I wrote about wanting a better Python object for JSON. Now I’ve tried out a bunch of options, all inadequate, and am clearer what I want.

The best of the libraries I found was addict. Or maybe easydict because it is slightly less magic. dotmap is also OK but has one wrinkle. attrdict was the only one I couldn’t make work well.

I’ve put sample code exercising various libraries in this gist.

Here are the things I want, in order of priority:

  1. Dot access to fields instead of []
  2. Sensible default value for missing keys instead of an exception
  3. Ease of adding new nested values
  4. Ease of serializing to JSON
  5. Small performance hit

All the libraries provide #1, dot syntax for reading keys. The challenge is #2, what happens if the field is missing (like d.noObj in my code). dotmap and addict both return an empty dict {} for missing keys. That’s not a terrible default although I’d prefer None. attrdict.AttrDefault() lets you choose a different default value but has other problems. easydict just throws exceptions for missing keys; making the dot syntax of questionable usefulness.

The tricky thing is #3 and it ties to what happens if you then assign to an empty dict for a missing key. That’s required for convenient syntax for setting a deeply nested value, the ideal syntax of “d.other.nested.thing = 6”. Both dotmap and addict actually create an empty dict value in the data structure the moment you try to read an empty key. That lets nested assignment work, but leaves litter in your data structure. addict edges out dotmap here because it provides a .prune() method to remove them. easydict doesn’t create empty dict values, so nested assignment isn’t convenient but then it’s less magic.

#4, JSON serialization,is not too hard in any system. addict, easydict, and attrdict just let you pass the thing to json.dump(); their objects are subtypes of dict. dotmap requires you explicitly call .toDict().

I did not measure #5, performance. Each library has a different approach to when it copies data, would be worth examining.

I mentioned above I couldn’t make attrdict work for me. That may be my error, not the library’s. It’s neat in that there’s actually two options; AttrDefault, which provides alternate default values, and AttrDict, which is a bit simpler. But AttrDict has a mysterious / confusing design wrinkle for “Recursive attribute access” that’s a n00b trap. And I couldn’t figure out how to JSON serialize an AttrDefault, nor even how to turn it into a normal dict. Maybe I missed something.

Doing this exercise made me wonder about the wisdom of #2, sensible default values. The problem is there’s not a one-size-fits-all default. Often you want it to be None, for simple primitives. But sometimes you might want [] for an empty list or {} for an empty object. If you want to let the programmer choose those values, you might as well go fully verbose and use the dict.get() method with its default value.

I could see using EasyDict in the future if I only wanted to read JSON and weren’t worried about #2, missing values. It’s the least magic. Or else Addict if I also wanted to construct JSON and get empty dicts returned for missing keys.

Update: it strikes me that a lightweight use of JSON schema would be helpful here. If you know what types to expect, you can fill in any missing keys with appropriate empty values. Not sure anyone uses JSON schema in the wild though. I’d want to start with something that auto-infers schema from examples. And I don’t care about validation, just using type expectations as hints on what to do with ambiguity.

Update Nov 2019: see FlexDict. It has solutions for the creating-objects-for-keys problem.

A better Python object for JSON

Python’s default JSON package encodes and decodes to a dict. This works well enough, but I’ve never much loved the dict type in Python. I’d rather it were an Object with attributes. dicts are verbose: data[“foo”] instead of data.foo. Also dicts throw exceptions on unknown keys, when often what I want is it just to return None. So I’m left with data.get(“foo”, None) which is awfully wordy. Basically I want something that’s as convenient and sloppy as Javascript objects.

I asked on Twitter and got some suggestions, none awesome.

Not sure if these imply overhead from copying, etc. Also they may not serialize well in the JSON module, although I imagine you can copy out a dict view on at least one of these. (More overhead!)

A yak that needs shaving. Don’t they all?

Update: see this second post

sqlite upserts, inserts, etc

sqlite has a nifty feature; “on conflict”, aka “insert or”. You apply it to insert and update operators to tell sqlite what to do if the operation would violate a constraint like unique or not null.

I’m using “insert or ignore” to only insert a row if it doesn’t exist.

insert or ignore into mytable(userid) value (23)

You can also use “insert or replace” to do an upsert

insert or replace into mytable(userid, name) value (23, "Joe")

 

Slack API thoughts

I’m working on a Slack integration that marries the Riot games API to the Slack API, for a group of League of Legends gamers I play with. I’ve been doing simple message posting from a cron job for 6 months now and it works great. Now doing fancier stuff.

I’m not a fan of the message formatting options. There’s the basic markup which they call “markdown” even though it’s not markdown. Then you can add attachments which has a bit of a tabular layout to them but it’s not very flexible. I can’t make it look like what I want, so I’m reduced to doing fixed-width formatting of plain text. Ugly. I wish they’d let me do free form HTML but I guess they’re aiming for display consistency so don’t want that.

I am impressed with how easy it is to add basic slash commands though. You can just create a “Configuration” that causes /foo to fire off a POST to the URL of your choice. Done! There’s fancier stuff for installable commands, too.

Last comment; the slackclient.py that looks official is not awesome. There’s no proper release schedule so what’s on PyPI is out of date. And it seems to rely on an odd websockets implementation. I may want to look into alternative Python wrappers if I do anything too complicated. I’ve only been using the REST Web API so far, not any streams.

 

Let’s Encrypt thoughts

I just set up Let’s Encrypt to enable SSL on my weblog server. I did this in the dumbest way possible, just running ./letsencrypt-auto --apache without understanding what it was doing. It went very smoothly and I really admire the turnkey installation that the project has come up with. Here’s a report on the result, and how it looks in Chrome:

Screen Shot 2016-01-06 at 10.46.37 AM

But of course I have some complaints valuable observations.

There’s one usability problem; the certificates expire every three months and they don’t have an automated renewal process yet. They promise one soon.

Also I lied a bit, it didn’t go smoothly, in fact it choked processing my Apache config file. I filed a bug, it’s related to a rewrite rule that is idiosyncratic to me, no big deal. But the bug reports are full of “it failed to parse my Apache file!” with the developers diligently fixing every parse problem. It feels like they’d benefit from a more sloppy parser, something that just extracts the part of the config file they really need and doesn’t try to validate / parse the whole thing. This config management stuff always sucks in software though.

As convenient as the turnkey magic is, it also made me nervous. I wish it printed a little summary of what it did to console. It seems to have installed some Ubuntu packages, munged some config files, generated a key, and reloaded Apache to enable SSL. I’m protective of my server; maybe I should have done a manual install or read the docs first.

Fortunately there are good docs, a little thin, but the basics. They store all the certs in /etc/letsencrypt/. Diffing against a backup I see they add SSL solely by creating new files in /etc/apache2; enable a couple of SSL mods, then create a somebits-le-ssl.conf for the SSL site. Unfortunately that file is a complete copy of the original somebits.conf file only on port 443 with SSL stuff added. I hate to see that duplication of configuration! I wonder if it’s partly my fault for having sloppy config files. Some ideas for doing it right: macros or include files. Of course Let’s Encrypt shouldn’t be doing that for me, but it may be best-practice to do it for myself.

Their logging config in /etc/letsencrypt/options-ssl-apache.conf was not a good match for my carefully managed logs. Their config seems to automatically write any SSL site logs to /var/log/apache2/access.log with a vhost attached. That seems like a reasonable default, but in my case I already have custom logs enabled in each site.conf file that go to different directories. Just a case of Let’s Encrypt’s defaults not being right for me.

Slack API code to look up IM channel

I want to write a Slack bot that sends IM Direct Messages. It’s a bit indirect in Slack. You have to first call im.list to get a list of all the “DM channels” the bot can write to. Then you have to look up the user info for each channel to figure out which person it actually is. Here’s some throwaway code that does that.

Bonus wrapper for the official Python slackclient library to decode the response and throw appropriate exceptions. That library has gotten little love from Slack, it could use some help.

from pprint import pprint
from slackclient import SlackClient
import json

_slack = SlackClient("SECRET")
def slack(*args, **kwargs):
    "Wrapper for Slack API. Manages stub, also decodes responses and raises exceptions"
    rb = _slack.api_call(*args, **kwargs)
    r = json.loads(rb.decode("utf-8"))
    if r.get("ok", False) != True:
        raise Exception("Error making Slack call", r)
    else:
        return r

imList = slack("im.list")
for user in imList['ims']:
    pprint(user)
    info = slack("users.info", user=user['user'])
    pprint(info)