Some Bits: Nelson's log

148 posts in 2015

DNSSEC examination

I was curious what was up with DNSSEC these days. A little bit of a dive on deployment and the way it all works in practice.

Bottom line: use a DNSSEC-aware nameserver like Google Public DNS and you will be protected from DNS records that were signed but tampered with. However very few DNS names are signed.

You can see quick DNSSEC tests in a browser. This page displays a DNSSEC Secured!” if you are secure. This site should fail to load entirely (name won’t resolve) in a secured system.

Deployment

My main question is how widely DNSSEC is deployed. This little name-and-shame site gives a pretty depressing answer, the top 25 sites according to Alexa all don’t support it. Particularly curious why Google doesn’t publish DNSSEC records. They’re not dumb or lazy, they take security very seriously, I imagine they think it isn’t important or useful for some good reason.

Verisign’s DNS Scoreboard says some 625,000 domains are DNSSEC secured. That’s like 0.4%, although it is growing.

percent-trace.png

 

Example DNSSEC records

The Verisign Labs DNSSEC debugger is the best web tool I’ve seen for examining DNSSEC records. Note the little “more/less” buttons in the display, if you click “more” enough you get to see the full response like dig gives you. You can also use dig to check things with “dig +dnssec”, then look for the extra records and the “AD” flag in the response.

Here are some test domains and their properties. Note I wrote this in Dec 2015, things may change afterwards.

  • google.com: no DNSSEC on the domain.
  • ietf.org: working DNSSEC, a simple signed domain.
  • www.ietf.org: working DNSSEC that’s a CNAME to CloudFlare, which also has DNSSEC (since last month).
  • www.paypal.com: working DNSSEC at PayPal, but www is a CNAME to Akamai, which does not have DNSSEC enabled.
  • dnssec-failed.org: a deliberately broken DNSSEC record. Most tools and nameservers I use won’t even give you any data from this record, presumably because it’s broken. I had to view the web page via archive.org, which apparently isn’t verifying DNSSEC. Neither is Googlebot unless they special-cased it.
  • rhybar.cz: another deliberately broken DNSSEC record.

Screen Shot 2015-12-20 at 10.13.32 AM.png

DNS server behavior

How do various public DNS servers handle DNSSEC records?

  • Google: supports DNSSEC, doesn’t return records for broken DNSSEC.
    dig @8.8.8.8 dnssec-failed.org +dnssec
  • UltraDNS: supports DNSSEC, doesn’t return records for broken DNSSEC.
    dig @156.154.70.1 dnssec-failed.org +dnssec
  • OpenDNS: does not support DNSSEC at all. Will return records even if DNSSEC is bad.
    dig @208.67.222.222 dnssec-failed.org +dnssec
  • Verizon / Level3: does not support DNSSEC at all, returns bad records. (The list I’m working with says this service is “DNSSEC aware”, but that’s not the same as “validating” apparently.)
    dig @4.2.2.1 dnssec-failed.org +dnssec

Bottom line it looks like there’s two types of servers. Those that do support DNSSEC and won’t return any data if a declared DNSSEC record is broken, and those that are ignorant of DNSSEC entirely. That’s to be expected.

I’ve long been a skeptic of OpenDNS, and their lack of DNSSEC support is another reason to not like them. Back in 2010 they proudly announced they were going to back DNSCurve instead. No one else has supported it since then, so I assume it’s basically a dead end. Their arguments for DNSCurve was that no one was using DNSSEC and that DNSSEC’s choice of crypto algorithms was weak. Adoption is still a problem for DNSSEC, but it supports many different crypto algorithms now so I assume that’s less of a problem.

I’d like to note that my OpenWRT DNS server seems to not pass on the AD flags. I’ve got it configured to use Google DNS upstream, so I get the benefit of the protection since Google simply won’t return records for broken domains, but clients won’t get to see if the records are properly signed or not. I think this is fixable, either by changing to a different DNS resolver in OpenWRT or maybe just telling dnsmasq to add DNSSEC.

Client support

The whole point of DNSSEC is to authenticate the DNS record all the way to the client. But I don’t think many (any?) consumer clients are validating DNSSEC themselves. Instead they are trusting their DNS server to validate for them. That violates the end-to-end principle.

On testing, I believe MacOS 10.9 does nothing with DNSSEC. If I manually set my DNS server to 4.2.2.1 (a Verizon server that does not do DNSSEC), Chrome can load the test pages with broken DNSSEC signatures. I suspect MacOS is just assuming you should trust your DNS server.

I didn’t test it, but I think stock Ubuntu does not do DNSSEC either. The glibc resolver doesn’t seem to have it. I did run across some libraries that do DNSSEC; libval, ldns, and knot. And if you’re running bind or dnsmasq you can enable DNSSEC on those.

I found one Chrome extension that verifies DNSSEC itself. Neat! But it requires a native binary plugin and that was more than I felt like dealing with.

Final thoughts

DNSSEC seems to mostly work, just adoption is slow. On the server side, the root DNS servers didn’t support it until July 2010; before then it would have been very awkward to use. For clients, Google DNS started doing DNSSEC in May 2013, so that’s been a good long while now. But end user clients aren’t doing anything themselves.

One question I didn’t explore is overhead. All those extra DNS records take memory and bandwidth to serve. And verifying signatures takes CPU time. I don’t think that’s prohibitive at the edges given all the room for caching, but the big DNS server operators may be worried.

 

New password

I needed to generate a new serious password so I decided to try to out the old Diceware / xkcd idea of a phrase made of nonsense words. I took inspiration from this article (as seen on Metafilter). I ended up using the Diceware list along with this Python generator. I probably could have just used this Diceware Javascript generator but some irrational part of me trusted a Python program installed on my own machine via pip more than a Javascript page.

Why not use the big list that xkcdpass has? Because it has too many obscure words (“filariae”). What’s nice about Diceware is it has a list of just 7776 short common words. According to that Javascript generator 6 Diceware words has 77 bits of entropy, which is good for 3500 years against an attacker making a trillion guesses a second.

The best thing about these long passphrases is they are easy to type on mobile keyboards. The whole l33+ thing we still childishly do is murder on an iPhone.

Somebits Games

Mostly putting this here so I don’t forget. I made a new Twitter account, @SomebitsGames, for uploading game screenshots and video clips. The PS4 has some very nice sharing features built in but I didn’t want to share them to my main Twitter account.

(Fallout 4 is awesome, y’all.)

Tweeting a torrent

A friend asked what the best way to tweet a Torrent would be. I thought the obvious thing would be to tweet the magnet link, but those tend to be too long to fit in 140 characters and Twitter’s URL shortener doesn’t work on magnet: links.

Why are magnet links so long any way? Here’s a working magnet link to a copy of wikipedia, an 11GB file named enwiki-20140707-pages-articles.xml.bz2:

magnet:?xt=urn:btih:e18b8cce7d9cb2726f5f40dcb857111ec573cad4&tr=http%3A%2F%2Facademictorrents.com%2Fannounce.php&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80%2Fannounce

That’s awfully wordy, let’s break it down and futz it to be readable.

magnet:?
xt=urn:btih:e18b8cce7d9cb2726f5f40dcb857111ec573cad4
tr=http://academictorrents.com/announce.php
tr=udp://tracker.publicbt.com:80/announce
tr=udp://tracker.openbittorrent.com:80/announce

The important thing is the hash in the xt parameter. That uniquely identifies the content and it can be addressed as such via DHT discovery. Those tr parameters just list trackers, which you don’t strictly need thanks to trackerless torrents. Indeed, the following 61 character URL works fine in Transmission.

magnet:?xt=urn:btih:e18b8cce7d9cb2726f5f40dcb857111ec573cad4

It’s not very convenient though. It lacks a filename, file size, etc. Startup time is (theoretically) slower as we have to discover data. I also don’t know how much of a performance impact removing the tracker list has, if any.

Of course one could add some of the missing bits back. “dn” is the displayed filename, “xl” is the file size.

The xt parameter is a bit subtle; there are at least 9 different hash algorithms that can be specified. BTIH seems to work well for torrents.

 

Home surveillance cameras

I want a security camera for my house, for when I’m away. Nothing too creepy or serious, just some peace of mind so I can see if a package got delivered or if the propane delivery guy came.

tl;dr; I’m going to try ZoneMinder with an Axis M1034-W camera.

The mainstream product everyone recommends is Dropcam. But it and its competitors all work by uploading a video feed 24/7 to a server they host which then does the processing to do useful things like only show video clips of motion, etc. They tend to charge $10/month for the hosting. And it’s a lot of bandwidth. So I’d rather roll my own, using my own Linux server. (Yes when Jack Bauer breaks in, Chloë will be able to knock my surveillance offline with a Linux zero-day. That’s not my threat model.)

The hacker solution for this stuff is surprisingly unclear. On the Linux video collection side, motion(1) is a popular low level tool for doing motion detection from video feeds. ZoneMinder seems to be the high end tool of choice for managing multiple cameras. It works with a lot of stuff including video capture devices hard-wired to the machine and network cameras.

I’m baffled by the choice of camera hardware. I decided to try Axis because they have a developer program, ZoneMinder works well with them, and they have a reputation for being good but expensive. I only need one camera so expensive is OK. The M10 line seems to be the low end stuff, $200 instead of $400+. The M1034-W is the WiFi option. They also make wired POE stuff which seems like it’d be good for outdoor use.

That’s all research. I ordered the camera, will tinker with it next week.

 

LoL lag on Wifi

When I play LoL with a wired connection to my router in Grass Valley it looks like this. But when I play via WiFi it looks like this. Periodic ping spikes, from the usual 85ms to 170ms or so. Note the packet loss number is the same, about 10 packets/s. This ping pattern is not particularly noticeable while playing, but sometimes on WiFi I’ve had serious lag, disconnects, etc. Not so much when wired.

The WiFi link is as good as it could be. I’m 10 feet from the router, clear line of site, 30dB SNA. 802.11n, 5GHz, relatively quiet network. Either there’s something broken with the hardware or else WiFi really is just this unreliable. Need to experiment more. I sure wish I knew what algorithm LoL used to report ping. Last time I did the packet dissection work it looked like it was the RTT time on special ping/pong packets. Maybe they get lost and are retransmitted?

OpenWRT second impressions

I’ve been running OpenWRT for a few days now. I like it. I also don’t like it. I’m going to keep running it, and will probably install it on any new routers in the future.

The part I like is it feels like a “real Unix”. I trust that it’s going to do its job right, or if it doesn’t I have access to look inside and figure out what went wrong. Tomato has always been opaque, and if it rebooted itself or didn’t do something I wanted I felt powerless to understand or fix it. With OpenWRT it’s all just a Linux distro.

The part I’m on the fence about is that it’s “real Unix”. In particular, that it’s super complicated. The ipchains have some 100+ rules in them, which really are defining about seven “zones”, which really are 4 physical interfaces and maybe 6 aliased interfaces. It’s great that the system is so flexible, but then it also makes even simple things hard.

vnstatThe part I don’t like is that it’s a “real Unix”, complete with that awful lack of usability. You can configure everything but you also have to configure everything. That’s a grand old Unix tradition, see also: Linux-on-the-desktop. As an example, I’d like a simple counter of bandwidth used per month. There’s none installed by default. But here’s a list of 17 tools that might do it. Only a few of those have Web UIs, and only ~half of them are installable via the package manager. And none do precisely what I want, the best I could find is something that churns out hideous 1990s-style gd images. Of course I could build my own, it’s Unix! But I don’t want to build my own.

I think there’s a need for a new router firmware, a nicely packaged distribution based on top of OpenWRT. Take the stock OpenWRT and add the packages that ordinary home router users need. Maybe write / package a few other things, like the monthly bandwidth monitor I would like. Then stick them all together with a nice GUI that ordinary technical savvy people can use, not just Linux/networking experts. Tomato is the model for this, the core Tomato firmware was a beautiful, well documented product. Tomato-on-OpenWRT would be terrific. It all seems doable, OpenWRT is a strong foundation. The only thing I’m not sure about is how hard it’d be to build the web UI. Luci is pretty flexible as a foundation, I think what I’m describing could just be a skin and set of Luci apps. But not sure.

Automatic: driving history

For two years I’ve had an Automatic tracker in my car, a gizmo that downloads data off the diagnostic port and uploads it to an iPhone app via Bluetooth. It tracks things like speed, mileage, etc but it turns out the most interesting thing it’s actually tracking is where I drive. But it’s not that interesting, and I’ve always been a bit nervous about the privacy implications of it, and rather than pair it to my new phone’s Bluetooth I’m going to stop using it.

Some summary stats from it:

  • 613 trips since September 2013
  • 11,290 miles in 252 hours. Average speed: 45mph.
  • 25 MPG average, $1600 in fuel

By far most of the hours in the car have been the 150 miles on I-80 between SF and Grass Valley.

The main use case the developers have in mind seems to be a nanny to encourage you to drive better. You get a “Score” that’s dinged down for driving over 60 mph, or braking too hard, or whatever. I found that condescending and useless. The IFTTT integration was sort of nice for creating data in Dropbox, but it wouldn’t export the GPS track. The product got a lot more useful when they added the Dashboard, with some nice Mapbox views of the data. Still I don’t have much use for collecting the data.

Here’s a heatmap they produced of all my driving. You can see all the I-80 trips, plus a long trip down to LA and back. Occasional detours through Stockton or Yuba City.

Automatic heat map

OpenWRT: persistent DNS entries

One wrinkle with OpenWRT: if the router reboots, it loses the DNS entries it was giving based on DHCP leases. Even the ones you’ve configured as static DHCP leases, they don’t show up until the client host renews its DHCP lease. Forum discussion suggests this is because dnsmasq is reading from the dhcp.leases file which is stored on tmpfs, not permanent storage.

The simple workaround is just to manually add the host in /etc/hosts and restart dnsmasq. It will serve those entries to DNS clients. That means the client’s IP address is now stored in two different places, which is not ideal, but I can live with it. There’s some discussion of other solutions for this like moving the DHCP lease file to permanent storage or changing the configuration tool to manage parallel entries in both DHCP and dnsmasq. As of 15.05, none of that seems to be happening.

I’m liking OpenWRT now. It’s comforting working with a router that’s a full and proper Linux distribution. It’s also sort of overkill, but on the balance I like it.

Networking complication

I’m in over my head with this wireless ethernet bridge thing. Story isn’t complete, but collecting my notes. There are further writeups of this question in forum posts I’ve made: on OpenWRT forums and on Ubiquiti forums.

The real problem is I don’t understand Linux networking any more. Ethernet address aliases are new to me, and I’m confusing routing and bridging, and my knowledge feels too outdated to diagnose this properly. Honestly if it hadn’t all Just Worked on my old Tomato box I’d never have believed this was possible.

I have three subnets:

  1. My home LAN, managed by my OpenWRT box, running 192.168.0.1/24.
  2. My ISP’s network, managed by their gear, running at 10.33.1.1/24.
  3. My management IP addresses for the Ubiquiti wireless bridge, mostly invisible, but running at 192.168.1.110/24 and 192.168.1.111/24.

The challenge is getting my OpenWRT router to be able to talk to the boxes at 192.168.1.*. With Tomato I just added a static route and all was done. I tried that with OpenWRT and no luck.

A lightbulb went off thanks to an answer on the Ubiquiti forums. The WAN port on my OpenWRT boxes now has two addresses: 10.33.1.50/24, assigned by the ISP via DHCP. And also 192.168.1.1/24, assigned manually by me to talk to the Ubiquiti gear. I managed to make that actually work by manually running “ip addr add 192.168.1.1/24 dev eth0”. And now I can talk to the Ubiquiti boxes!

BTW, this whole “ip addr” thing is new to me. In my day we used ifconfig and every interface had one address, thankyouverymuch. Kids these days with their multihoming and aliases and VLAN tagging and stuff. Just don’t understand it.

Update: I added this IP address alias permanently to the routers config by following these docs, which led me to add this block at the end of /etc/config/network

config interface 'ubiqnet'
    option 'ifname' 'eth0'
    option 'proto' 'static'
    option 'ipaddr' '192.168.1.1'
    option 'netmask' '255.255.255.0'

Those same docs have a worrying warning “On openwrt 12.09, a lan interface that is first defined as dhcp interface and then has aliases with static ip address could cause problems in routing the lan traffic through the wan zone”. I think that’s exactly what I’m doing but I’m running 15.05; maybe it’s no longer a problem?

Remote Wireshark capture

It’s easier than I thought to capture network traffic from a remote machine and display it in WireShark running on your local computer.

# one liner with named pipe
$ wireshark -k -i <(ssh root@192.168.0.1 "tcpdump -s 0 -U -w - not port 22")

# more explicit version of named pipe
$ mkfifo p
$ ssh root@192.168.0.1 "tcpdump -s 0 -U -w - not port 22" > p &
$ wireshark -k -i /tmp/p

# one liner with a normal pipe
$ ssh root@192.168.0.1 "tcpdump -s 0 -U -w - not port 22" | wireshark -k -i -

All three variants are doing the same thing; they ssh into the remote host you want to monitor and fire up tcpdump to get the packet stream via SSH. Then wireshark is launched to read from the stream.

The official docs for this talk about using named pipes, which is what the first two versions do. The <(command) thing is a special bash syntax for creating a named pipe for you, it’s just a more concise version of explicitly using mkfifo. The last version using stdin also seems to work for me but the docs say “it is not clear whether it always works”. The only mysterious thing I can think of is buffering questions, but I don’t know why a named pipe would be better than a normal pipe for that.

The tcpdump command is a tiny bit subtle. It’s important to not capture ssh traffic, since we’re using ssh as the transport and that’d create a feedback loop. The other options are basically “capture everything and don’t buffer”.

OpenWRT first impressions

I decided to get yet another new router, a TP-Link Archer C7 on the WireCutter recommendation. Mostly for 5GHz radio, but also as an excuse to play with new firmware. I’d really like some sort of reboot watchdog. My impression is both Tomato and DD-WRT are a bit long in the tooth and it’s time to try something new. OpenWRT has a lot of mindshare right now, I first noticed it because it’s the home of the fq_codel work for better QOS. Worth a try.

My first impression of OpenWRT is it’s definitely not for civilian use. Really it feels more like a nice custom stripped down Linux distribution you use from the command line, not a network appliance. If you just install it and run it you do get a basic working router. But some fundamental features like detailed bandwidth monitoring, Dynamic DNS, or UPnP/NAT-PMP aren’t enabled by default. And the Luci web GUI, while nice, is very technically oriented. For instance the default configuration screens are yammering at you about bridging and WLAN1 and a bunch of confusing stuff that I understand but your basic user won’t. I get the impression that really I shouldn’t be using the Web GUI at all, just log in via ssh and editing text files.

One specific reason I installed OpenWRT is that it has a lot of third party packages. In theory a lot of this is manageable via the web GUI but I couldn’t even find the “update package list” button so ended up running “opkg update” on the command line instead. It is awesome that OpenWRT has a sane package management system!

I like that OpenWRT is clearly designed to support IPv6 well.

Some interesting packages:

  • tcpdump: for network diagnostics
  • luci-app-sqm: fq_codel QOS. traffic shaper.
  • wget curl netcat: some basic things on hand. these have to install SSL, so it’s a significant download / disk space.
  • nano, less: unix file utilities
  • luci-app-statistics and collectd-mod-*: historical stats for router
  • luci-app-vnstat: more historical traffic stats
  • luci-app-upnp miniupnpd: UPnP and NAT-PMP port forwarding
  • watchcat: reboot if ping fails for a long time
  • luci-app-*: applications that have a Web UI for them. Many useful things here.

All in all OpenWRT seems great for someone lwho wants to build and maintain a custom router software installation. If you just want a basic router that works I think stock firmware may be a reasonable choice these days. Or else Tomato/Shibby, but that’s pretty wonky.

Now I’m trying to figure out my weird network setup to talk to the usually-transparent Ubiquiti boxes.

Don’t store JSON blobs in text columns in sqlite3

I decided to try something naïve and put big JSON blobs in a sqlite3 database. About 1700 of them, 150k each, data from League of Legends matches. I knew this was dumb but I did it anyway. And it was dumb, like 300MB of dumb. To be fair sqlite3 handles this just fine, but the single big file makes backups and caching awkward. And I wasn’t even using the column!

I rewrote the code to store the JSON blobs as gzip files instead. 36MB instead of 300MB, and each file doesn’t ever change once written. Just nicer all around. Kind of a pain to remove the data though. sqlite3 doesn’t let you drop columns so you have to make a temporary table to remove it. And even then the file didn’t get smaller on disk; I ended up doing a dump / restore to reclaim the space.

I still want sqlite-for-JSON, a simple JSON datastore. I see the JSON1 module made it into sqlite3 3.9, no longer draft. I should try it out. It’s not compiled in by default. Also I assume it’s not compressed. sqlite3 does have compressed database support, but only as a paid extension.

3d touch on iPhone 6S

I was curious how the 3D Touch feature worked on the iPhone 6S. Here’s a reasonable explanation based on a iFixit teardown. tl;dr: low resolution capacitive sensors measure the distance between your finger and the base of the phone. The glass bends a bit.

I can’t say I find the UI gesture very useful. The lack of true tactile feedback makes it hard to know which gesture you’re making, and the lack of much in the UI using the sensor means often nothing happens. We need someone to figure out a great use for it, and that in turn probably requires more market saturation.

Notes on an iPhone upgrade

I just upgraded my iPhone 5S to a 6S. The basic backup-and-restore process works remarkably well, as did Verizon’s activation. However a bunch of stuff didn’t carry over. Some of this is my own fault, some of it is security, and some of it is just dumb.

  • Logins. I had to log back in to all these apps like Twitter, Gmail, etc. I’m not using the iCloud Keychain, perhaps that would have solved this. Some apps like Uber, Nest, and TriMet Tickets seem to not work after the restore to new device; the login hangs. It’s not consistent, some apps worked fine. Uber even asked for a password, then hung. I had to delete and reinstall it.
  • Authenticator tokens. I have three MFA tokens on Google Authenticator as well as a separate authenticator from Blizzard. Had to manually set those up again on the new device, which in many cases requires access to the old device’s authenticator. Again I think iCloud Keychain might have helped with this.
  • Music. None of my music copied over. That’s probably because I got hit with another iTunes debacle at some point and iTunes on my computer didn’t have access to my music library. Apple refuses to copy music off of an iPhone, I guess because they think that’s a meaningful piracy prevention mechanism.
  • Cached app data. Some apps cache data locally, like Overcast’s podcasts. That cache seems to have not been copied over. That’s not terrible, but mildly inconvenient.
  • Application data. iOS has a sort of per-app filesystem you can find, where some apps like Wiki Offline store data they downloaded. None of that data was saved or restored. This seems like a serious flaw to me; oftentimes that data is irreplaceable, or at least inconvenient to restore. I ended up copying it over manually.
  • OpenVPN setup. The basic “enable VPN” button still works, so something carried over. But the OpenVPN app was not installed correctly; greyed out for some reason. Also the OpenVPN app has a file in the per-app filesystem I need.

Hotel internet woes

Travelling in France, various problems with hotel Internet:

  • The one whose captive portal logs you out every 15 minutes
  • The one that resets HTTP requests for various Javascript libraries, including some basic things likes like JQuery and Dojo. On further inspection my guess is it has a whitelist of allowed Javascript URLs and blocks all others.
  • The one that requires an email address and gives you 10 minutes to verify a code sent to it. After entering the code your 10 minutes is not extended, but logging in again with the same credentials does work.
  • The one that doesn’t allow SSH connections.
  • The one whose captive portal aggressively intercepts connections sometimes breaking web page reloads.
  • The one that is just crushingly slow.
  • The one that is sort of fast on download but 400kbps on upload. Trying to Tweet a 2MB photo times out.
  • The one that works reasonably well, if slowly, but 1 of the 12 wifi access points is broken. The one closest to my room, and me with no idea how to tell my computer to ignore that single access point. They brought a new access point for me, some ZyXEL consumer hardware. It works better but the antenna is broken off so the WiFi is weaker than the rogue bad AP. Fortunately the ethernet switch on it worked so I was able to use my own wifi router.
  • The one whose captive portal can’t capture Google, so the obvious way of triggering the login capture process does not work.

France has a particular problem in that the law requires all Internet users have to identify themselves. A requirement which is not always reliably enforced, but it seems to be enough that few places are willing to just let you connect to a WiFi node; you have to type in some form of identification. Hotels love getting your email address, of course.

The real problem is all this captive portal hackery; it may be an even worse networking abomination than NAT. Wasn’t there some effort to at least standardize a captive portal response so your browser understands that “www.google.com” isn’t actually a page for a shitty Novotel?

Needs more MPEG

Remarkably prominent video compression artifacts in this video. Note the 8x8 rectangles at bottom, those are supposed to be mice being chopped to bits.

Screen Shot 2015-09-23 at 9.37.54 AM

(From Scratchtasia, the Simpsons / Itchy & Scratchy parody of Fantasia. Specifically the Sorceror’s Apprentice sequence, which every software engineer should know and love.)

Butt-based machine learning

I’ve been doing somework with scikit-learn but running code on your own computers is for chumps, why not do our machine learning in the butt in the cloud? Here’s the offerings from a few, there are lots of others, too. This cross-service developer test is interesting data on prediction and running times.

Google Prediction API. $0.50 / 1000 predictions, $0.002/MB of training data. Focussed on training prediction models, both numeric (regression) and categorical. Didn’t see any documentation of what kind of algorithms they implement.

Amazon Machine Learning. $0.10 / 1000 predictions, $0.42 / hour for training. The FAQ says it does logistic regression, but the docs say it does both categorical and numeric predictions. They also have some data exploration tools and quality metrics.

Microsoft Azure Machine Learning. $0.50 / 1000 “API transactions”, $2 / hour. Also a per-seat charge which is completely “lol Microsoft”, I mean seriously? Offers classification but also other stuff: text analytics, vision, speech. The algorithm cheatsheet makes it look liek you have a lot of choices for basic prediction algorithms, too.

BigML: $0.10 / 1000 predictions, $0.01/MB of training data. Didn’t review what all algorithms it supports, clearly they do predictions. They’re a startup up in Portland and in Spain, with just $1.6M in funding in 4 years.

I’m not qualified to evaluate these yet. Google’s the oldest and simplest, also the most limited. Amazon’s product looks pretty simple and pretty. Microsoft’s has the most bells and whistles but you have to wade through Microsoft’s sales cluelessness. No idea on BigML but I like the idea of a startup making headway here.

JSON1, a SQLite extension

A couple months back I expressed a desire for a SQLite-for-JSON system. And someone’s done it! I got here from this Hacker News discussion about a different system.

JSON1/SQLite

JSON1 is a draft SQLite extension for JSON. Here’s notes on how to use it in Python, including a demo notebook. Still some rough edges, but it’s promising.

JSON is stored as type text. No binary encoding, the docs say the improvement isn’t worth the trouble. JSON arrays are used as a container type in parts of the query language, for things that return N JSON blobs. There’s also some SQLite virtual tables that are created by advanced query methods.

There’s the basic functions you’d expect for manipulating JSON, mostly setting and changing properties on a JSON object.

For basic query, json_extract() is the basic function that pulls out pieces of a document based on a query path. (Ie: $.title means “give me the title property”, $.authors[2] means “give me the 3rd element of the array that is the value of the authors property”)

For advanced query, json_each() and json_tree() turn a single JSON blob into a virtual table you can then query. The table has a schema with one JSON column per property queried, as well as some other data related to the query like integer IDs and the path. json_each() only queries the top level properties, json_tree() is a recursive search.

I like it, it looks really promising. Maybe not quite ready for civilian use yet, but soon? The discussion a month ago advises we “check back soon”.

My one mild concern is that JSON data tends to be really big. Like I have 1000 LoL matches in a SQLite database, each one a 200kb JSON blob. And no surprise, it’s a 200MB file! That starts to get awkward for backups, etc, and is kinda dumb since the JSON is immutable. It’d be better to store them as read-only files but that’s not compatible with SQLite’s design.

JSONlite

JSONlite is the topic of the HN post that let me to JSON1. It’s a valiant effort, a set of bash scripts to store JSON as files and retrieve them with UUIDs. It’s not a bad little wrapper but it’s very simple. And no query interface, which to me is the interesting part, although one could probably just use jq on the backend store.

UnQLite

UnQLite also came up, in this description. “UnQLite is to MongoDB what SQLite is to Postgres”, which sounds good to me! It uses Jx9 for query. I didn’t look any further; it seems promising, but my general rule with tech like this is wait for critical mass before investing any time.

SVMs in Python

I started trying to apply SVM machine learning to my Battlefield 4 dataset and got something that only predicted my data with 60% accuracy. I’m expecting 95% or more but I don’t really know and I realized I was trying to learn too many new things at once.

So I went back to my Coursera homework, exercise 6, and used their data and problem sets as Python exercises. Specifically I trained SVM classifiers on two datasets. The result is in this notebook.

Cells 2–4 are me simply fitting a binary classifier to the toy input data. Cells 5–9 are fitting a binary classifier to different data, in this case performing repeated training steps to pick the right parameters C and sigma for the learning system. I did it the homework’s way in cells 6–7, using an explicitly split training and test dataset. Then I used sklearn’s cross_validation library to do the training in 8–9, which is a form of resampling to produce test sets on the fly. Results were roughly the same. I’m not 100% certain it is philosophically kosher to use CV in this manner, but I think it is.

Things I learned:

  • You can load matlab arrays with scipy.io.loadmat()
  • The ‘rbf’ kernel is what sklearn.svm calls the Gaussian kernel.
  • Instead of sigma, sklearn parameterizes rbf with gamma. gamma = 0.5/sigma**2
  • Decision boundaries are plotted by simply creating a raster grid of predictions, then making a contour plot to only show the boundary.

The big thing I learned is how sensitive these systems are to choices of sigma and C. Before I had the code working right I was using bad values and getting insane results. Relatively easy to see in a 2d dataset where you can plot the data and the decision boundary, but this must be much harder to understand and debug in large multidimensional datasets.

Machine Learning: reflections on the Coursera course

I’m all done with my Machine Learning course on Coursera, and I wrote a lot about it as I was taking it. Time to look back and put it together.

First off, it was a good use of my time. I complained about aspects of the course and I definitely think it can be improved. But it was a good introduction to what machine learning is and enough hands-on that I feel like I can no go do my own work with real tools. I also mostly liked the Coursera structure, having weekly deadlines and assignments was the structure I needed to actually learn something.

Techniques and Approaches

The thing I was most interested in learning is the general gestalt of machine learning, like how to sit down and get a problem solved. That was covered reasonably well through the course to varying degrees. Some themes:

  • The general structure of “take a training set of data. train a model on it. evaluate the mode against your test set. apply the model”. In some sense all the machine learning systems do the same thing: map a vector of input data to a scalar output value. The various algorithms are just different approaches to learning how to map input data to outputs. I didn’t understand they all fit into this category before.
  • The specific way that the training step is basically just running a function minimizer over your cost function (ie: measure of error). The subtlety here is most minimizers require some understanding of the gradient as well, which means you need to take partial derivatives of your cost function. (I wonder if numeric approximations to the derivative are useful in practice?)
  • The concept of high bias vs high variance models, ie: overfitting the data vs. underfitting the data. Basically if your choice of algorithm has a lot of internal knobs to twiddle, it’s likely you have high variance and might overfit the data, particularly if you don’t have a big data sample. Alternately if your chosen model is too simple the system might not ever predict the data well because it lacks the expressive power. I particularly liked the way you can detect which problem your system has with measuring the learning curve, how well your system learns based on how much data you give it.
  • Precision, recall, and f-score as a way to evaluate the success of a model.
  • A principled way to normalize data so that all your numbers are on comparable scales of roughly -1 to 1, with mean 0.
  • Regularized learning algorithms, with an extra term in the cost function to discourage overfitting.
  • Machine learning pipelines. The way you can segment a broad problem like photo OCR or automatic driving into smaller machine learning problems. Also ceiling analysis to figure out which part of your pipeline could be improved the most.
  • Stochastic machine learning. For very large datasets just iteratively learn on subsets of the data. Naturally leads to online learning, systems that continually learn in response to new data.

Algorithms

Most of the class was a tour through machine learning algorithms. Too much time implementing those algorithms for my tastes, but at least there’s no mystery to many of them now. Things we learned:

Supervised learning (ie: your training data is classified with expected outputs you are trying to predict.)

  • Linear regression: fit a linear model to the data. Predict a single number from a vector of numerical inputs.
  • Logistic regression: fit a logistic model to the data. Predict a single binary classifier from a vector of numerical inputs. (Really it outputs a probability!) Can predict N classes with one-vs-all classes.
  • Neural networks. Fit multi-stage regression to the data. Hidden layers can discover and calculate their own learned features. Good for non-linear models.
  • Support Vector Machines: logistic regression with a different error function that encourages your system to make sharp distinctions when classifying data. Also pluggable kernels, which allow you to change the function applied to features being considered to get beyond linear models. I got the impression SVMs with Gaussian kernels are the right choice in practice for many problems.

Unsupervised learning (no expected output on hand)

  • K-means clustering. Group your data into K natural clusters.
  • Principle component analysis. Boil high dimensional data down to fewer dimensions, while measuring and minimizing the loss of meaningful data.
  • Anomaly detection. Find data examples way outside the mean.
  • Collaborative filtering. Learn from user preferences what features of something result in those user preferences.

Practical skills

Practical application of subject matter was the weakest part of the course. The primary new technical skill I learned was Octave. But that feels like an increasingly obsolete tech and I wish I were using a language I’d be using more later. OTOH it was fun programming in a matrix math language with vectorization. I think if I were reimplementing this course today with the same curriculum, I’d consider using R and a notebook environment.

There were some real applied problems like number OCR and spam classification and movie recommendations. Those were interesting to me, but the exercises tended to have us solving one piece of a system to learn the data rather than putting the whole thing together.

I keep thinking it’d be fun to design an alternate machine learning course, one that focusses on the more practical application. Start with you downloading and pre-processing data. Then create a machine learning experimentation pipeline, plugging in out-of-the-box algorithms rather than implementing the algorithms yourself. Then go back and iteratively improve your application of ML, evaluating with learning curves and test data sets and honing the system so it really works.That’s a different course, but if I were doing that I’d do it in Python with scikit-learn and IPython notebooks.

What I missed

As noted above, the main thing I missed is more practical application. But that’s OK, because I think I learned enough to teach myself the practical stuff.

I also wish the course had a broad overview of more algorithms. There are literally thousands of machine learning algorithms in use out there, and while I trust we hit the most important basic concepts I’d have loved a single week which was just a whirlwind tour. Bayesian inference, decision trees, Markov models, ... so many options.

Next steps

Now on to applying what I’ve learned to my own data. I already did one little exercise in PCA and clustering with Battlefield 4 data, which was a good experience. I should really try applying SVMs to something next. Maybe League of Legends match data, but it’s hard to get a large sample with the default API rate limiting.

What I really want to do is try applying this stuff to map data. Some machine learning system to improve OpenStreetMap, maybe by identifying anomalies comparing the vector map users generate to raster aerial imagery.

Machine Learning: Photo OCR, real world problem

These last two weeks of the course were so short I finished them all in one day.

I liked this last week, week 11. Most of the lectures were about a real world machine learning problem: finding and OCRing text in photographs.

Photo OCR

The key idea here is the pipeline. He broke the problem up into 4 separate machine learning problems that can be worked on independently.

  1. Find regions of the image that look like text.
  2. Segment text regions into individual characters.
  3. OCR individual characters
  4. Spell correct OCR errors

The real meat of the lesson was the sliding windows algorithm, the technique by which you identify text regions. Basically you look at small square regions of the image and train a recognizer to identify text/not-text. Then you merge adjacent regions of text into single blobs for handing off to step 2, the segmenter. The segmenter also uses a sliding windows analysis to find whitespace between characters, albeit a 1d window.

Lessons for machine learning

Second half of the lesson was reflections on doing better for machine learning.

First question: do you need more data? It may be expensive to get it. More data is most useful for low bias machine learning algorithms, so don’t bother if you have an overfit model. (Or rather, loosen your model first!). He also talked about artificial data synthesis, ways to generate more data from existing labelled training sets. For instance if you’re doing voice recognition, maybe you can generate more training examples by adding real-world distortion to existing examples. However don’t just add random noise, since that doesn’t really train anything useful.

Second question: what should I work on next? The key idea here is ceiling analysis. Basically you go down your pipeline replacing each step with a perfect system. Ie, replace step 1 with a perfect text region classifier; how much does your system improve? Now also replace step 2 with a perfect segementer: how much better does your system do? With that experiment in hand you can identify which steps in the pipeline have the most room for improvement, are worth your time to work on.

Once again I wish there were a programming exercise here to hammer these lessons home. Have us construct our own pipeline and do some testing / segmentation on it. I think this would be a good time to revisit the ideas of training vs. test sets, applying the test set well. Also evaluating systems for bias/variance problems. I suspect the Stanford undergrad class had students doing some final project which was just left out of the Coursera class, perhaps because it would be impossible to grade. Guess it’s up to me to apply this stuff to real problems and make my own mistakes without a teacher to tell me how I’m doing. Unsupervised learning, as it were.

And that’s the course! I’ve got one more blog post coming summarizing what all we covered and what I thought. Overall I’m quite positive, it was a good use of my time.

Machine Learning: large scale learning

Major shift of tone in week 10 of my course. Less detailed algorithms and programming assigments, more of a “here’s some wisdom about real world use”. Well a bit of each, but no programming. Being this high level makes me feel a bit dislocated, I appreciate more now the harder assignments in previous weeks.

Stochastic Gradient Descent

Most of the lecture was on the problem of running machine learning algorithms on enormous data sets, say 100,000,000 examples. These algorithms tend to be of the form “calculate this cost function over all data. then average the cost and update theta, our model parameters”. That’s inefficient when your data is 100M examples! So instead we update theta based on only some of the example set.

Stochastic gradient descent has you doing gradient descent where you update theta once per data example. That means that instead of swiftly following the gradient down to the optimum your optimizer is now doing a bit of a drunken walk, but in the right direction towards the optimum. And with a huge amount of data you can get away with looking at all the data a little less often. Ie: a normal batch gradient descent may do 100 evaluations of all 100M data points. With stochastic you can get away with 1-10 evaluations of the 100M data points. I assume law of large numbers is why. One caveat: it’s important to iterate through your data in a random order, shuffle the data first.

“Mini batch” gradient descent is a middle ground where you calculate the cost over, say, 1000 samples before updating theta. Stochastic looks at 1 sample at a time, batch looks at all N, mini-batch looks at a subset of say 1000. The reason you do this middle ground is because you can still get some benefits of vectorization and/or parallelization.

Convergence is a bit woolly with these stochastic approaches. You still want to monitor convergence, but you really don’t want to calculate the cost function over the whole 100M data samples every time! So instead look at a sliding window of the last, say, 100 cost function calculations you did and monitor it to make sure it’s converging.

Online Learning

Closely related to stochastic machine learning is online learning, where your machine learning model is updating itself continuously in response to new user input. That’s how real websites work. The neat thing about this is your model will adapt to changes in the world over time. Ie: you may have trained a perfect spam classifier in 2013, but spam techniques changed. An online learning system will adapt to new techniques as new data comes in.

Parallelism and map reduce

Last lecture was a funny coda which was basically “oh yeah, you want to run machine learning in parallel on big data!” along with “there’s this thing called map reduce you should know about”. It’s obvious how many ML algorithms are embarrassingly parallel over the input data, so maybe it’s fine to go quickly over this. But a simple map reduce implementation of, say, linear regression would have been a great programming exercise. Perhaps not in Octave though, maybe that’s why they skipped it. I wonder if scikit-learn has support for map reduce? Quick search suggests not really, you roll your own on top of Hadoop.

My first iPython notebook

I finally sat down and learned some IPython for data exploration today. I re-examined some data I had for Battlefield 4 players, something I’d published as my BF4Plots visualization a year or two ago. It’s the stats on ~5000 top Battlefield 4 players, things like their win/loss ratio, skill score, etc.

You can see my notebook in this gist. That’s a static snapshot taken from my last run. If you run it yourself the results will change slightly as some of the algorithms I apply include randomization.

My main goal here was to get more comfortable using IPython. It’s awesome! I really love having the inline, easy to produce graphs. I mostly followed this tutorial for guidance.

Secondarily I was also trying to apply some cluster analysis to my BF4 data to see if I could learn any insights. Not really. This is my first foray into my own machine learning project applying stuff I’ve learned in my course. And it was interesting, I definitely felt I understood what the scikit algorithms were doing. Also a little lost how to get real meaning out of the data. No surprise, that’s the hard part!

The main IPython thing I’m still adjusting to is that it’s a notebook, not a program. I’m so used to iteratively working and re-running my program from scratch. But IPython encourages you to keep a persistent Python VM around and iteratively add to its state. I keep looking for the “Start over and run it all from scratch” button, and there sort of is one, but that’s not really how you’re supposed to work. Which got me into trouble a couple of times. Also I do wonder how IPython people transition their code to running programs for other people to reuse.

Update: a “restart and run all” button was just merged into the main codebase so that’s coming soon. And apparently I’m right that notebooks are more for exploration. When it comes time to create reusable code you create a normal module with some other code editing environment. You can certainly start by pasting your notebook-developed code over, though.

First Python library I learned was Pandas, the data management library. Really all I did was work a bit with DataFrame, which is a data container type that’s a 2d array on steroids. Columns are typed, everything’s nicely addressable and searchable, and it’s all efficient numeric spare arrays behind the scenes. I think it even supports multicore number crunching in a transparent fashion. Really nice library, a joy to use.

Second library I learned was matplotlib, some basic bashing at it to draw some graphs. It’s really great and I wish I’d invested the time to learn this before. But until I saw the HTML notebooks it wasn’t very compelling to me. It’s funny, Mathematica notebooks have been a thing for 20+ years but it’s only the last couple of years where Python caught up.

Final thing I learned was a bit of scikit-learn, in particular how to apply its PCA and K-Means algorithms. Went pretty smoothly. My only annoyance is it seems to only half-support Pandas. It will take DataFrames as inputs but then the objects it returns are basic numpy Arrays which lack column names and some of the nice slicing options. I can’t tell if I’m doing it wrong, it has to be this way, or if it’s just that Pandas is so new that scikit-learn hasn’t fully adopted it yet.

Anyway, all in all my experiment was a big success, very happy. Fun stuff!

IPython notebooks + geodata

IPython notebooks (ie: Jupyter) seem like an important innovation for me. A really nice web-native REPL for exploratory programming, including decent visualization of data. Plot data in particular, graphing with matplotlib. It’s quite capable, I think approaching what people do with R.

So I’ve been asking around about adding geodata capability to Jupyter. My first thought was a visualizer for GeoJSON, but I’ve learned now there are other approaches. I asked SeanG and he pointed me to a couple of things, which lead to some other things.

Summary: there are several geodata visualization packages that work with IPython. Some integrate with matplotlib and some are standalone geographic tools. None of them quite worked right for me after just a few minutes tinkering, but several seem worth the effort to get working.

folium is closest to what I’m looking for. It’s a Leaflet wrapper for Python with baked in support for geojson, various Stamen tilesets, etc. It seems to support inline plots in IPython notebooks but I couldn’t figure it out, there’s been some discussion that it should work. It doesn’t use matplotlib.

leafletwidget is another Leaflet-based map making tool, here’s an example notebook screenshot. It’s not packaged on PyPI and hasn’t been updated in awhile, looks like it’d take some effort to figure out how to use. But it might be a good basis for building my own thing.

mpleaflet lets you visualize matplotlib plots using Leaflet to add a geographical basemap. It looks very promising but I had some trouble using it out of the box. The key thing here is adding map capability to matplotlib, the primary charting visualization library IPython users use already. Seems good for data visualization but less map-specific.

matplotlib basemap toolkit is a more low-level tool for making maps with matplotlib. No Leaflet or otherwise fancy slippy map, it’s just helping you do map projections and draw geographic data in a single static image. Might be nice for one off visualizations!

cartopy is another non-leaflet map maker in python using matplotlib. It has support for using GoogleTiles. IPython support is not mentioned in the docs but it seems to work.

mpld3 has nothing to do with maps but is neat. It adds D3 rendering for matplotlib plots in your notebook, so you have fancy interactive javascript instead of a static image. Works great right out of the box. I want something that works like this for geodata. See also mplexporter, which seems to handle getting the data out of matplotlib.

GeoPandas is a bridge between Pandas and geographic data, including shapeley/fiona support. It uses descartes too, which is a bridge from geodata to matplotlib plots.

Cheating at League of Legends

A lot of people cheat while playing League of Legends. My impression is it’s not so bad that it ruins the game, but it sure is annoying.

Network invalidation

The simple and dumb cheats are denial of service attacks and drophacking. (See this discussion.) DoS attacks are directed against an enemy player in your game. Somehow you already know their IP address, and then you pay a couple of bucks to a bot farm to knock them offline. This happens a lot to high Elo players, particularly streamers. Poor Rivington (a Riot employee) basically couldn’t stream for a whole week because he’d be knocked offline every time he tried to play. Riot can’t stop DoS attacks directly, but they could definitely make it less appealing by having some sort of game invalidation if players are disconnected through most of the game. For some reason they’ve never wanted to implement that. DotA 2 has a good system.

Drophacking is a similar network denial attack, only in this case when you’re losing you crash the game server so it invalidates the whole game. This attack seems less common but not unknown and there’ve been a couple of severe instances at specific times, I assume once someone finds an exploit. Riot seems to be pretty quick about stopping drophacking, which is certainly expected given they control the server code.

Scripting

The other half of cheating is scripting, code running on the player’s computer to help them play better. I’ve seen a couple of what look like scripters to me in game. Specifically someone playing Sivir, where she’d cast her spell shield with inhuman swiftness to block my attempts to hook her as Thresh. I mean maybe she was just very good, but there was the time I cast the hook from inside a bush and she had at best 100ms to press E and yet there she is, pressing E. Or having a script press it for her.

Mostly this seems to be done via DLLs injected into the LoL process itself. The DLL allows Lua scripts to run, alter the UI, and perform player actions automatically. Two popular scripting tools are L# and Bot of Legends. Bot of Legends costs $10/month. Here’s a video of what it looks like to play with BoL.

There’s a huge variety of community-supplied scripts. See BoL Script Status for a gallery of scripts. Unfortunately most of the links go to paywalled forum posts. But scripts seem to be shared on GitHub. Here’s a couple of users I found: BoLFantastik, DraconisBoL.

Here’s an example code snippet that casts Ignite if it will guarantee a kill.

function AutoIgnite(enemy)
        iDmg = ((IREADY and getDmg("IGNITE", enemy, myHero)) or 0)
        if enemy.health <= iDmg and GetDistance(enemy) <= 600 and ignite ~= nil
                then
                        if IREADY then CastSpell(ignite, enemy) end
        end
end

Augmented intelligence

People who cheat at games baffle me, and make me angry when I play against them. But I do find the idea of augmented intelligence interesting, machine tools assisting people in doing things they intend. Like the Zed video I linked above has a short bit for “Jungle clear”, where you tell it “I want to kill this monster” and it combos your skills efficiently for max damage. The Insec video is another good example, scripting the ward / hop / kick combo that is a famously high skill play. Or not anymore, just press the button.

One challenge is UI for augmented intelligence, how do you present these higher level actions to the user? From the few videos I’ve seen there’s nothing impressive. That Insec video just shows a minimal line you draw, which way the enemy will go when you do it. Spare, but functional. Some of the other videos I’ve shown overload the player with information, drawing overlapping circles over everything. Maybe useful for debugging but not anything else.

The other question I have for scripting is how much it really helps the player. I have no doubt that spell-shielding Sivir was getting boosted by a tool that prevented me from hooking her. But there’s still a person in control of the character, it’s not a full bot, and she’s still having to make choices about where to go on the map and what to attack and when to go in or flee. I don’t think these scripts help with that. My gut feeling is the scripts probably cover about 40% of what a good player needs to do, the other 60% is up to them to do themselves. What’s funny is I’m in the bottom 25% of players. So if I see a scripter, they must be truly terrible if they have a 40% boost.

Machine Learning: anomaly detection, recommender systems

Week 9 of 11, and the last week with coding homework!

Anomaly Detection

The first unit of lectures was on anomaly detection: picking outliers out of a dataset. Very simple compared to previous algorithms we’ve studied. In the one feature case it boils down to “calculate the mean and standard deviation of the input set. Values way outside the mean are anomalies”. He does define it carefully in terms of Gaussian probability distributions, which is the solid way to do this at least.

So what about multi-featured data? Instead of doing proper multivariate Gaussians, the course focusses on handling vector input data by analyzing a single-variable Gaussian separately for each input feature, then calculating the product of all the probabilities to label the full vector. The result is a special case of the general multivariate Gaussian, in particular it’s a case that only really makes sense if you believe there’s no correlations between your input features. If you do it this limited way you’re stuck having to inspect the data to define new synthetic features, like “height times width” based on domain knowledge that the area of something is more relevant than the height or the width itself.

There are optional lectures on multivariate Gaussians but I’m left wondering why the course just doesn’t start there. Maybe to simplify the math (ha!) or maybe because the special case is more efficient to calculate. He notes the multivariate case doesn’t work well if you have more features that data samples. But if that’s the case, you probably shouldn’t be trying some fancy statistics on your meagre dataset anyway. (The irony is the homework code actually does use the multivariate Gaussian afterall.)

The artful step of applying anomaly detection is determining the threshold for what an anomaly is. Ie: if the datapoint has probability of 0.9 it’s clearly good. 0.1? Probably. But 0.01? Or 0.001? Or 0.0001? How improbable does it have to be before you decide it’s an anomaly? The course has us iteratively learning a good epsilon threshold for discrimination, using a classified test set. But we have the standard deviation of the good data available to us; surely it’d be better to talk about “5 standard deviations out” being a threshold? Or maybe that’s implicit in the Gaussian probability calculation?

The programming homework was awfully simple. The solution for the first part of the first question is literally “mu = mean(X);”. I have come to appreciate how nice Octave is about writing vectorized code for computing with vector and matrix data. So much nicer than writing loops!

Recommender systems

Second unit was on recommender systems, specifically collaborative filtering. This is serious throwback for me; when I started grad school in 1996 my group was all excited because some previous students had just gone off to found Firefly, a company to do collaborative filtering recommendations. They did sort of OK and finally sold to Microsoft 6 years later for a rumored $40M. IIRC the machine learning part wasn’t the real value of the company in the end, but rather some engineering details of how they built it.

Anyway, collaborative filtering is a neat algorithm because it lets a machine learning system really learn something. You give it a big batch of user ratings of, say, movies. The system divines hidden features for those movies that best predict why people have preferences for certain movies. (Ie: maybe it figures out there’s a grouping which is roughly “action movies”). Then you can use these learned features to go back and predict ratings you haven’t seen before.

I particularly like the way Ng presented the algorithm first as an iterative problem. “Use ratings to predict features. Then use those features to predict ratings. Then use those to improve your feature predictions, ...”. But in the end it all gets collapsed into a single optimization problem.

OTOH I still hate the math and notation presented in the lectures, it’s just impenetrable. I understand the gist of what it’s doing but what is this supposed to convey? My desire now is that the course not be taught with math notation but instead Octave code notation, so that all those ugly sums and stuff are replaced with simple vector math code samples.

ss

One thing the lecture didn’t take is how you decide how many features to let the system learn. I believe this choice is arbitrary but probably essential to good performance. Someone else already asked in the course discussion. The mentor answered saying basically “try the smallest number that works well on test data”.

I was dreading the homework, since it’s yet again a “translate the confusing math to code” exercise. But having done this kind of thing a few times and with the mentor’s course notes as a guide, it’s pretty straightforward. Particularly to just do a vectorized implementation instead of the for loops the lecture definitions and exercises suggest. Seriously, I think this course got its approach wrong, it’s insane to try to do the calculations unvectorized in a language like Matlab. Both for clarity and performance. The lectures should teach to this approach.

The exercises build up to an actual movie recommender system (using MovieLens data). Neat! Only the homework is flubbed. With the originally supplied code we tell the recommender we liked Alien and Die Hard 2 and then it recommends Star Wars and Braveheart. Makes sense, right? Only the predicted rating I will give these films is 8.9 on a scale of 1–5. Oops. But at least the list of recommended movies is plausible.

Turns out the supplied code forgot to use some normalized values. So I fix that code as instructed and run it again, and now the highest predicted rating is 5. Good! Only now the list of recommended films are completely obscure movies like “Santa with Muscles” and “Aiqing wansui”. I’m left wondering if there’s still a bug in the code or this is a cruel lesson in the confusing vagaries of trained machine learning systems. I looked more closely and the recommendations I expect are there at the top, just not the very top. Still, it’s a disappointing end to the homework problem.

No more programming!

And a disappointing end to the course’s programming assignments. That’s the last one. There’s two more weeks of lectures and short quizzes, but no more coding. I’m sort of glad because hey! no homework! But also sad because I was hoping I’d learn more from the coding assignments.

I’ll say it one last time; I’d love a class that focussed more on application of machine learning systems. I really don’t need to implement the code for neural network back propagation or the fiddly details of collaborative learning. Or rather if I’m going to be doing that, I should be doing it on a graduate level with real math as the foundation. I’m fine with an introductory course being more shallow, but then I wish the programming exercises skipped the half-assed algorithm implementation and focussed on applications, on coaxing good results from these algorithms.

I realize I’m being cranky and truly I’m grateful that the course exists. I certainly appreciate that it’s free! Mostly my criticism is intended as “how could this be better?”.

Machine Learning: k-means clustering, principal component analysis

This week’s lectures were our first foray into what is bizarrely called “unsupervised machine learning”. All our previous algorithms were given data features and correct classification as inputs. This time around all we get are data features, these are algorithms to try to classify / understand the data without guidance. It all seemed much simpler than previous weeks, particularly the assignments, I don’t know if I’m getting smarter or the material is just easier. I vaguely remember enough math from college that this all seemed pretty straightforward.

K-Means Clustering

K_Means clustering is a way to classify a bunch of inputs into a relatively small set of “K” clusters. It’s easy to illustrate visually:

Screen Shot 2015-09-04 at 3.29.05 PM

The dots represent data input points, 2 dimensions of input data. Visually we can see these naturally fall into two clusters, helpfully colored here red and blue. Note the input data to this algorithm is not labelled, we don’t know what’s red and blue. The point of k-means clustering is to discover those red/blue labels. Once k-means has converged the model has two points, here marked in Xs. Those are the centroids of the two clusters. The way the algorithm works is you pick points at random to be your cluster centroids, then iteratively optimize that updating centroids so as to minimize the distance between every point in a cluster and its centroid.

Intuitively this is a pretty simple algorithm, and it is effective. Where people get tripped up is that our intuitions about “distance” and “near” from 2 or 3 dimensional spaces don’t really work for 1000+ dimensional data that’s often what we study. Ng didn’t go over that, just wisdom i’ve picked up from friends.

One thing I hadn’t known is that k-means is useful even when the data isn’t strictly clustered. For instance say you have height/weight of people, a continuous smear of points. Now say you want to sell t-shirts in three sizes: Small, Medium, Large. So cluster your data into three clusters and the centroids are the mean person you should make that size for. Kinda neat.

The art of applying k-means is knowing how to pick K, how many clusters. He presented the “elbow method” which basically lets you keep making K bigger until you don’t get a significant improvement in the error from its application.

Principle Component Analysis

PCA is an algorithm to project a high dimensional dataset down to a lower dimensional dataset. You can use this to project 10,000 dimensional input data down to, say, 1000 dimensions so that then your learning algorithms run faster because there’s less data. Or you can try to project data down to 2 or 3 dimensions for visualization.

The actual PCA algorithm basically boils down to “calculate eigenvectors”. Which Ng sort of said was the case, while not assuming the student knows what an eigenvector is. It was a pretty clear explanation really.

You still have to choose how many dimensions you want in your reduced dataset. His heuristic is “You want 99 percent of value retained”, which means “accept up to 1% error”. He says in practice you can often reduce data to 1/5 to 1/10 the number of dimensions and stay in this threshold.

Homework

Our actual homework this week was really simple, basically writing one-two lines of vector math code at a time to implement the pieces of k-means and PCA algorithms. Not much learning. There was a bunch of optional extra homework assignments applying to real world data. Using k-means clustering to reduce an image palette for instance (find the 16 most important colors). Or use PCA to reduce pixel data from pictures to the important components for facial recognition. That was neat stuff, I wish we’d done that for homework.

Screen Shot 2015-09-04 at 3.36.44 PM

Once again I find myself wanting to do this stuff in Python. PCA would be nice to apply to that Battlefield 4 dataset I collected; it’s ~20 dimensional data, boil it down to the 4 or 5 eigenvectors that really define people’s performance. Then maybe cluster that to segment the population.

How many addresses are there in the world?

A question inspired by my work on OpenAddresses.. How many addresses are there in the world? By “address” I mean something that should be geocodable to a specific lat/lon, like 1600 Pennsylvania Ave NW, Washington, DC 20500. Normal people might define an address as something you can get mail delivered to, or tell a taxicab.

One address per two people. That’s the estimate Tom Lee came up with by comparing sizes of OpenAddress data we have to population. It’s not a bad estimate!

The confounding factor is that “address” is a somewhat first world concept, I imagine there’s fewer unambiguous addresses in rural / third world places. There’s a lot of the world where naming locations is much more loosely defined, “go to Tegaljaya village, go towards the mountain from the crossroads, turn left at the big banyan tree, and then five houses down”. OTOH I think every country in the world has mail delivery, which means there is some sort of system for finding people. Should do more research.

Rant: Apple Store Stonestown shoddy repairs

My second time trying to repair my iMac, my second failure.

I took my 2011 iMac in for extended warranty repair after a hardware crash related to the video card. I got the machine back a week later with a new video card. And a new logic board, which I didn’t ask for, but their testing indicated a problem and they replaced it for free. OK, thanks!

But they’d screwed up the repair. Specifically the WiFi didn’t work at all, which is unacceptable. Also a new problem, a weird chirping noise coming from the right side of the machine when high-contrast areas on screen were scrolled, like in Sublime Text black text on white background. I could live with that but it suggested maybe something wasn’t grounded or shielded right.

So I took it back for the WiFi problem. And got it back a week later, along with a sheepish admission that they plugged the antenna in to the logic board this time. OK, mistakes happen. Then I get the machine home and plug it in and surprise! There’s a big wodge of dust under the screen, about 7 x 4 pixels big. Nice job, Geniuses! The screen chirping noise is still there too.

dirt

Now I don’t know what to do. And Apple makes it difficult enough to get through to a human I’m not confident my problem will get fixed. Any reasonable fix will at the least involve me not having the machine for a few days and probably having to lug the machine in again to the Apple store, which takes about an hour each way.

The whole premise of Apple’s high prices is they get stuff right. Their repair folks in Stonestown sure didn’t succeed.

Update: took 20 minutes but talked to a repair manager at Stonestown. No explanation for how they’d screw up a repair twice, but at least polite acknowledgement that it isn’t right. Best they can offer me is I make an appointment to bring it in again and they’ll make it a priority repair, hopefully same day.

Machine Learning: Support Vector Machines

After weeks of complaining my machine learning course had too much detail on the math and guts of ML algorithms and not enough on applying ML to real data, I got my wish. This week’s course on Support Vector Machines (SVMs) was pretty high level and breezy, and the homework even more so. And now I’m dissatisfied, feel like I didn’t get my week’s learning’s worth! Not that I’m complaining to have an easy week, but I wish there were a bit more brain-bending around application to replace all brain bending I was doing before figuring out the vector math and programming.

PS: I’ve created a Machine Learning category on the blog. And mucked with the theme. Boy, wordpress.com is super buggy and badly product managed.

Lectures

The main topic this week was Support Vector Machines, a supervised learning technique that was framed as being more powerful and practical in application than the previous techniques we used like linear regression, logistic regression, and neural networks.

Conceptually it works a lot like these other supervised learning systems. You define a cost function, but unlike the logistic cost function this one biases the system to prefer “large margins”. Ie basically it’s not enough to say “49% chance it’s category A”, the training is encouraged to say “10% chance it’s category A” instead. You control this bias/overfit tradeoff with the parameters C and sigma. C is much like our lambda from before, a damping factor to encourage small constants. (Confusingly, C = 1/lambda). sigma shapes the cost function curve itself, at least in the usual Gaussian kernel.

Oh yes, kernels. This is a neat trick where you can modify your input features with various functions. A linear kernel gives you linear regression (exactly? or more or less?). The Gaussian kernal is a good general purpose kernel. There’s a bunch of other kernals people use. And some magic allows this pluggable kernel function to be applied efficiently, so the training system runs quickly.

That’s where the lectures got a bit hazy. There was one whole 20 minute video dedicated to the math which was prefaced with “this is optional, and you should never try to implement this; use libsvm instead”. The main thing I learned from this is you can still understand speech when watching a video played back at 2.2x speed, even though the individual phonemes are no longer distinguishable. He skimmed over the math quite a bit, nothing was lost by ignoring it.

I never did quite understand why SVMs are better. We were advised they are best in applications with lots of training examples relative to the size of the feature set. Logistic regression is better if you have lots of features and few training examples. And neural networks may be better than SVMs too, but take longer to train. ¯\_(ツ)_/¯

Homework

The homework this week was super-easy, all about applying SVM to problems. Each of the 4 exercises was like 3 lines of code. The only hard part was learning Octave syntax for doing things like “find the element in the list”, which once again made me wish we were using Python.

Anyway we implemented two learning exercises. An artificial problem of “find the boundary between Xs and Os for 2d input points”. And a real problem of “build a spam classifier trained on this data set”. We were supplied with the SVM ML system itself, so all we had to do was write simple functions to compute the Gaussian kernel and boil a list of stemmed words down into a vector coding. It was kind of dumb.

The most useful assignment was writing a loop to try out a training system with various values of C and sigma, the tuning parameters for the SVM. And experimentally determine what values gave the most accurate trained model. I imagine this is the kind of thing you do in the real world frequently, and doing it well is an art.

The spam filter problem was also fun because it felt real. Took inputs from the SpamAssassin spam corpus. Used their code to crunch that text down to stemmed words, which we then coded into feature vectors. Push it through SVM and you end up with a system that classifies 98.6% of spam correctly! Which is not so great, I think 99.99% accuracy is minimal for a useful spam system. And even then you really want to measure that false positive rate carefully. But I had a whisper of an idea of how to apply this stuff to a real problem that is really solved with ML systems like what we are studying, and that was fun.

Application

Once again I find myself wanting to do this in Python. I really want a class which is “applied Machine Learning in Python”. I guess focussing on how to use Pandas and scikit-learn. Maybe someone has written that up already?

autossh for a persistent ssh tunnel

My Internet in Grass Valley is newly fast, but my ISP’s NAT setup  means I have no way of initiating connections from outside into my home network. Nice for security, awkward for hackiness. (They do offer a DMZ configuration but when I had them enable it on the previous link it never worked and broke traceroute, so I’m not asking this time.)

Instead I’ve set up a persistent ssh tunnel so that a port on my Internet server is always forwarded through to the ssh port on my Linux server in the house. That way I can ssh in remotely through the tunnel.

The only novel part of this is autossh, which is a wrapper for ssh that takes care of restarting the ssh tunnel if something goes wrong. autossh logs to syslog and has some configuration environment variables, none of which I needed to alter. It monitors for the tunnel dying and also periodically sends traffic through to make sure the tunnel is still working. ssh also has a keepalive mechanism it’s probably wise to use.

I mostly followed this guide for setting it up. Except for the Upstart config; after spending 30 minutes tearing my hair out I remembered I hate upstart and a good ol’ BSD 4.2 rc.local script would do just fine. Also I set stuff up to run as a separate user, and made an ssh config, so really it ended up being quite different. Steps:

  1. create a new “autossh” user on both machines with a shell of /bin/false
  2. set up ssh keys without passwords for this user, so that my house computer can log into my Internet server without any passwords
  3. Set up an ssh config for the tunnel for the autossh user at home.
    Host tunnel
      ServerAliveInterval 60
      HostName example.com
  4. Test that a basic manual ssh tunnel works as user autossh, without a password. This is important; first time you have to accept the ssh key manually!
    home$ autossh -N -R 2200:localhost:22 server
  5. Put the command to launch the tunnel in /etc/rc.local on the home computer
    su autossh -s /bin/bash -c 'autossh -fN -R 2200:localhost:22 tunnel'

Note the “-s” flag to su in the init script. Without that it runs as the /bin/false shell the user has which not only doesn’t work, but doesn’t give any useful error output.

Ubiquiti: less LoL lag

One nice change from with the new network, less lag playing League of Legends.

With my old hacky setup with triple nat and routers acting as a bridge, I had a lag pattern like thishacky lag

Now with the Ubiquiti gear I have a lag pattern like this:

Lag after

Note the lack of spikes! I have no idea what those were, something was getting buffered or something weird before.

I don’t think median latency or packet loss really changed, but I’m glad not to see those ping spikes. Although TBH they didn’t affect my gameplay much.

Ubiquiti success, sort of

Running a wire at my house isn’t working out, so I’m stuck needing a wireless link to get the 200′ outdoors to the base of a tree. Fortunately there’s power there! Today I replaced the hacky leftover router wireless link with a more permanent setup involving Ubiquiti hardware. So far so good, some things to improve.

The Ubiquiti equipment is interesting. In a lot of ways it’s just like a WiFi router with flexible firmware like DD-WRT on it. It has a wifi network interface and a wired network interface and various routing and bridging capabilities. But it’s more prosumer. Ubiqiuti has pretty solid firmware (airOS) and I’m impressed with details like the web-based discovery tool and the way it reconfigures itself quickly without rebooting. Also the wireless implementation seems much more solid than consumer gear. And the hardware is designed for outdoor use with directional antennas, and supports distances of 5 miles out of the box. Pretty impressive.

One massive caveat: the wireless link startup time is slow. Like 30+ seconds, maybe 5 minutes the first time. It appears to be scanning the spectrum for the right channel to use. Not sure why that takes so long, or why you can’t just rely on normal 802.11 frequency hopping for the 5GHz links.

I set up a Nano M5 and a Nano Loco M5 paired together as a transparent ethernet bridge. That configuration means those devices are invisible to the rest of my network. My router sits at the other end and gets DHCP from my ISP’s equipment. The wireless network SSID for the nanos isn’t even visible (and anyway it’s not standard 802.11). I think this is the right configuration for my purposes.

The configuration is like this:

  • A WISP POP a mile away with IP 173.195.173.1
  •    ... via a wireless link to ...
  • ISP hardware in my tree, acts as a DHCP server and NAT router.
    The WAN side is at 173.195.173.xxx
    The LAN side is at 10.33.1.1 and provides DHCP and NAT to my house
  •   ... via an ethernet cable to ...
  • Nano M5 in Access Point mode. WDS is enabled for bridging. This device has an IP address of 192.168.0.111 but that’s mostly invisible.
  •   ... via a 5GHz airMax link to ...
  • Nano Local M5 in Station mode. WDS is enabled for bridging. This device has an IP address if 192.168.0.110 but that’s mostly invisible
  •    ... via an ethernet cable to ...
  • My home router, an ASUS RT-N16 running as full AP + Router.
    The WAN side gets its IP address via DHCP from the ISP (via the Nanos). It happens to be 10.33.1.23 at the moment.
    The LAN side is 192.168.0.1 with subnet 255.255.255.0. Also provides DHCP and all the other home network services you’d expect
  •    ... via an ethernet cable or 2.4GHz 802.11 link to ...
  • Desktop computers, mobile devices, etc in 192.168.0.*

The good news is I’m not doing triple-NAT anymore. My router is doing all the real NAT work for my house. The ISP’s hardware is also NAT but I’ve taken pains to only have the one device connecting to it.

The main problem with this configuration is from my house network I can’t access the Nano status pages at 192.168.0.110/111. My router and the rest of my house’s devices think all of 192.168.0.* is on the LAN interface so won’t send packets out the WAN interface where they are. I could hack around this with static routes but that’s dumb. I should reconfigure the Nanos to a different subnet like 192.168.25.*. Then I add a single static route for that subnet in my router and I think I’m done. (I could set them to 10.33.1.* but that’s a bit funky, I definitely don’t want to risk those devices being visible to the wider Internet.)

The other small problem I have is the secondary PoE port on the Nano M5 isn’t working. In theory this should provide power to the ISP equipment in the tree. Power passthrough isn’t enabled by default but I fixed that, still not working. More tinkering required, for now I just use a second PoE injector.

This Ubiquiti firmware is pretty powerful and I feel like there’s some simpler configuration where I get rid of my house router entirely, use one of the two Nanos to be the router too. I’m not sure that really simplifies anything though, I’d probably still want the third box acting as an access point inside the house.

Update

I renumbered the Ubiquiti bridge devices to 192.168.1.110 / 192.168.1.111 and added a static route for them in my router. Works great. Next project; some sort of monitoring for them. They have SNMP and I find references to Munin plugins.

I also figured out the secondary PoE problem. I thought maybe it was total power; the Ubiquiti device wants 8W, the Cambium radio in the tree wants as much as 7W. So 15W total and the PoE injector only puts out 12W. But then I read more closely and discovered that the Cambium PoE implementation is reversed from the usual passive setup. Cambium puts positive voltage on pins 7 & 8, not 4 & 5 like everyone else. How stupid! Really dangerous, I’m lucky the magic smoke stayed inside the Cambium gear when I plugged it in. Maybe they engineered in some safety to overcome the perversity of using reverse polarity from what is common. (I hesitate to say standard, because there is no standard for passive PoE, although the 802.3af standard has a mode B that looks an awful lot like the passive PoE everyone but Cambium does.)

I’ve also discovered the radio in my house works in a closet, behind a relatively thick wall. Signal strength is degraded; airMAX quality is 78% compared to 95% with a clear view through the window, and max speed is about 200Mbps instead of 300Mbps. Still well above what I need for the 12Mbps Internet link though. Going to test it out, would be nice to not have to mount that thing outdoors or in the window.

Outdoor wiring

(Some very boring notes so someone else can wire this up)

Conceptually, we’re connecting a wire from the antenna in the tree to the Ubiquiti NSM5, one long straight wire. But it’s complicated because we need separate PoE injectors to provide power to both devices.

The black wire from the tree goes to the Phihong PoE module. It goes to the port on the left, labelled “Data + Power”. Very important to use the right module; the Cambium tree antenna uses non-standard PoE and this Phihong PoE module is special. The word “PHIHONG” is in the upper left of the label, beneath a spiral P logo. It’s the longer module, that does not say “Ubiquiti” in the upper right. The top one in this photo.

An ordinary short ethernet patch cable goes from the “Data” port on the right side of the Phihong PoE module to the “LAN” port on the right side of the Ubiquiti PoE module. This cable is currently a 3′ coil of white wire (would be nice to replace with a 1′ cable). This cable is not powered, not PoE, it just carries data between the devices.

Another ordinary ethernet cable goes from the “PoE” port on the left side of the Ubiquiti module to the Ubiquiti NSM5 antenna. It goes to the port on the right labelled “Main”. The port labelled “Secondary” is not used.

Finally, plug both PoE modules into AC power. There’s an LED on the back of the Ubiquiti radio to confirm it’s powered, but it’s pretty hard to see in bright sunlight. Once the devices have power they both take about ~60 seconds to establish wireless links.

WiFi protocol notes

I’ve been doing Wikipedia reading associated with my wireless experiments on how 802.11n works. Here’s some brutal summaries, note I’m totally ignorant of signals processing and believe taming the electromagnetic field is basically witchcraft. I’m sure I made a mistake somewhere.

802.11n notes

  • 802.11b and 802.11g are basically a single wireless signal on a single 20MHz wide channel. 802.11g uses orthogonal frequency division multiplexing to split that 20MHz up into 52 separate subcarriers. There’s 8 different modulation and coding rates possible in 802.11g, resulting in data rates of 6, 9, 12, 18, 24, 36, 48, or 54 Mbps.
  • 802.11n is based on 802.11g.
  • 802.11n’s main innovation is multiple antennas and MIMO.
  • 802.11n can optionally use a 40MHz channel. That’s a bit naughty at 2.4GHz; it means you overlap with pretty much every other 2.4GHz user around you. My iMac doesn’t appear to support 40MHz at 2.4GHz.
  • 802.11n can also run at 5GHz. (My router doesn’t.) I don’t think it runs any faster at that frequency, although the channel separation is nicer.
  • Max 802.11n datarate at 20Mhz channels is 288.8Mbps. At 40MHz it’s 600Mbps.
  • Multiple antennas also allow for MIMO, multiple-input and multiple-output. I don’t understand this at all but the Wikipedia page says this is about exploiting multipath effects to effectively get more useful signals out of the same bandwidth. This seems like complete magic to me.
  • A specific thing MIMO does is spatial division multiplexing. I think this is effectively a directional thing, ie: “I can talk to radios north of me and radios south of me independently”. Only I’m guessing this has more to do with orientation of the antenna, and may explain part of why simply rotating my antennas so they were not all parallel resulted in a better connection. (If the access point’s antennae are parallel then they are not spatially disjoint.) My iMac is currently enjoying two spatial channels to the router, which makes more sense if you think of rotational spatial division.
  • You get 1 spatial stream per antenna+radio (sort of), and 802.11n supports up to 4 antennas. My Asus RT-N16 is a 2x2 configuration so that’s effectively 2 transmit and 2 receive antennae. (There’s only 3 physical antennae, no idea how that works). That’s why it maxes at 300Mbps; only 2 spatial streams. With 20MHz bandwidth it maxes out at 144.4Mbps. My iMac gets 1 spatial stream sometimes and 2 most of the time.
  • 802.11n optionally supports a 400ns guard interval, half the space between separate data frames as the old 800ns. That seems to boost throughput about 10%. The Wi-Fi signal app on my iMac reports speeds that suggest I am using this, sometimes. (Ie right now: MCS index 7, but 73 Mbps).
  • 802.11n supports a bunch of different coding rates. The coding rate describes how much of the signal is reserved for redundant error correcting bits. My iMac is typically seeing a coding rate of 3/4 or 5/6.
  • 802.11n supports several different modulation schemes. That’s the digital to analog part of the radio, the way bits are turned into waves. My iMac is mostly using 16-QAM or 64-QAM, which corresponds to 4 or 6 bits per symbol. Neat visualization here
  • The coding rate, modulation, number of spatial streams, and maybe even the guard interval are varying frequently, at least once a second. Presumably the access point is picking which variant to use depending on the current error rate.
  • 802.11ac is the new hotness. It’s 5GHz, supports 80Mhz and 160MHz channels, 8 spatial streams, 256-QAM (with non-standard 1024), etc. If my arithmetic is right the spec could in theory go up to 8Gbps (compare 600Mbps for 802.11n). I think in reality you can actually get gigabit wireless speeds. But only if the spectrum is uncongested and the signal path is clear. My fancy ASUS RT-AC68U claims up to 1300Mbps at 5GHz. That seems to correspond to 2 streams at MCS index 7, which is 64-QAM 5/6 rate.

MCS Index

Most of the 802.11n options are summarized in a single number called the MCS Index. See also this table. MCS Index specifies the number of spatial streams, the modulation type, and the coding rate. Those together define how much data can be stuffed in a single subchannel. Combine that with your bandwidth (20Mhz or 40MHz) and your guard interval and you get a max data rate.

In practice my iMac mostly hangs out at MCS 7 or MCS 12. MCS 7 is a very dense modulation and coding, but only one spatial stream, and it’s reporting 73Mbps. MCS 12 is a less dense modulation but 2 spatial streams, and reports 78Mbps.

Misc other observations

The upstream bandwidth from my link is 12Mbps, so I don’t really care about any of these higher speeds. I’m much more interested in reliability.

I had my RT-N16 configured to use 40MHz but my Mac wasn’t using that. (From a quick search, Apple doesn’t support 40MHz at 2.4GHz.) So I knocked it down to 20MHz in the router and now I think I’m getting a stronger signal. -60dBm instead of -65dBm. I suppose that’s possible? I didn’t measure carefully.

I’ve got two wireless devices connected to the router; my iMac and an old WRT54GL running 802.11g. I tried making both of those wireless links busy, about 5Mbps each, and didn’t see any obvious contention. My iMac didn’t even drop down to 1 spatial stream which I was sort of naively expecting. That’s all as it should be: 802.11g promises 54Mbps bandwidth and I wasn’t getting near that. Nice that it really works.

Google’s new OnHub router does 802.11ac and 802.11n in a 3x3 configuration.

My 2013 iMac’s wifi antenna is behind the Apple logo in the case. Why? Because it’s the only part of the back that’s not made of aluminum.

Machine learning: picking the right system

Week 6 of my machine learning course.

Lectures: applying machine learning, system design

This week’s lecture was about using machine learning algorithms well. Great series of notes, the kind of thing I’m really in this course for. Focus in particular was on figuring out how to improve the results of your learning system and then evaluate the result. You have a lot of options to tweak the model and learning: more properties, more data, different learning rates. Which should you use? He gave a few heuristics better than guessing.

The first thing is splitting data into training and test sets. Keep the evaluation test data separate so you have something to test with that the learning algorithm never saw. Good advice. He also points out that you often use tests on trained systems to pick your trained system; you can’t use that test data (“cross-validation data”) for final evaluation either, since your metalearning system was picked to do well on exactly that data.

The other thing was defining “high bias” models (underfit models, too few parameters) and “high variance” models (overfit models, too many parameters). These are important concepts! Then he gives a test to figure out if your learning system is one or the other, which is basically looking at error rates. Systems that train to low error but then test badly are high variance, overfit. Systems that train to high error and test badly are high bias, underfit. I get the intuition for this and look forward to apply it in the homework.

Finally we moved on to ways to build systems and evaluate them for success. Really nice exhortation to build a quick and dirty system first with the simplest features and data you can get your hands on. Start working with the problem and you’ll understand it better, then you can make an informed decision about what extra data you need. Also an interesting observation about the usefulness of very large datasets. Having an enormous amount of test data means you can use more complex models with less bias, and be confident that you won’t overfit your training data just for the sheer size of that training data set.

Ng defined precision and recall for measuring an algorithm’s correctness, also boiling those two numbers down into a single F-score for ease of comparison. Useful in particular for skewed datasets where you may be classifying something that’s only True 1 iin 1000 times.

Homework

This week’s homework has us loop back and implement the very first model we learned, linear regression, then test and evaluate it according to some of what we learned. I didn’t care much for the linear regression part, but the the hands-on application of learning systems and error measurements was great.

The first half of the homework was “implement linear regression learning with all the bells and whistles”. We’d not done that before, only logistic regression, so it was similar and yet different. Not too challenging really, a bit repetitive from previous work, but reinforcement is good.

The second half of the homework was “train a bunch of learning models and measure their error”. Specifically comparing the error on the training set vs. the training on our reserved cross-validation set, and graphing learning curves, etc. This is a sort of meta-machine learning, choosing the parameters for our machine learning system so that we get a well trained model.

We looked first a a truly linear model, trying to fit a straight line to data that’s roughly quadratic. Lots of errors. The learning curve shows us that adding more data points isn’t really going to help make this model more accurate, it is over-biased. So then we switched to an eighth order polynomial model but trained it without regularization. That fits the training data great but fails cross-validation, because it is high variance.

So finally we applied regularization in the learning model, the mechanism that encourages the learning to low-magnitude constants for the polynomials. The encouragement strength is governed by the value lambda. So train lots of models with low lambda and high lambda and see which lambda is best. Lambda = 3, that’s best! At least for this problem.

Conclusion

I’m really itching to apply this stuff to my own problems now, to make it real. But I’ve got to solve two problems at once to do that. I need confidence in my own code without the safety net of homework problems with calculated correct answers. And I really want to redo this work in Python, to get out of the weird Octave world. Taking both leaps at once is foolish. I should either bring a problem of my own into Octave once to apply my proven code to new data. Or else port the homework to Python first and verify I still get the right answers to prove my new code. I tried the latter already and got frustrated, should try the former.

Project idea: open stuff with VLC

VLC doesn’t install itself as the default handler for media files like .m3u or .mkv or whatever. Not sure why, but the documented process is tedious.

I should write a simple script / program to set VLC to be the default app for a bunch of types that VLC supports. Maybe absolutely everything that would otherwise open in iTunes is a good start :-P The program duti is a good start on how to set associations in MacOS. It seems to work by using the Launch Services API.

Wireless ethernet bridge success

Frankenstein network success! I managed to turn an old Linksys WRT54GL into a wireless ethernet bridge. It was remarkably difficult. Despite a long history the WRT54GL seems end of life to me, a lot of the hacker firmwares don’t really support it well anymore.

The goal here is to bridge my new fast Internet access from the tree 200 feet away to my house. The router up there works great but right now I don’t have a wire into my house, so only wireless devices with good antennae can use it. A wireless ethernet bridge is perfect for that; it turns that old WRT54GL into what looks like an ethernet switch connected to the router via a magic wireless wire. In theory. Note the WRT54GL is doing very little else in this configuration: no routing, no DHCP, no DNS, etc. It’s acting more like a layer 2 ethernet/wifi device than a layer 3+ Internet device.

The big problem I had was trying to make this work with Tomato/Shibby firmware. It supports ethernet bridging but has some weird and spooky restrictions around WPA2 and bridging mode. I never could get it to connect on the wireless link, probably because of that authentication mismatch.

So back to good ol’ DD-WRT, a 2009 build named dd-wrt.v24_mini_wrt54g.bin. Downloaded that, followed some instructions, and bridging was working in just a few minutes.

I’m grateful I understand arp; there’s no way to debug or reason about what a bridge is doing without it. The Tomato firmware doesn’t even really present the arp data to you very clearly, you have to ssh in and run the arp binary to see it.

So now I have 4 ethernet ports with fast internet inside my house. Albeit as a temporary setup. How do I get the rest of the network using it? I can just plug the switch for the wired devices into the bridge and it should all work, now DHCPed and routed by the temporary router up by the tree. The problem is I have a couple of wifi-only devices in the house with antennae too weak to reach the tree. So I could repurpose a third router and turn it into an access point for the tree network, that’d be the “right” way to do it permanently. But I want to be able to undo this all and so not screw up that third router, the one that’s my current normal (slow Internet) router.

So instead I’m considering plugging that house router’s WAN cable into the bridge. That should work with much less disruption to the rest of the house network and easy to undo. But it implies we’re doing double NAT for everything which is pretty gross.

Update: I went with the double NAT setup; basically changed my primary home router’s WAN connection from the old Internet link to get Internet via the bridge, which goes to another NAT router, and then the antenna. It may actually be triple NAT; I think the antenna hardware does NAT too. It’s gross but none of my client computers seem to care much. UPnP/NAT-PMP doesn’t seem to be working so no inbound connections, but I can live with that for now. I realized later the “right” setup is for the wireless ethernet bridge to be outside near the tree / antenna, then have my internal router get its WAN connection via that WiFi link. I think DD-WRT or Tomato can be bent to do that but the firmware all assumes your WAN link is coming in that ethernet port on the back. Too much hacking for a temporary thing.

One other thing to mention / option for making this work is WDS, a sort of bridge-like system for wifi networks. The key thing is it allows a device like my WRT54GL to both use the wifi interface as a client and also serve as a repeater / second access point serving that exact same wifi interface. Both Tomato and DD-WRT claim to support it, but it seems pretty spooky to me. Also lots of warnings online it’s not a well defined standard and compatibility is a problem.

I’ve spent a lot of time on a hack that’s only going to be used for a few days. The outside router is sitting in open air on top of a post! Good thing it doesn’t rain in California anymore.

Video bitrates

Interesting post from Riot explaining why they don’t broadcast 1080@60fps. Long story short, they say it’s too much bandwidth. I was curious how much bandwidth it really is so I used youtube-dl to look at the streams for the DotA 2 final this year.

For MP4 streams the bitrates for video only are:

Resolution   FPS     KBPS
       144    15      120
       240    30      255
       360    30      610
       480    30     1148

       720    30     2243
       720    60     3362

      1080    30     4191
      1080    60     5592

Bottom line: 1080@60 is 2.5x the size of 720@30. And 720@60 is less bandwidth than 1080@30. IMHO the faster framerate offers more of an upgrade than the extra scanlines.

Edit: the LCS live broadcast on Aug 22 is 720@60. 3800kbps total at the router. Format 298, which is h264.

For completeness: YouTube also offers VP9 streams. They’re mostly smaller except 1080@60, but the scaling is about the same. Here’s all the streams on offer.

160          mp4        256x144    DASH video  120k , avc1.4d400c, 15fps, video only, 34.59MiB
278          webm       256x144    DASH video  131k , webm container, VP9, 15fps, video only, 35.95MiB
133          mp4        426x240    DASH video  255k , avc1.4d4015, 30fps, video only, 77.52MiB
242          webm       426x240    DASH video  281k , vp9, 30fps, video only, 75.53MiB
243          webm       640x360    DASH video  525k , vp9, 30fps, video only, 141.57MiB
134          mp4        640x360    DASH video  610k , avc1.4d401e, 30fps, video only, 147.37MiB
244          webm       854x480    DASH video  957k , vp9, 30fps, video only, 254.94MiB
135          mp4        854x480    DASH video 1148k , avc1.4d401f, 30fps, video only, 293.53MiB
247          webm       1280x720   DASH video 1945k , vp9, 30fps, video only, 510.17MiB
136          mp4        1280x720   DASH video 2243k , avc1.4d401f, 30fps, video only, 561.60MiB
298          mp4        1280x720   DASH video 3362k , h264, 60fps, video only, 917.39MiB
302          webm       1280x720   DASH video 3372k , VP9, 60fps, video only, 815.76MiB
248          webm       1920x1080  DASH video 3580k , vp9, 30fps, video only, 896.15MiB
137          mp4        1920x1080  DASH video 4191k , avc1.640028, 30fps, video only, 1018.78MiB
299          mp4        1920x1080  DASH video 5592k , h264, 60fps, video only, 1.55GiB
303          webm       1920x1080  DASH video 5833k , VP9, 60fps, video only, 1.38GiB

CSV query tools

I do a lot of work with CSV files, and up to now I’ve been mostly doing clumsy stuff with standard text tools like “awk -F,” and the like. Here’s a roundup of some Unix command line tools for working with CSV files, lifted from One Thing Well

  • xsv: slice, split, summary stats, etc. also supports creating a quick index to accelerate things. Seems pretty solid. Rust program, which is awfully weird, but he provides a Linux binary.
  • csvkit: suite of programs for manipulating CSV. Includes import/export to JSON, Postgres, Excel, etc. Also has a SQL query via in-memory sqlite3. Python program.
  • Miller: “like sed, awk, cut, join, and sort for name-indexed data such as CSV”. More limited queries than xsv or csvkit. But it embraces more input file types, including CSV files that change schema and arbitrary keyword/value data. Seems perfect for the “long list of JSON object” files I often work with. (Although no JSON support?!)
  • csvfix: thin docs, another xsv-style tool. Has more operations than other tools.
  • q: SQL queries on CSV files via sqlite. Python program.
  • TextQL: SQL queries via sqlite. Go program.
  • fsql: SQL queries via some Perl SQL implementation. Supports JSON and YAML.

I just tried xsv and it’s quite nice, may be the closest to what I need day to day. I’ve used q before and remember it working nicely, albeit a bit slowly. Arbitrary SQL is appealing.

WiFi transmit power readings

I’ve got a router outside about 200 feet from my iMac with a clear line of sight through a window. I’m running 802.11 at 2.4GHz over the distance. It works surprisingly well. I’m in a quiet rural area. The signal strength isn’t great and the speed isn’t what I’d like. The Tomato firmware I use lets me override the transmit power in the router, numbers from 0-250. Default is 17 or 42, folk wisdom is that up to 70 is “safe” although other folks say any setting is safe. Those settings may be throttled too, depending on what country you’ve configured the router to be in. Also apparently too high and you start getting distortion. Or not. Wireless is spooky.

Here’s some readings on signal courtesy of the WiFi Signal Mac program. Routers are running Tomato and/or Shibby and are using stock antennae. Readings taken under light to no load. All readings are approximate / variable and sloppy enough to not be very good. It’s not clear what these settings really mean; people call them “milliwatts” but it’s not clear that’s true.

All this stuff is using channel 11. 20MHz wide, AFAICT, even though I configured for 40. Measured noise is -79 to -82 dBM. I wish I understood how noise worked better. I’ve been able to use this link even when reported noise was higher than signal. Is that a thing WiFi can do?!

iMac 2011 tests:

Linksys WRT54GL 802.11g, 200 feet away

  • 12: -72 dBm
  • 42 (default): -75 dBm
  • 70: -72 dBm
  • 200: -67 dBm

ASUS RT-N16 802.11n, 200 feet away

  • 80: -68dBm
  • 200?: -68dBm. (May be limited by US country setting.)

a different ASUS RT-N16 802.11n, 10 feet away

  • 17 (default): -50 dBm

Macbook Air 2011 tests

ASUS RT-N16 802.11n, 2 feet away

  • 80: -32 dBm

ASUS RT-N16 802.11n, 200 feet away.

  • 80: -69 dBm

No real conclusions from all this. Boosting power might or might not make a significant difference; measurably it does with the WRT54GL, not so much with the RT-N16. The RT-N16’s signal strength also seems a little better, which is sort of expected since it’s 5+ years newer hardware with fancier antennas, etc.

One thing I didn’t record systematically is the improvement 802.11n brings. With the 802.11g links my actual link speed seemed to be 2Mbit/s as measured by Ookla Speed Test. I can get the full 12Mbit/s with the 802.11n. The reported theoretical Mbps of the wireless link is also significantly faster, as expected. The way I understand this is that 802.11n makes better use of available signal than 802.11g.

See also this discussion which shows improvements from -73 RSSI to -60 RSSI as power went from 1 to 55. Another graph shows improvements from -80 to -72 RSSI as power goes from 0 to 80. This article is interesting as well.

Update: antenna arrangement

Woah! I rearranged my antennas and picked up 5-6 dBm, which when I only had 6 dBm over noise basically doubles the SNR.

All the tests above are with the 2 or 3 antennas on the router all pointing straight up. Turns out that’s dumb, you want them perpendicular. I arranged the 3 antennas on the RT-N16 into a W shape (45 degree angles) instead of all 3 straight up. Went approximately form -68dBm to -63dBm. Who knew?

Update 2: hot rod antennas

I tried some third party antennas, advertised as 9dBm gain (compared to 3dBm stock). Not impressed. Measured signal strength at my iMac was the same, about -63dBM with both sets of antennae. The new antennae are over 2x as long, which I guess is probably good? But the connector isn’t stiff enough and it doesn’t hold its own weight at the 45° angle I figured out was better. I think I won’t be using these.

Update 3: symmetric readings

I forgot that my RT-N16 wifi router 200 feet away has a report of RSSI too, so I can see the signal from the other side. These readings are all +/- 3dBm fluctuations.

  • iMac hears -65. N16 hears -58
  • WRT54GL hears -61. N16 hears -52
  • MacBook Air hears -73. N16 hears -71

These devices all report noise measurements too but its’ radically different, like -75 dBm on the iMac and -92dbM on the WRT54GL. No idea what that means.

Update 4: San Francisco tinkering

I tried to apply what I learned about improving wifi strength in San Francisco. Different environment: I’ve got 10+ networks in view of me (mostly 2.4GHz?) and the walls of the house generate a lot more interference, I think because of metal lath in the plaster. Anyway, what I learned:

  • Changing xmit power from 42mW to 100mW didn’t help at all
  • Repositioning the antennas to a spread out W made things a little worse, if it had any change at all.
  • 2.4GHz and 5GHz work equally well downstairs, about 32dB SNR. Upstairs (away from router), 2.4GHz has a significantly stronger signal. like 10-20dB SNR vs 5-10dB.
  • Fancy ASUS routers have an “interference mitigation” setting that seems designed for dense urban areas. Turning it on didn’t help signal strength at all, may even have harmed SNR by 2dB or so. Nevertheless I’ve left it on with some theory it will help.

I wish there were some easy way to measure reliability. I don’t care about max throughtput nearly as much as I do reliable packet delivery at whatever speed.

LoL dotmap

Fresh off my heatmap attempt I made a second map of a single LoL game using a dot map. One dot per player recorded position (28,000 in all), colored by team.

Screen Shot 2015-08-17 at 6.04.56 PM

I think this treatment works better; the team color is really important information. But I miss the emphasis of dwell times that the heatmap accumulation algorithm gives. I’ve tried to fake it by using dots with 20% opacity but that’s pretty bogus. (Also easy to fudge, depending on dot size, opacity, and stroke weight you use.)

Still, an improvement, and I’ve also got a data extractor that’s creating more structured data so I can track individual players.

I did this in D3js because it was easy to. But I want to produce a static final output so there’s really no need for Javascript. I should look into data plotting tools in other languages. Maybe this is a time to try out some more of the big data Python tools, or see what Octave has up its sleeve. I think something like the heatmap algorithm is really what I want.

First light: League of Legends heatmaps

I took a crack at rendering the position data I found in the League of Legends live matc stream. Here’s a first take on TSM v TL game 1

Screen Shot 2015-08-17 at 3.59.13 PM

Interpretation

Not bad, it at least looks recognizable. The main trend is that there’s more activity on blue side (lower left) than red size (upper right). That matches what happened in game; TSM was red and they won, and dominated. The other basic pattern is you see the basic shape of the map and the paths through the jungle. This is expected.

But then it gets more subtle. I love the two blobs at upper left. I think these are times when TSM’s jungler was hiding in those bushes ready to gank for TSM’s top laner, will have to watch the game again to verify he really did spend a lot of time there. Als interesting to see the relative bias of activity over towards Baron instead of Dragon, I suspect that’s not a universal for all games.

Improvement

Lots to do to make this better. Some inspiration: this NYT treatment of similar data, which takes data from many games and uses dots instead of a heatmap. However my goal is more to highlight what’s interesting about a particular game, so have to apply their many-games approach carefully. And also these DotA maps which are basic but complete works.

#1 problem with my treatment is the single color scale: I really want red vs blue ramps for the two teams. But then I don’t want to mix them to purple! I suspect the heatmap treatment is really not the right tool here, I should consider dots like the NYT map. It’s about 26,000 dots in total per game. (600 per minute, games seldom go 60 minutes.) Also should look at hexbinning or whatever the cartohipsters are doing these days.

I’d also like to examine the time axis, see how the movement spreads over time. I don’t really want to make some interactive visualization though, a static image is better. I like what the NYT did breaking the game up into three phases.

Finally it’d be nice to be able to pick out individual players. Particularly the support and jungle since they roam more, but also bot and top to see what happened with lane swaps.

Implementation

The heatmap rendering is from heatmap.js. I like it for being a straightforward canvas implementation, and it is fast as promised. But the rendering is very limited, in particular I can’t come up with any way to render two categories of data in different colors in the same heatmap. (And the canvas is opaque, so I can’t just draw two superimposed, which would be awful for other reasons too.)

The data extraction is some dumb-ass Python to pull the position fields out of the stream data. Quick and dirty, need to clean it up if I do this for real. If a character doesn’t move I don’t draw their position twice right now. Also the stream data is remarkably messy, I need to do extra work to detect game start and end and filter out data from the previous game that sometimes got mixed in. And I should preserve per-player data to allow more flexible visualizations.

Machine learning: backpropagation shitshow

Frustrating week in the machine learning course. We learned how to implement backpropagation in neural networks. Or at least we pretended to.

Lectures

Ng’s lectures skate over the math pretty fast and there’s like 3 separate snippets reassuring “if you don’t understand this don’t worry, it’s hard and I don’t always remember either lol!”. I think this course tried to walk the line between either really doing the math or not and fell in a gap in the middle. I’d prefer to have skipped the math entirely. I kind of did, honestly, and fell back on my “how do I fake this” survival skills from the few college math classes I didn’t like.

The useful part is Ng also emphasizes the intuitions and mechanical logic of what backpropagation is doing, and that I think I understand. Forward propagation is creating a mesh of hidden layers that map inputs to outputs with hidden weights. Backprop starts at the output layer and observes the error, how far the network’s output is off from expected output. It then tries to apportion that error to the previous layer’s nodes by spreading the error backwards, weighted by the activation parameters. And so error is propagated backwards through each layer and in the end you have some idea how much each activation weight contributed to the mistakes the output made.

More concretely, backpropagation gives you a cost function J and its partial derivatives where each activation weight in the neural network gets a fair share of blame for the error. With cost function in hand you can run a function optimizer to find the activation weights that minimize the cost. (One fact Ng skated over; this cost function is no longer convex, which means the optimizer might get stuck in local minima. He mentions the problem and says not to worry about it in practice. Um, ok).

One fun thing in optimizing neural networks: if you start one out with node having constant activation weights (say, all zero) then all the nodes look the same and error is apportioned equally, so nodes don’t train separately. To break this degenerate symmetry you start training the network with randomized weights. Reminds me of the Big Bang and the lumpy cosmic microwave background.

Homework

The homework programming exercises are the only way I feel like I’m really learning anything. They’re reasonably good.

However, this week’s lecture + assignment clearly specify “don’t try to vectorize over the 5000 training inputs, just use a loop”. But then the tutorial that’s my real lifeline to implementing these assignments is a vectorized implementation! Which is it, teacher? I’ve mostly preferred implementing the vectorized versions, both because it’s faster to run and because it’s a closer match to the math equations from the lectures. It’s sure nice avoiding writing lots of for loops. But the teaching materials really need to decide to either vectorize everything or not, this stuff in conflict is a mess that I imagine loses a lot of students.

While I’ve been doing vectorized implementations, really I’d prefer to not vectorize over the training inputs. Write all my code to process one training example at a time. That’s the way a lot of stuff works in the real world anyway.

Anyway I stumbled through the notes and managed to implement backpropagation. I think I understand how it works too, although I just accept the provided cost function and derivatives as gospel truth rather than having done the derivation myself. And in the end I’ve trained my own neural network to recognize handwritten digits. Yay!

One fun thing in the homework is they visualize the hidden activation layer. That layer has 25 nodes. This image shows for each of those nodes, how much it weights the value of any particular pixel. If you squint you can convince yourself this hidden layer is doing some feature detection, like the bright vertical line in row 2, column 3. Also clearly the corners of the image are not useful to anything.

Screen Shot 2015-08-16 at 5.59.57 PM

I thought the technique of gradient checking was interesting. Backpropagation (and other cost functions) require you analytically divine the partial derivatives of your cost function, or in my case copy them blindly from the lecture notes, and then implement this in code. It’s pretty easy to have a bug. And apparently subtle errors in the gradient function result in neural networks that sort of converge but just not very well, so you might not notice the bug. Ng suggests as a backup check that you also numerically approximate the derivatives, by evaluating the cost function an epsilon away from some value and thereby calculate the gradient. Then check this numeric approximation is close to your analytically derived implementation. I like the idea, it’s a sort of interactive debugging technique. Also begs the question why bother with the analytic derivative at all, why not just use a numerical approximation? Because it’s expensive to calculate the numeric approximation, that’s why. And also it’s less accurate.

I also appreciate the role regularization plays. Apparently it’s not hard to overfit a neural network to input data. Ie: it is 100% accurate on your input data but then its overfit and may not work well on real data. The lambda regularization parameter is a damping applied to the gradients to encourage all the parameters to be small numbers, which apparently is the way you keep a neural network honest.

Here’s a picture of the hidden layer’s activations for an overfit model. Notice how there’s no obvious feature detection? At least, there’s no obvious vertical stroke detector like there was in the previous model. The accuracy of this model is 100%, but it may be less useful when applied to data it wasn’t trained on.

Screen Shot 2015-08-16 at 6.01.36 PM

That’s the kind of machine learning trap I’m taking this course to learn more about. I sort of understand the math behind why lambda works, but I can see it would take a lot of experience applying this stuff to real problems to really get a feel for how to set it right.

In the end I really hope to never, ever implement a neural network again in my life. I do honestly just want to use someone else’s neural network library. I do feel some sense of accomplishment having built my own though. And my real goal here is to understand a little of what’s going on inside the black box so I can use it better. I gather neural networks have a lot of subtle traps.

I still have to go and apply this stuff to real data I really care about. I started trying to do that a couple of weeks ago, in Python, but got frustrated trying to learn Pandas and scikit-learn and iPython notebooks all at once.

LoL live match stats

New feature on Riot’s pro game broadcast site: a live stats board. It updates once a second in your browser showing you game stats. Also features for Twitter messages, game stream info, etc. It’s the stats I’m interested in.

Stats scoreboard

Here’s the data on display:

  • Match type. Game #. Games won / lost by each team. Team and player names.
  • Kills in current game. Also objectives: inhibs, barons, dragons, towers.
  • Total team gold.
  • For each player: kills/death/assists, CS, and gold.

Data contents

The game stats are implemented with a web socket. (There’s also some JSONP being polled for other features; the stats are a web socket.) I wrote a Python program to record the data. They generally send one message a second, about 500 bytes, updates to things like player gold, kills, etc. It’s a pretty efficient implementation.

The data on the web socket is mostly what you’d expect to implement that display. Messages usually contain updates on player stats: total gold, current gold, experience points, and player position. Variables are only in the JSON blob if their value has changed. A bunch of oddball updates sometimes come through for things like CS, player kills, etc. And then teamStats updates for tower kills, etc. They’re also tracking player double kills, triple kills, etc. Nothing in the stream about item purchases that I’ve seen.

There’s also some special messages. The first message on the socket is about 14k and contains all the data that ordinary isn’t changing, stuff like player name. When a new game starts the info about what champions are in the game is sent along. When a game ends there’s a gameComplete message. That kind of thing.

The most interesting thing I’ve found in the data stream is player position. It’s currently not being used by Riot’s web client. Should be possible to use that to animate a version of the game. riftwalk.gg had something like that based on replays before it got shut off, would be nice to feed this stream to that visualization code.

Technical details

My Python client is having the socket closed on it every 90 seconds. I just re-open it for now, seems to work. The web client in Chrome doesn’t seem to be doing that. Wireshark tells me that there’s a ping/pong Chrome is exchanging every 45 seconds. I’m guessing the Python client isn’t responding to pong and after two failed pings the connection closes. A bit confused why the pong doesn’t come through, the Python library looks like it just handles that for me.

Update: I looked in Wireshark and found the Python client is sending pong responses, but they’re getting TCP fragmented into two packets maybe because of the way the async writing code works. I’ve opened an issue on GitHub seeing if my analysis is correct and whether it’s something that could change. Update 2: I guessed right! The author changed the code to not fragment the packet and now I can stay connected. Yay!

The web socket hosted at ws://livestats.proxy.lolesports.com/stats. The socket requires a JSON web token to connect, which is some signed blob, although it’s not tied to any personal secret like a password login. I pulled one out of my browser and decoded it via jwt.io, it contains a bunch of IDs. Also has what looks like an expiration date, token is good for a week. I just pulled the token out of my browser and reused it in the Python code.

Mac screen capture: creating League of Legends highlights

I felt like a huge nerd today and wanted to record a video highlight from a League of Legends. Lots of steps here to capture the game itself, capture video and audio on the Mac to a file, convert it to something usable, then upload it. Here’s all the steps.

Generate content: record game replay

The service replay.gg will record all your League of Legends games for you. It’s terrific! Using it you can watch one of your games later in the observer client. I use this to get the exact game scene I want to capture.

Capture content: video and audio capture

The Mac does not make it easy to capture full screen video and audio. I used to use the commercial product Screenflick to do this but it’s pretty buggy. So this time I did the capture with Open Broadcaster Software, which is a free. The UI is a bit more hackerware but for my purposes it’s perfect.

OBS records video pretty much right out of the box. I tinkered with the Advanced Output settings to record at the bitrate of 10,000 (overkill) using the faster preset. Note that OBS is doing h.264 encoding live while you go, so it’s taking CPU power. The “slow” preset definitely interfered with my game framerate. (Screenflick records with a very fast, disk intensive codec and then re-encodes later, which is kind of nice.)

Audio is a problem. Update: see this second post about sound. OBS recommends WavTap but I couldn’t make it work. Instead I installed SoundFlower, which also works well with OBS. Basically SoundFlower installs a kernel module that’s a new loopback audio device. You use the Sound control panel to tell the Mac to make SoundFlower 2ch the default audio device. SoundFlower then passes that through to your actual headphones or whatever, while also making the sound stream available to apps. Note that starting with Yosemite it’s getting very hard to run custom kernel drivers in MacOS. Thanks a lot, Apple.

Now I have OBS recording movie files to my hard drive of whatever is on my screen. Yay!

Edit content

The next challenge is editing the capture down to what you want to share. I’m allergic to iMovie, and AFAIK there is still no good free simple “let me cut 15 seconds out of my video” GUI tool for Macs. I ended up using ffmpeg to do this with these instructions. ffmpeg lets you pick to the nearest millisecond, but irritatingly VLC won’t show you milliseconds in playback, so precise cuts suck.

Here’s the command I used to cut from 00:02 to 00:19 of my recording and re-encode it at decent quality. Unfortunately you can’t just use “-copy” in ffmpeg because that doesn’t properly trim the audio for some reason; you have to reencode.

ffmpeg -i obs.flv -c:v libx264 -preset slow -crf 20 -ss 00:00:02 -to 00:00:19 out.mp4

Man I’d like a simple GUI program that lets me watch the movie and set a start time, an end time, and press a button to do this cut for me.

Share content

Now you have an ordinary MP4 movie file you can share anywhere. I uploaded it to Streamable, a lightweight hosting / sharing service for video that plays nicely with Reddit and friends. They re-encoded it to a 2260 kbps vp8+vorbis file which still looks pretty good. In particular I think they kept my 60 frame per second source, much appreciated.

LoL protocol: channels

I sliced my ~20 minute ARAM game packet capture a different way, looking at channel numbers. Enet is a multichannel protocol, it can contain up to 0xff different channels. No idea what guidance there is for using this feature, but here’s what I found. Note that my parser still breaks on some packets, so I discarded things that look malformed or very rare. Ie: report is not 100% complete.

Channel 0xff: control. 2%
Starts the game off with a CONN/VCON pair.
For the whole game, client sends PING roughly twice a second. It gets an ACK about 35-40ms later (my client’s RTT.) A new ping is sent almost exactly 500ms after the last ACK is received.
For the first three minutes, server sends PING roughly twice a second which then client immediately ACKs. Server pings mostly stop after 180 seconds, although I did see a single server PING at 519, 848, 964, 1666, and 1928 seconds.
The PING packets are generally just 12 bytes big, but occasionally are bigger: 30 or 31 bytes is next most common.

Channel 0x03: server to client. 42%
Entirely reliable packets. A whole lot. 54% are small (14 bytes is most common), but some get to 100s of bytes. I imagine this is the important game state.

Channel 0x01: client to server. 35%
This contains all of the traffic the client sends the server. A healthy mix of Enet packet types (reliable, unreliable, and unsequenced). 72% of these packets are very small (14, 24, or 25 bytes). Some are a little bigger.
I ran a second game which was a custom solo game for just 4 minutes with me doing nearly nothing, almost no input. There were almost no reliable packets sent by my client at all; that is consistent with the reliable packets being used for user input. I wonder if all the unsequenced/unreliable traffic is used for bot detection, tracking the user’s mouse position or other signals from the client?

Channel 0x04: server to client. 19%
A bunch of SUNR packets first; those are unreliable but sequenced. Then a stream of SUNS packets; those are unsequenced. No one packet length dominates, the most common is a 40 byte packet at 9%. But almost all the traffic is in the 40-60 byte length.

Channel 0x02: server to client. 1%
Entirely unreliable packets. Not many. 71% are 25 bytes.

Channel 0x05: server to client. 0.03%
This is a mystery. It’s very low traffic, 25 or so over the whole trace. But they’re there and they are sequenced.

Conclusions

I think channel 3 is most interesting as a source of lag; that’s the server sending reliable packets to the client. Channel 1 is also interesting since it contains the clients’ reliable packets to the server.

I just noticed that SUNS packets (unsequenced) still contain sequence numbers. That’s handy for monitoring out of order and loss even if the protocol doesn’t treat those as errors.

I also did a quick spot check of this data vs. a custom solo game I recorded for ~4 minutes where I did almost nothing. The traffic distribution was roughly similar other than the difference in  channel 1 I noted above.

Here’s a table of popularity of packet types and channel number.

    1469 .4164 PING   :ff
    1459 .4135   ACKK :ff
     299 .0848 ACKK   :ff
     298 .0845   PING :ff
       1 .0003 CONN   :ff
       1 .0003   VCON :ff

   38364 .2362 SUNS   :01
    8541 .0526 SREL   :01
    8540 .0526   ACKK :01
     967 .0060 SUNR   :01

   34606 .2131   SREL :03
   34217 .2107 ACKK   :03

   29401 .1810   SUNS :04
    1689 .0104   SUNR :04

    1510 .0093   SUNR :02

      23 .0001 ACKK   :05
      23 .0001   SREL :05

libenet / league of legends protocol success!

Last year I looked into the League of Legends real time protocol, the format of the UDP messages between the game server and clients. My recent lag problems motivated me to look again and I’ve gotten somewhere this time.

The protocol is said to be based on libenet 1.2 with some modifications. The body of the protocol itself is encrypted, presumably to make it harder for third party hacks to sniff data from the game. (It doesn’t make it impossible though, so once again DRM frustrates legit use without dissuading cheaters.) But I don’t care about the body, I just want the enet headers, the sequence numbers and retransmits and stuff. And that’s in the clear!

The best guide I’ve found is this Wireshark dissector, or rather an updated version Boreeas kindly gave me that isn’t checked in anywhere. The key thing is inside the UDP packet, the first 8 bytes are a not-very-interesting header. Then the 9th byte is an Enet command, the 10th byte is a channel number, and the 11th and 12th bytes are the sequence number. (To complicate things sometimes only the first 6 bytes are the header, so the command is the 7th byte, etc.) ACK packets have some bogus sequence number, but the first 2 bytes after that are the sequence number of the packet being acknowledged.

So I put all that together and wrote some Python Impacket code and now I have something printing a summary of UDP captures I made. Below is a few lines from my outputter. This shows the server sending a reliable packet on channel 3 numbered 01a9, then another numbered 01aa, then another number 01ac. My client acknowledges all three. But what happened to 01ab? The server sends that along 200ms later, either because it arrived out of order or else because the server knew to try to send it again. Note that in the meantime 01ad also went missing; that never showed up, so I’m confused. Still, it’s a start. I assume the LoL client shows lag if a reliable packet doesn’t arrive properly.

SREL   03 01a9 00167.521401   00000000: 0D 89 78 BC A7 80 96 CE  86 03 01 A9 00 38 D6 23  ..x..........8.#
  ACKK 03 01a9 00167.521538   00000000: F3 CC 6D 92 A7 03 01 03  00 00 01 A9 96 CE        ..m...........
  SUNS 01 0000 00167.542210   00000000: F3 CC 6D 92 A7 03 49 01  00 00 03 8C 00 0A 87 99  ..m...I.........
SREL   03 01aa 00167.562514   00000000: 0D 89 78 BC A7 80 96 E5  86 03 01 AA 00 07 6F 00  ..x...........o.
  ACKK 03 01aa 00167.562663   00000000: F3 CC 6D 92 A7 03 01 03  00 00 01 AA 96 E5        ..m...........
  SREL 01 0065 00167.583485   00000000: F3 CC 6D 92 A7 83 8E B4  86 01 00 65 00 1F 6B 4F  ..m........e..kO
SREL   03 01ac 00167.629336   00000000: 0D 89 78 BC A7 80 97 28  86 03 01 AC 00 18 D8 AB  ..x....(........
ACKK   01 0065 00167.629393   00000000: 0D 89 78 BC A7 00 01 01  01 AC 00 65 8E B4        ..x........e..
  ACKK 03 01ac 00167.629477   00000000: F3 CC 6D 92 A7 03 01 03  00 65 01 AC 97 28        ..m......e...(
SUNS   04 0000 00167.688278   00000000: 0D 89 78 BC A7 00 49 04  00 00 03 DD 00 3B BA D6  ..x...I......;..
SREL   03 01ae 00167.688330   00000000: 0D 89 78 BC A7 80 97 64  86 03 01 AE 00 10 F5 54  ..x....d.......T
  ACKK 03 01ae 00167.688425   00000000: F3 CC 6D 92 A7 03 01 03  00 65 01 AE 97 64        ..m......e...d
  SREL 01 0066 00167.709221   00000000: F3 CC 6D 92 A7 83 8F 31  86 01 00 66 00 1F 6B 4F  ..m....1...f..kO
SREL   03 01af 00167.736732   00000000: 0D 89 78 BC A7 80 97 A5  86 03 01 AF 00 44 2B 25  ..x..........D+%
  ACKK 03 01af 00167.736863   00000000: F3 CC 6D 92 A7 03 01 03  00 66 01 AF 97 A5        ..m......f....
ACKK   01 0066 00167.739947   00000000: 0D 89 78 BC A7 00 01 01  01 93 00 66 8F 31        ..x........f.1
  SUNS 01 0000 00167.740008   00000000: F3 CC 6D 92 A7 03 49 01  00 00 03 8F 00 0A 23 68  ..m...I.......#h
SREL   03 01ab 00167.765224   00000000: 0D 89 78 BC A7 80 97 C2  86 03 01 AB 00 1B BC 8D  ..x.............
  ACKK 03 01ab 00167.765389   00000000: F3 CC 6D 92 A7 03 01 03  00 00 01 AB 97 C2 01 03  ..m.............
SUNS   04 0000 00167.770715   00000000: 0D 89 78 BC A7 00 49 04  00 00 03 DF 00 23 31 79  ..x...I......#1y

Here’s a breakdown of packet types from an ARAM game I recorded. 23.77% of packets are from my client to the server, “send unsequenced”. Huh, what does my client have to say to the server that’s so volumnious and yet unimportant? About 41% of traffic is the server sending reliable packets and the client acknowledging them and another 11% is the client sending reliable packets and the server acknowledging them. 21% of the traffic is unsequenced packets from the server, or about the same number of packets as reliable ones. I’d expected more of a bias to unreliable packets from the server than that.

   20086 .2377   SUNS
   17498 .2070   ACKK
   17475 .2068 SREL
   15406 .1823 SUNS
    5670 .0671   SREL
    5101 .0604 ACKK
    1528 .0181 SUNR
    1311 .0155   PING
     203 .0024   SUNR
     197 .0023 PING
      40 .0005 SFRG
       1 .0000 VCON
       1 .0000   CONN

Machine learning: Neural networks introduction

Week four of my Coursera machine learning course was a breezy introduction to neural networks. The lecture videos were very high level but did a good job introducing the concept. The part I hadn’t understood before was how regression techniques are really best suited for linear prediction models, that building Nth order polynomials out of M features leads to O(N*M) work and badness. I also hadn’t really understood that neural networks are just a series of logistic regressions. The input variables are mapped through a logistic model to an intermediate hidden layer (of some chosen number of features), then the hidden layer is mapped again through a second logistic model to yield output variables. However the lecture stopped before we got to backpropagation, so for this week the method of training a neural network is still a mystery.

Logistic regression applied to OCR

The homework is a bit behind and out of sync with the lecture notes. The bulk of the work in the homework was still doing logistic regression, last week’s lecture concept. The hardest part was figuring out how to vectorize the naive loop implementation of the regularized logistic regression cost function we did last week. But I’d already vectorized it so I could just copy my solution from last week, gold star!

The more fun part was actually applying one of these learned models to do something useful with real data; OCR classification of handwritten numbers. The input was 5000 images, 20x20 greyscale pixel arrays, along with their classification (“this squiggle is the number 7”). Our job was to build a multiclass classifier to do the OCR, to predict a digit. So we took the regularized logistic regression cost function we just implemented and used fmincg() to search for the best parameters to match the data. The resulting output vector (theta) is our prediction model. Then we applied that learned model to classify input data. So I’ve now built a linear regression OCR system for handwritten numbers! The final system predicted the input set with 95% accuracy. The final model is quite large; 4010 separate integers. 401 weights for predicting each digit from 0–9, or one weight per pixel plus a constant term. Not exactly parsimony.

One neat thing about multiclass models is they don’t just output a predicted clas (“the number 7”), they also output a vector of probabilities for each possible value: “probability this image is the number 1, probability it is the number 2, ...”. We crush those probabilities down to a single “this input is probably an image of the number 7”. But something to remember for later; machine learning models not only can return a prediction, but a confidence in that prediction. Or some ambiguity, I believe the math works such that a single image might have a 90% probability of being the number 7 and an 80% probability of being the number 9 (for a particularly ambiguous squiggle.)

Neural network forward propagation

The last part of the homework was implementing a basic neural network. Or rather the application of one, the forward propagation that maps the input data through the layers and gives outputs. We were handed parameters that had already been trained, so really this was just an exercise in “can you code up forward propagation?” Useful to do that myself though. In particular I had to puzzle out that the hidden layer consists of 25 nodes. So the final classifier is basically two steps. Logistic regression to map 400 pixels to 25 hidden nodes. And then a second logistic regression to map 25 hidden nodes to 10 probabilities. The central mystery of neural networks is what those “hidden nodes” really mean. And we have Deep Dream to thank for a lovely visualized expression of hidden states in a different kind of machine learning image processing system.

Metacomments

I almost gave up this week. Ran into a bunch of weird technical problems. By far the biggest one was me putting the line “print size(X)” in my code as a debugging aid and then forgetting about it. And suddenly my octave program is complaining about fig2dev missing and I’m down a rabbit hole of Homebrew installs trying to figure out what the hell is wrong. Turns out “print” means print, as in paper, and I needed “printf”. Derp.

I am also doing a lot of stumbling around and shallow learning. Like I know I need to combine the matrix X with the vector theta somehow but forgot which way. Rather than puzzle that out from mathematical principles, I just inspect and see X is 5000x400 and theta is 1x400, and I need to multiply them somehow, so the only sensible math is X*theta’ or theta*X’. So try one out and see if the homework oracle tells me I got the right answer, and call it a day. (Writing this out I realized I picked the wrong one of the two, which is why I keep having to transpose everything. oops.) Anyway this doesn’t feel like learning so much as just bashing about with the only thing that will pass a type checker. I keep telling myself I’m absorbing something though, and my real goal here is just to understand enough about what’s going on that I can use other people’s machine learning systems later.

I do wish the homework assignments had more interactive help. In particular a bit more hand-holding about how to run the code you write, understand what it’s doing, and test it against known good results. In desperation I started looking at the submit.m internals just to see what test cases the homework oracle was using. I don’t get to see the right outputs that way (they’re hidden on the server), but at least I have some reasonable test inputs I can look at.

The only actual course lecture notes are a wiki page. The wiki content is pretty good. But it requires a login to even read the pages! And Coursera’s wiki is broken somehow so you have to log in about once an hour, makes me very cranky.

New LoL NA servers

Riot is finally moving the North American League of Legends game servers from the west coast to somewhere more central, Chicago,. Their network operations guy RiotAhab has been making a series of great posts about netops, his post about the move is good reading. Also buried in the discussion is a comment from dArtaganan, a Riot employee, giving us a new server IP: 104.160.131.1. (Compare old IPs like 192.64.170.78).

A simple ping from my house to the new IP is 70ms. Some random other Chicago IP was about 60ms. Theoretical best RTT (speed of light in copper) is 30ms. Riot is promising ping increases of “up to 30ms” for west coasters, which would put me at 65ms.

That IP is in AS6507. My route to them from my Kansas server (12ms away) ends at be2217.ccr41.ord03.atlas.cogentco.com, which could be a Cogent datacenter like this one. Or maybe Cogent just provides the link and the warehouse is owned by someone else. Note the old west coast IPs are also in that ASN, Riot didn’t set up a new one.

Riot’s ASN has 110 peers, which is impressive; compare 13 for my ISP or 6 for my server. Google has 200+, mega-backbone he.net has nearly 4000. Anyway, Riot’s peering efforts are clearly visible. I imagine each one of those 110 peers is a separately negotiated contract.

Diagnosing a weird LoL lag issue

I’m having a weird lag problem where I get massive packet loss playing LoL. But the reported ping stays low (35ms) and the game is mostly playable. Some small hiccups that look lag related, more than I’m used to, but it’s not hugely awful. Really don’t know what’s going on.

My logs are telling me I’m losing 2.4% of my packets. That seems awfully bad; 0.1% or so is more typical. Borderline surprised it’s playable, but who knows. It’s not clear why the LoL client still reports the 35ms ping; the usual client behavior is if you’re losing packets the reported ping goes up. Or at least it used to be, maybe that changed?

I’ve done every test I can think of to prove that it’s not my home network in general to blame. I can iperf3 burst UDP traffic all day reliably from my house to somebits.com in Kansas. That shares the same route over my ISP as far as cr1-9greatoaks-te-0-7-0-8.bb.spectrumnet.us; then the somebits packets go through he.net on their way to Kansas while the LoL packets go through spectrumnet up to Portland and Riot’s datacenter. That route looks fine, as well as I can test. (with mtr -u, a UDP traceroute).

Confusing things more, a friend of mine also plays on the same ISP in San Francisco. His client is not showing any lag like I am. But we share almost the same route, our routes converge on the fourth hop from 76-14-93-222.sf-cable.astound.net / 76-14-93-218.sf-cable.astound.net onward. So if there were a bad router it’d be close to my house. But then my link to somebits.com goes through that same route and I can test that thoroughly, and it’s showing no problem.

Frankly all signs point to something being wrong with my Mac, the client itself. Only I can reproduce the problem on a second machine, my laptop! Could it be my router? Possibly. But it’s worked fine in the past. I’ll try to test without the router soon.

Here’s some stats from a Wireshark capture I did in an ARAM I just played. I was Amumu.

LoL server address: 192.64.170.78

Wireshark statistics

  • 39750 packets from server, 44769 packets from client
  • 2003 packets reported lost by the client. 2.4% packet loss rate!
  • 39kbps from server, 17kbps from client
  • Average packet size 228 bytes
"Address","Port","Packets","Bytes","Packets A → B","Bytes A → B","Packets B → A","Bytes B → A","Latitude","Longitude"
"192.64.170.78",5107,84517,9616369,39748,6599894,44769,3016475,"-","-"
"192.168.0.20",53040,84517,9616369,44769,3016475,39748,6599894,"-","-"


==================================================================================================================================
Packet Lengths:
Topic / Item       Count         Average       Min val       Max val       Rate (ms)     Percent       Burst rate    Burst start  
----------------------------------------------------------------------------------------------------------------------------------
Packet Lengths     84519         227.56        54            1038          0.0627        100%          0.2400        73.682       
 0-19              0             -             -             -             0.0000        0.00%         -             -            
 20-39             0             -             -             -             0.0000        0.00%         -             -            
 40-79             46272         62.08         54            79            0.0343        54.75%        0.1600        2.285        
 80-159            26150         101.90        80            159           0.0194        30.94%        0.0900        838.818      
 160-319           7204          228.76        160           319           0.0053        8.52%         0.0500        351.673      
 320-639           4120          437.28        320           639           0.0031        4.87%         0.0600        73.648       
 640-1279          773           814.54        640           1038          0.0006        0.91%         0.0600        73.717       
 1280-2559         0             -             -             -             0.0000        0.00%         -             -            
 2560-5119         0             -             -             -             0.0000        0.00%         -             -            
 5120 and greater  0             -             -             -             0.0000        0.00%         -             -            

----------------------------------------------------------------------------------------------------------------------------------


$ sudo mtr -u 192.64.170.78
                                   My traceroute  [v0.85]
ub (0.0.0.0)                                                        Tue Aug  4 17:43:25 2015
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                                                    Packets               Pings
 Host                                             Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. router.nelson.monkey.org                       0.0%   981    0.2   0.2   0.2   0.7   0.0
 2. 76-14-35-1.sf-cable.astound.net                0.0%   981    9.8  11.8   4.0 156.4   9.6
 3. 104.220.254.17                                 0.0%   981    7.4   9.2   3.6  31.3   4.0
 4. 76-14-93-218.sf-cable.astound.net              0.0%   981   14.6  17.2   7.7 234.4  22.8
    76-14-93-222.sf-cable.astound.net
 5. cr1-wsache-a-be-100.bb.spectrumnet.us          0.0%   981   11.8  14.2   9.1  37.2   3.8
 6. cr1-55SMarket-te-0-0-0-8.bb.spectrumnet.us     0.0%   981   11.1  14.7  10.3  37.6   4.7
    cr1-55SMarket-te-0-0-0-10.bb.spectrumnet.us
    cr1-55SMarket-te-0-0-0-9.bb.spectrumnet.us
    cr1-55SMarket-te-0-0-0-19.bb.spectrumnet.us
    cr1-55SMarket-te-0-0-0-11.bb.spectrumnet.us
 7. cr1-9greatoaks-te-0-7-0-6.bb.spectrumnet.us    0.0%   981   11.5  14.2   8.2  36.4   3.7
    cr1-9greatoaks-te-0-7-0-8.bb.spectrumnet.us
    cr1-9greatoaks-te-0-7-0-9.bb.spectrumnet.us
    cr1-9greatoaks-te-0-7-0-7.bb.spectrumnet.us
 8. cr1-pdx-te-0-0-0-4.bb.spectrumnet.us           0.1%   981   44.3  30.8  23.8  56.2   4.5
    cr1-pdx-te-0-0-0-5.bb.spectrumnet.us
    cr1-pdx-te-0-0-0-6.bb.spectrumnet.us
 9. cr2-fdcp-t4-4.bb.spectrumnet.us                0.0%   981   29.4  34.2  25.2 376.9  25.7
10. 216.243.25.86                                  0.0%   981   28.3  29.9  24.8  51.3   4.0
11. ???

Graph of packets / second

Packets per second

Update

Some updates after a few experiments

  • Problem definitely occurs on two different computers, an iMac and a Macbook Air
  • Problem occurs without my router / switch. Still plugged into my cable modem.
  • I played a game with a friend of mine who happens to also be in San Francisco on the same ISP and plays on a Mac. He had no lag, I did. Here’s my Logs of Lag report and here’s his. I lost 80 packets a minute, he lost 2. WTF? According to traceroute our routes are the same after the 4th hop above, so if it’s a problem in the route it’s something very close to my house at my ISP.
  • However, I can happily shove a huge amount of UDP traffic into my house with no problems. And those packets also traverse that same route to hop 4.
  • I see the same problem on a Windows box in my house. (35 packets lost / minute in a Custom game, which is line with results on the Macs I play on.)

My next step is to try playing through a VPN and see if it helps. I’d also like to understand better what it means for the LoL client to know it’s lost 2.4% of packets and yet still report a low ping. That seems odd; usually the reported ping number goes up in response to retransmits, or at least I thought it did.

Update 2

A friend of mine has a VPS at directspace.net, which is either in the same datacenter as Riot NA or else very nearby. He ran an  iperf2 server for me. Here’s some redacted data testing from my problem network.

iperf shows 69 packets out of 26224 lost, and 47 out of order. that’s about normal for a working link I think, and 1/10th the loss rate I’m seeing from the game.

mtr shows at worst 1 packet dropped out of 100. the stddev to hop 4 is higher than I’d like though.

$ iperf -l 300 -u -t 60 -i 10 -c XXX.XXX.XXX.XXX
------------------------------------------------------------
Client connecting to XXX.XXX.XXX.XXX, UDP port 5001
Sending 300 byte datagrams
UDP buffer size:  208 KByte (default)
------------------------------------------------------------
[  3] local 192.168.0.65 port 34071 connected with XXX.XXX.XXX.XXX port 5001
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0-10.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 10.0-20.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 20.0-30.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 30.0-40.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 40.0-50.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 50.0-60.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3]  0.0-60.0 sec  7.50 MBytes  1.05 Mbits/sec
[  3] Sent 26225 datagrams
[  3] Server Report:
[  3]  0.0-60.0 sec  7.48 MBytes  1.05 Mbits/sec   1.561 ms   69/26224 (0.26%)
[  3]  0.0-60.0 sec  47 datagrams received out-of-order

$ mtr --report -c 100 -u XXX.XXX.XXX.XXX
Start: Wed Aug  5 21:37:40 2015
HOST: ub                          Loss%   Snt   Last   Avg  Best  Wrst StDev
  1.|-- router                     0.0%   100    0.2   0.2   0.2   0.5   0.0
  2.|-- 76-14-35-1.sf-cable.astou  1.0%   100    9.3  11.0   5.4  57.1   7.2
  3.|-- 104.220.254.17             0.0%   100    9.9   9.4   5.0  28.1   4.1
  4.|-- 76-14-93-222.sf-cable.ast  0.0%   100   14.5  15.0   9.9 114.6  11.0
  5.|-- cr1-wsache-a-be-100.bb.sp  0.0%   100   11.9  14.9  10.2  33.2   3.7
  6.|-- cr1-55SMarket-te-0-0-0-8.  0.0%   100   11.9  13.4  10.4  32.0   2.3
  7.|-- cr1-9greatoaks-te-0-7-0-8  0.0%   100   14.6  15.1  10.3  33.1   4.6
  8.|-- cr1-pdx-te-0-0-0-4.bb.spe  0.0%   100   26.6  29.8  26.2  47.5   3.9
  9.|-- cr2-pdx-te-0-1-0-4.bb.spe  0.0%   100   29.7  29.6  26.1  47.8   3.3
 10.|-- directspace.nwax.net       1.0%   100   29.9  31.8  26.0 166.0  15.4
 11.|-- 69-163-34-113.in-addr.arp  0.0%   100   28.1  28.8  25.2  31.4   1.2
 12.|-- XXX.XXX.XXX.XXX            0.0%   100   28.6  29.3  26.1  47.0   2.7

Update 3: I have a theory: out of order packets. My mtr tests are telling me there’s something a bit flaky between hops 3 to 4. Occasionally a packet will take a very long time, like 200ms, and the stddev on that hop is way higher than the others. I wonder if an out of order packet causes the LoL client to drop it or otherwise treat it as a lost packet? To further complicate things, mtr -u shows me that there are many different paths on my route. All the same lengths, but node 4 (the suspect one) has a couple of different IP addresses that show up. If only one path is congested that will cause a lot of out of order packets.

I don’t know what LoL does with out of order packets. ENet, the protocol LoL is based on, is pretty clear about what it does:

ENet provides sequencing for all packets by assigning to each sent packet a sequence number that is incremented as packets are sent. ENet guarantees that no packet with a higher sequence number will be delivered before a packet with a lower sequence number, thus ensuring packets are delivered exactly in the order they are sent.

For unreliable packets, ENet will simply discard the lower sequence number packet if a packet with a higher sequence number has already been delivered. This allows the packets to be dispatched immediately as they arrive, and reduce latency of unreliable packets to an absolute minimum. For reliable packets, if a higher sequence number packet arrives, but the preceding packets in the sequence have not yet arrived, ENet will stall delivery of the higher sequence number packets until its predecessors have arrived.

But I don’t know how LoL uses these features, in particular what packets are marked reliable / unreliable.

The good thing about this theory is it explains a lot of the facts I see, including why my friend at the same ISP doesn’t have the same lag. (He’s beyond hop 4!). The bad thing about this theory is I still can’t really reproduce the presumed failure with iperf. iperf3 does report out of order packets (as an error message!) but I’ve only been able to induce it to do that with ridiculously high bandwidth tests, and even then not reliably. But maybe iperf3 is really polite and sends packets spaced exactly N ms apart so is less likely to have an ordering problem?

Here’s an ICMP traceroute showing the high stddev at node 4.

$ mtr -n somebits.com

                             My traceroute  [v0.85]
ub (0.0.0.0)                                           Wed Aug  5 23:03:04 2015
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                                       Packets               Pings
 Host                                Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. 192.168.0.1                       0.0%   539    0.3   0.3   0.2  29.1   1.2
 2. 76.14.35.1                        0.4%   539    8.0  11.0   4.7  60.6   7.7
 3. 104.220.254.17                    0.0%   539    8.0   9.6   5.5  30.4   4.7
 4. 76.14.93.222                      0.6%   539   13.5  17.0   9.7 229.9  22.1
 5. 208.76.187.33                     0.0%   539   28.9  14.1  10.2  36.7   4.1
 6. 208.76.185.26                     0.0%   538   12.8  14.6   9.0  35.5   4.8
 7. 208.76.185.58                     0.0%   538   13.6  14.0  10.0  36.8   3.7
 8. 206.223.116.37                    0.0%   538   14.7  16.5   8.5  44.6   5.6
 9. 184.105.213.106                   0.0%   538   38.3  44.2  37.0  74.5   5.9
10. 184.105.222.22                    0.2%   538   91.2  82.6  62.7 121.7  14.5
11. 184.105.213.37                    0.0%   538   71.1  69.6  62.9  96.7   5.8
12. 216.66.78.90                      0.2%   538   56.5  56.6  48.1  83.5   6.2
13. 69.30.209.138                     0.0%   538   49.6  54.4  47.9  83.6   6.1
14. 192.187.107.5                     0.0%   538   53.4  54.9  48.2  87.9   5.4
15. 107.150.51.74                     0.0%   538   51.3  52.1  47.4  96.1   4.8

Update 4: A VPN fixes my problem! I sort of predicted it would, glad to confirm my hunch and also nice to have a workaround until the real problem is fixed. I set up a TCP VPN through Cloak, promised to US West Coast. I ended up going through Seattle. The resulting log shows a little more latency than without the VPN but also nearly no packet loss. Yay!

I set up Cloak because they have a really great Mac client, easy to get going. If I make a habit of this I may consider a VPN endpoint I own up in Seattle / Portland. Would rather just fix my ISP problem though. Don’t want to be paying $10 a month just to fix someone else’s broken service.

Update 5: this problem went away, and I don’t know why. I’m now playing games with 0.2 packets / s, very good, and no obvious lag. It may have been fixed by the Riot server move to Chicago, that’s the most likely explanation. But I’m still struck by the way I was getting this lag and my friend playing the same game with me on the same ISP wasn’t! That fourth hop from me is still showing suspiciously high standard deviation, so whatever that means it may well be unrelated.

iperf to measure UDP loss

Sometimes I want to test link quality by seeing if UDP packets are getting lost. iPerf is a nice tool for that. It’s a client + server command line app that generates floods of packets and verifies they arrived on the other end. A bandwidth intensive ping.

To confuse things, there’s an iperf2 and an iperf3. They sort of do similar things but I think iperf3 is mostly better. In particular the server is now mostly a dumb packet reflector and the client can give the server instructions like “try UDP now” etc, more suited for running a server somewhere stable and headless and testing with the client. See in particular the -R option to ask the server to send packets to the client.

server$ iperf3 -s

client$ iperf3 -u -c somebits.com
Connecting to host somebits.com, port 5201
[  5] local 192.168.0.23 port 63531 connected to 107.150.51.74 port 5201
[ ID] Interval           Transfer     Bandwidth       Total Datagrams
[  5]   0.00-1.00   sec   120 KBytes   983 Kbits/sec  15
[  5]   1.00-2.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   2.00-3.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   3.00-4.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   4.00-5.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   5.00-6.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   6.00-7.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   7.00-8.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   8.00-9.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   9.00-10.00  sec   128 KBytes  1.05 Mbits/sec  16
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Jitter    Lost/Total Datagrams
[  5]   0.00-10.00  sec  1.24 MBytes  1.04 Mbits/sec  1.545 ms  1/159 (0.63%)
[  5] Sent 159 datagrams

iperf Done.

If I understand correctly the default UDP settings try to send 1 megabit a second worth of packets. That works out to 128 KBytes each second in 16 datagrams, or 8192 byte UDP datagrams. With the usual 1500 byte MTU that works out to 6 actual packets. You can set options for bandwidth, maximum datagram size, etc. Here’s a nice long test sending 1400 byte packets.

iperf3 -R -l 1400 -l 1000 -t 100 -u -c somebits.com

There’s a few public iperf servers to test against. The one run by @scottlinux in California was working well when I just tried it.

Machine learning: Logistic regression

Just finished week 3 of Andrew Ng’s machine learning course on Coursera. I’m going to try to blog each week summarizing what I learned.

This week’s topic is logistic regression; predicting discrete outcomes like “success or failure” from numeric data inputs. Ie: “our diagnostics measure these 4 numbers for a tumor. Is it cancerous or benign?” Turns out logistic regression is basically just linear regression where the output set is restricted to the interval [0, 1]. Normal linear regression gives all real numbers on output, so you pass that through the sigmoid curve to bound the result to [0, 1]. That number is effectively “the probability the output is 0”, you can then threshold it at 0.5 to map it to a strictly binary “success or failure” output. There’s a bunch of math then to define the cost function and the partial derivatives of the cost function which you can then use with an optimization algorithm like gradient descent.

Logistic regression only classifies data into two classes. If you want N classes you do logistic prediction many times, ie: “is it A or not A? is it B or not B? is it C or not C?” and then pick the class ABC with the highest probability.

The predictor you get from the logistic regression is best understood in terms of a decision boundary, a drawing of the threshold that tips an input from success to failure. My final homework assignment was learning this threshold boundary to separate plusses from squares where the input data is 2 dimensional. The green line is the learned threshold boundary, some sixth order polynomial the magic optimizer found for me.

Screen Shot 2015-08-02 at 11.02.08 AM

Thankfully the course moved on a bit from math into “use the black box” by introducing fminunc, a black-box minimizer provided by Matlab/Octave. All it needs is the cost function and its partial derivatives and it does who-knows-what to find the minimum. Frankly I wish the class spent more time on how to use fminunc well and less time deriving the gradient descent solutions that I’ll never use again. But gradient descent is a nice simple optimizer and it is good to know how at least one works.

This week also introduced the concept of overfitting, of specializing your predictor too tightly to the data. Regularization was the solution provided for overfitting; basically biasing the cost function to prefer small values of theta, the learning model parameters we’re optimizing. Ng doesn’t really explain why small values of theta are “better” other than presenting some intuition that a theta_i of 0 means the parameter is fully ignored and a theta_i of 1000 means it’s way too overemphasized. The regularization parameter lambda is picked out of a hat much like the learning rate alpha is also picked for gradient descent.

Along the way I learned how to define anonymous functions in Octave which then gives you a really easy way to curry a partial function application (in this case, currying X and y into my costFunction so that fminunc only works on the parameter t.

fminunc(@(t)(costFunction(t, X, y)), initial_theta, options)

I continue to be amazed that I type vector equations into Octave and they Just Work on first try, despite my being rusty on linear algebra not to mention matrix programming languages. I’m kind of just accepting that if the homework grader says I got it right I’m done.

Some metacomments about the course... I read something somewhere that characterized this as an advanced undergraduate class, maybe sophomore or junior level. That feels about right and explains why it seems a little too easy. But easy in the right ways for me, I really don’t want to do the math derivations. Also I discovered a lot of previous students’ homework checked in on GitHub. Cheating would be stupid, who would I cheat but myself? But it’s nice to be able to look what other students did. Helped me verify arrayfun() was really the right thing to apply a scalar function to a matrix, for instance.

Now I feel like I’ve studied enough machine learning to apply it to a problem I care about. I intend to look at League of Legends match results, to see whether I can predict a game is a win or a loss based on match performance. The simplest thing is to look at end of game stats like kills or gold earned. Of course end of game I already know for sure if it was a win or a loss, but I’m thinking I can read the learned model parameters out to see how significant a contribution those inputs like kills are to whether a team wins. Alternately I can get ahold of some mid-game stats like “gold earned after 20 minutes”, whether that results in a win or a loss is a bit more of a legitimate prediction problem.

Python looping for n times

A Twitter friend proposed an idiom for doing something N times in Python I hadn’t seen before, Using itertools.repeat instead of range. I was curious if it was better.

$ python3 -V
Python 3.4.3
$ python2 -V
Python 2.7.10

$ python3 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 275 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 133 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(1, 10000): pass'
10000 loops, best of 3: 130 usec per loop

$ python2 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 218 usec per loop
$ python2 -m timeit 'for _ in xrange(10000): pass'
1000 loops, best of 3: 179 usec per loop
$ python2 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 122 usec per loop

So huh, itertools.repeat is about 50% the cost of using range. We’re only talking 13ns per iteration, or roughly 50 CPU cycles. If you’re doing meaningful work in that loop it won’t matter. Still it’s neat that itertools.repeat is more efficient. Perhaps this shouldn’t surprise me, it doesn’t have to do the work of generating increasing integers. But I’d assumed no one had optimized itertools this carefully.

Note that in Python3 range is an actual type and doesn’t create a list, tuple, iterator, or generator. Also interesting that repeating an integer is 3% more efficient than repeating None; that’s a reproducible result.

Python2 is faster across the board. I see that a lot in Python and it makes me wonder. But the itertools vs. range/xrange difference is still about 50%, or meaningful.

Having now understood all this I’ll go right back to using range() like my grandpappy did.

MacOS directory permissions

Macs have this weird problem where the Unix file permissions for things get corrupted. Not just a couple of top level directories either. Things like the Finnish localization file for iBooks, an app I have literally never run, is marked group writeable and shouldn’t be. How does this happen?

The thing that’s most alarming is my root directory, /, is mode 0777. World writeable. And owned by my user account, not root. Literally any program running on my computer can come in and hijack the whole system because of that. Not the first time that’s happened either. I’ve read somewhere that a bunch of bad Mac install scripts like to just recursively make things world writeable “to make it work” and they work their way up to /. Also there was that one time when iTunes kept making /Users world writeable. Quality programming there, Apple.

The problem is so common Disk Utility has a special GUI app just to “repair permissions” by comparing the filesystem to records of what should be there left behind by installers. Only that’s a little scary because what if it breaks something? Helpfully there’s an audit mode just to see what’s changed. Run from the GUI or via diskutil verifyPermissions /.

At the bottom of the page is the audit of what all the tool finds wrong on my Mac after filtering out 3000+ lines of iBooks.app garbage. Mostly not too scary, although libruby.dylib being world writeable sure seems like a potential security disaster. The most terrifying one is

Warning: SUID file “System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent” has been modified and will not be repaired

What, a setuid root executable that’s part of a remote management system that’s been modified? Why that’s not suspicious at all! But have no fear: Apple itself says that’s one of roughly 100 messages from the audit you can “safely ignore”. So yes, the security audit tool prints a lot of false positives. Fucking garbage.

Note that the root directory is not one of the reports in the audit.

I felt lucky and ran the tool and it changed a bunch of things. Then ran the audit again and it found three problems, including the setuid root file I’m supposed to ignore.

It did not repair my root directory. I manually set that to 0755, owned by root.wheel.

Started verify/repair permissions on disk0s2 Macintosh HD
Permissions differ on "System/Library/CoreServices/Feedback Assistant.app"; should be drwxr-xr-x ; they are lrwxr-xr-x 
Permissions differ on "usr/lib/libruby.2.0.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Permissions differ on "usr/lib/libruby.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Warning: SUID file "System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent" has been modified and will not be repaired
Permissions differ on "Applications/Safari.app/Contents/Resources/Safari.help/Contents/Resources/index.html"; should be lrwxr-xr-x ; they are -rw-r--r-- 
Group differs on "Library/Printers"; should be 80; group is 0
Group differs on "Library/Printers/Icons"; should be 80; group is 0
Group differs on "Library/Printers/InstalledPrinters.plist"; should be 80; group is 0
Permissions differ on "Library/Printers/InstalledPrinters.plist"; should be -rw-rw-rw- ; they are -rw-r--r-- 
Group differs on "Library/Java"; should be 0; group is 80
Permissions differ on "Library/Java"; should be drwxr-xr-x ; they are drwxrwxr-x 
Group differs on "Library/Preferences/SystemConfiguration/com.apple.Boot.plist"; should be 80; group is 0
Group differs on "Library/Preferences/com.apple.alf.plist"; should be 80; group is 0
Group differs on "Library/Printers/PPDs"; should be 80; group is 0
Group differs on "Library/Printers/PPDs/Contents"; should be 80; group is 0
Group differs on "Library/Printers/PPDs/Contents/Resources"; should be 80; group is 0
Permissions differ on "System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/libruby.2.0.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Group differs on "private/var/db/GPURestartReporter"; should be 0; group is 80
Permissions differ on "private/var/db/GPURestartReporter"; should be drwxr-xr-x ; they are drwxrwx--- 
Finished verify/repair permissions on disk0s2 Macintosh HD

New Mac logic board: system identity

I brought my 2011 iMac in for repair, to replace a video card under an extended warranty program specific to my hardware configuration. (Reading between the lines, a cooling problem.) Once they got it on the testbench the tech decided to replace the system board as well because it tested faulty. At no charge! Despite the machine being a year+ out of warranty. Nice of them.

Anyway, a new system board means a new CPU, a new ethernet MAC, and a bunch of other small things. Which changed my machine’s identity for various things. I had to re-log in to all Apple online services. Time Machine also expressed concern but offered to “inherit” the backup I had, which seems to have worked. Had to set up a new IP assignment on my router for the MAC address of course.

I’d also logged Chrome out of Google and wiped all local state, for my security. Happy to report that logging back in to Chrome restored everything pretty well. I got all my Chrome extensions back but lost the extension configuration state. Also my browser link history is gone forever, I’d sort of hoped that would sync through Google too.

Fixed wireless Internet: Cambium, Ubiquiti

I don’t believe in wireless communications. Too spooky. Also too unreliable, and slow. And 2.4GHz wifi is particularly bad in San Francisco, between the crowding, the lack of distinct channels in 802.11a/b/g, and the faraday cages surrounding all our lathe-and-plaster rooms.

But in Grass Valley wireless is the only option. AT&T and Comcast refuse to provide wired service to rural homes and PUC and the FCC are not regulating their monopolies effectively. My ISP is SmarterBroadband, a wireless ISP that works by establishing fixed wireless links from house to house to regional distribution point to central office and then down to fast fiber backhaul. It works surprisingly well and reliably, the main limiting factor has been speeds and the challenges of getting clear line-of-sight in a hilly area covered with trees.

My link for the last couple of years has been a 900 MHz link through oak trees to a house 1.4 miles north of me. The key thing about 900 MHz is it works OK through tree cover, something higher frequencies has a harder time with. Cambium Networks hardware running Canopy, which I think dates back to the old Motorola Canopy days. It’s been pretty reliable; the only time my point to point link has failed has been in heavy snow, and then only because snow accumulated on the antenna. Also low latency (20ms?) and low jitter. The problem has been speed. The max link speed is 2600kbits/s, and the product they sell me only bursts that fast before throttling me down to 1000kbit/s. That’s 300 megabytes / hour, and it sucks.

Yesterday they upgraded me. Sent a guy 70 feet up a tree with a Cambium ePMP 1000, a 5Ghz antenna. Pointed at the same house but that far up we’re above the trees, clear line of sight. I’m told the link is good to 25 Mbit/s but I’m being sold 12/2 Mbps. Which is still pretty great and I’m grateful for the upgrade. I’m surprised how cheap the antennas are. They offered me an upgrade for a very low cost, and it looks like you can buy your own antenna for about $140. Of course you need the service!

In addition to 900MHz and 5GHz my ISP sells two other types of wireless links. There’s a 2.4GHz product they mostly don’t sell any more. It also requires clear line of sight, but is slower than 5GHz. And they have a new 3.4GHz product they label “4G”, I think because it’s based on cellular technology. It’s pretty fast too (their product offers 70% the bandwidth of 5GHz) and is able to handle a little multipath, so works with a small amount of tree cover. Didn’t work at my house though, and once we were committed to going up a tree we might as well use the 5GHz gear.

The other half of the problem I have now is getting the Internet connection from the tree 200′ from my house inside. I’m intending to run cable, but that may get complicated depending on the status of existing conduits and the challenge of trenching. Right now I have a shitty old Linksys WRT54GL sitting outside and it works surprisingly well. That’s making me think I should try a wireless link instead, even though I don’t believe in wireless.

I asked on Metafilter and got a clear consensus answer on the product I need: a Ubiquiti Nanostation M. These are consumer grade point to point wireless links. There’s a variety of frequencies and antenna sizes. They’re rated for 5+ miles so are way overkill for my 200 ft needs. But then I can probably use the tiny 9″ x 3″ antennas and be done with it. It looks like I can get a pair for about $150. Need mounting hardware and a bit of wiring work at both ends to install it right, but still that’s got to be cheaper than digging a trench.

The big question is how reliable this kind of link is. Reports are promising! I’m also curious to know what’s going on at a protocol level. They call their protocol “airMAX” which is apparently not 802.11, it’s some TDMA thing. OK, I’m fine with proprietary. But then does the link work as an ethernet bridge? Or is it working at an IP level and messing with my packets? More to learn.

Wireless; maybe not as scary as I have believed! Still nothing beats a clean run of Cat5e. Except a pickup truck full of hard drives, of course.

Update: Ubiquiti answered a tweet I made asking for advice, with a suggestion to use the Nanostation locoM5 and a suggested wireless bridge configuration. That sure makes it easy!

Multivariate linear regression, gradient descent

I’m taking Andrew Ng’s online Machine Learning course on Coursera. First time doing a MOOC for real, and on the fence about the learning style, but it is nice to have an organized class with weekly assignments.

Two weeks have gone by. The two weeks together sort of consist of one learning unit. You learn how to do linear regressions for datasets. What does that have to do with machine learning? Well, a linear regression model is a very simple form of predictive modelling for a dataset. “I fit this straight line to my 100 data points, then can use that line to predict values for arbitrary other inputs”.

The course is a bit schizophrenic about being math vs. computer programming. Ng’s lecture notes are entirely in terms of linear algebra, building up to result equations like

Screen Shot 2015-07-26 at 6.55.26 PM

(WTF? X is a matrix of your input feature set; m rows of n features each. y is an m row vector of expected feature outputs. Theta is an m row vector that is the coefficients of your linear regression prediction model. Alpha is the “learning rate”, a number that’s picked essentially by intuition. The assignment := is shorthand for iteration; we keep iteratively improving the theta vector until it converges.)

I hate linear algebra. Always did, ever since I was 19 years old and it was my 8AM class. It was the only math class I nearly failed, then crammed super hard the last week and got an A. Then promptly forgot it all. Happily, this class is also a programming class, and the actual exercises are “implement this function in Octave / Matlab”. So I get to turn that confusing math into simple code:

Screen Shot 2015-07-26 at 7.04.07 PM

While I’m a good programmer it’s been many years since I used a matrix programming language like Maple/Matlab/Octave/R. So getting to that function was hard-worn. I ended up implementing that by following Ng’s lecture progression. He starts with a simple single variable linear regression. I coded that using lots of loops so all the actual arithmetic was scalar operations. Then I tediously hand-translated all those loops into vector forms and generalized it to multivariable inputs. Good learning exercise both to remind me how linear algebra works and to learn the funky vagaries of Octave/Matlab execution. (TIL automatic broadcasting). It was gratifying to see how much faster the code ran in vector form!

Of course the funny thing about doing gradient descent for linear regression is that there’s a closed-form analytic solution. No iterative hillclimbing required, just use the equation and you’re done. But it’s nice to teach the optimization solution first because you can then apply gradient descent to all sorts of more complex functions which don’t have analytic solutions. If I end up getting to do genetic algorithms again I’m gonna be thrilled.

In the end I feel pretty proud of myself for completing week 2, doing all the optional extra work, and understanding it all. My long term goal here is just to understand enough about machine learning algorithms that I can stop worrying about how they are implemented, just bash about with someone else’s software libraries applied to my data. But it’s helpful to understand what’s going on under the hood.

Installing Octave on Mavericks

I’m using Octave for a machine learning course I’m taking online. It’s an open source MatLab clone, and true to open source it is ugly, awkward, and doesn’t install easily. Of course it’s also great free software that I’m grateful for, but that doesn’t make it easier to install.

There’s a binary version of Octave 3.8.0 that is an official installer. But the command line interface doesn’t seem able to plot graphics of any kind. The GUI version can, but there’s so many other bugs in the GUI I want the command line to work. Specifically for a program like this to run:

t = [0:0.2:2*pi];
y=sin(t);
plot(t,y);

Homebrew has a formula for Octave 3.8.2 with a zillion dependencies and options. In theory “brew install octave” should work but in practice it’s not sufficient. Here’s something approximating what worked for me, based mostly on these notes

  1. brew install Caskroom/cask/aquaterm
    Some funky graphics system that allows plots to be drawn without X11
  2. brew install gnuplot --with-x11 --with-aquaterm
    Install GNUPlot using various graphics systems. The octave formula doesn’t seem to select these reliably.
  3. brew install octave --without-docs --without-gui --without-java
    Building the docs induces TeX to be installed. No thanks. I have no idea what optional Java things Octave depends on but I’d rather not bother. And I don’t want the experimental GUI, so skip that too.
  4. brew link --overwrite gcc
    Octave’s formula is designed to be built with gcc and gcc’s Fortran. It installs gcc (which takes over an hour to compile!) but I had a different version of gfortran installed previously, which caused my Octave build to fail. The --overwrite causes the gcc package to override gfortran.
  5. brew install ghostscript
    I had to run this three times by hand because the download server was broken.

This took about 3 hours total. Once completed, my simple 2 line plot program works. Yay!

One added complication; you can select different graphics systems in Octave at runtime. The brew info even helpfully tells you how:

setenv('GNUTERM','qt') # Default graphics terminal with Octave GUI
setenv('GNUTERM','x11') # Requires XQuartz; install gnuplot --with-x
setenv('GNUTERM','wxt') # wxWidgets/pango; install gnuplot --wx
setenv('GNUTERM','aqua') # Requires AquaTerm; install gnuplot --with-aquaterm

If I don’t set this at all, I seem to be getting aqua. And it works. I can also use the x11 graphics system and it works as well.

That IPython web browser integration sure looks like a smart idea now doesn’t it?

JSON query languages

Following up on an earlier post, a roundup of some systems for querying JSON documents. I’m looking for small data extraction languages that make it very easy to extract bits of data from a bunch of JSON blobs. Kind of like regular expressions or XPath or CSS Selectors. A key thing here is being able to do stuff like “find me the parts of this JSON document that have a property foo with value bar”. Also dealing with arrays intelligently.

jq. It’s the most popular JSON query language, and quite powerful. I also find it really terse and confusing but maybe that’s because I don’t use it enough. But it’s definitely the tool to compare everything else to. There’s also been some work on a usable libjq so you can use it inside other languages, like these Python bindings.

OboeJS. It’s a streaming JSON parser but also has an XPath-like language for pulling out chunks of a document. I like the look of it.

jsonfilter is a very simple grep-like tool that works with hierarchical input. It looks good and simple for doing simple things. The author is someone I trust to think a tool like this through.

Postgres. It has native support for JSON types and a pretty decent set of functions for working with it. It also has functions for converting JSON to Postgres’ array and recordset types, which you can then further query. And the JSONB type has a few extra query options. I don’t think I’d load data into Postgres just for JSON queries, but if you have JSON there already it’s pretty powerful.

MongoDB’s JSON query language is surprisingly limited for a system that’s all about searching JSON documents. Maybe that’s just my ignorance, but I can’t find any operators for diving into the document structure other than basically walking the JSON document tree manually.

Other options I didn’t explore. #1 question is whether these have momentum and/or a future. A bunch of them look active on first glance. Will update as I read about them and find anything interesting. There’s a bunch of other things not on this list, too.

Update: in further discussion, pvg notes it’s helpful to split JSON query systems into two groups: “QLs that do selection/filtering and QLs that do that and also processing and sorting and munging and aggregation and summing and map/reduce and ...”.

I really want a system that does all the processing and sorting and munging too. But SQL is very good at that already. So really I just want to do some simple extraction with jq or whatever and then feed it to a SQL system for aggregate reporting. Or else maybe just use Postgres to do everything? I need to get my hands dirty with some feature extraction examples to see how jq / postgres / etc feel.

2011 iMac crash: vertical lines on screen

My iMac just crashed hard. Watching a video in VLC one second, dead machine with mostly black screen the next. Some strange light colored vertical lines.

Googling around this is apparently a known problem, a hardware failure of the GPU. This Apple support page notes a particular known problem for exactly my model of video card and CPU. (2011 iMac, AMD Radeon HD 6970M GPU, 3.4GHz i7 CPU). Sounds like they have a repair program.

LoL API: match data

A long hard look at what is in Riot’s /match API call. It is well documented but those docs are about the individual trees, this is the forest level view. Particular focus on data that’s not visible in the match history view. (This is NA match #1892290414. None of the participants are my friends, but it is ranked and therefore public.)

Long story short, the most interesting data that’s not currently visualized in the match history pages includes:

  • player positions every minute
  • totalTimeCrowdControlDealt
  • 10 minute averages for player performance: CS, gold, etc
  • 1 minute reports on player XP, CS, etc. (gold is currently visualized)

Top level match object:
Metadata about the game. Game type, map, server version, etc.

Teams
some top level stats on team aggregate performance. Very little data, but does have bans.

participantIdentities
summoner id, name, link to match history. This object exists but contains no data for non-ranked games. (No matter whether my API token account is friends with the player or not.)

Participants
Champion, Summoner spells, Masteries, Runes
Explicitly not any identity info other than “highest achieved season tier”.

> Stats
Detailed per-player info on whole match. level, KDA, items, etc
Unvisualized stuff:
double kills, penta kills, unrealKills, killing spree
various “scores”, all set to 0
first tower, first inhib
totalTimeCrowdControlDealt

> Timeline
None of this data is visualized by Match History.
Contains Role and Lane
Also contains average stats every 10 minutes for creeps, xp, gold, csDiff, xpDiff, damageTaken, damageTakenDiff

Timeline
Timestamped frames every 60 seconds

> participant frames
unvisualized: player position, level, XP, CS.
visualized: player gold

> events
timestamped events like item purchases, skill ups, wards placed, etc. some events like champion kills contain positions. (sadly, not wards.)

Riot’s League of Legends API and match privacy

I’ve been dorking around with the Riot API, for League of Legends. They’ve done a remarkably good job on it, particularly for a game company. The API product, the docs and developer registration and stuff, is well executed. (I say this as someone with some personal expertise.) And they are providing a huge amount of data, particularly detailed info on specific matches.

Here’s an example visualization of a match, from Riot’s own web product. All the data behind that match history view is also available in JSON form.

Anyway, one specific question is how to find matches. There’s two methods for looking up matches. The old /game API returns all matches for a given summoner ID (ie, a player). And the newer /matchhistory API returns all matches for a given summoner ID, but only ranked matches. Riot has said repeatedly that they think of ranked matches as public data and will always make that info available to anyone. But that other matches are casual and should be private. OTOH they haven’t implemented that yet, at least not entirely. Here’s the state of things today AFAICT

  1. Ranked game data is entirely public, including summoner identity
  2. Other game data is entirely public too, but does not include summoner identity except...
  3. You can see summoner identity for all games played by friends of yours and...
  4. Your Riot API developer token acts as you, and thus you can see identities of friends.

These principles apply to both the /game and /matchhistory APIs for “find me games from this person”. But they also apply to the very detailed match data returned by /match. They will return a lot of detailed data for any game, even a custom ARAM (as casual as it gets). However if you’re not friends with a player it won’t show you their summoner details. Ie: the game is anonymous.

At least, I think that’s how it works. I should confirm more.

They keep saying they’re going to disable the old /game API. That will make it more difficult to find match IDs for non-ranked games. OTOH they’ve been saying they’re going to do that for a year now and haven’t.

Update: the bit about seeing data for friends may only be true for the old /game API. It seems not to be true for specific match data returned by /match.

Temperature vs time

Funny graph from my computer in a Kansas datacenter. Something changed there and the temperature has dropped 4°C over 12 hours. And just at the same time, the phase-lock loop that NTP uses to sync time with the kernel goes off. The error isn’t big, at most 8ms, but it’s amusing.

sensors_temp-day ntp_kernel_pll_off-day ntp_offset-day

Database IDs should not be integers

It always bugged me that standard databases use integers as IDs. Not just databases: all sorts of systems, anything with a notion of identity ends up with an “id” token, and the type of that token is almost always “integer”.

The problem is that “integer” has a lot of baggage. An integer is something you can do arithmetic on. It makes no sense to divide one id by another, or add two ids together, or do almost any other arithmetic operation on. The one exception is adding one to an id, as in an autoincrement column for the primary key. But even that’s really a mistake a lot of the time, because those IDs have a way of leaking to the public in URLs and JSON blobs. I can’t tell you how many sites you can estimate growth on by just looking at message IDs or customer IDs or whatever.

My ideal world would be to have a separate “id” type in SQL which has very few operations defined on it. That’s boiling the ocean though. A close second is just to use “text” or maybe “blob” as the ID type. But in practice that doesn’t really work very well. It ends up using more storage even if it shouldn’t have to. And I have to believe indexing and searching text columns is in practice more expensive than integer columns.

So integer it is. Why fight it?

Wanted: SQLite for JSON

I like SQLite. It’s such a nice simple data store. It’s fast for small data (< 100 MB), it requires no separate daemon process, it has great support in every language I work in.

I like JSON and the idea of schemaless databases. I want to be able to download JSON blobs from an API or create some new JSON blobs and store them away with a minimum of effort. Typeless. Then I want to be able to query them somehow.

Now I want to mix the two together. I want to take a bunch of JSON objects and store them in somewhere simple, then query them.

MongoDB was the first big “store a bunch of JSON”. It sort of fits the bill for what I want, but it’s way overengineered for my needs. I don’t want a separate database process. I definitely don’t want a separate cluster of database processes. Also MongoDB is fundamentally untrustworthy and should not be used by anyone for anything serious. It might be OK for my casual hacking, particularly without clustering, but then you run into the way the query language is so awkward.

Postgres has decent JSON support with some queries. I will probably try that for my next hack. Unfortunately it requires a separate database process and I prefer the simplicity of sqlite’s “just open the file” design. But I have a Postgres instance lying around already so what’s one more database?

PostGIS: intersections, multiple SRIDs

Someone asked me to give them a map of all the rivers in the state of Ohio. Sounded like a fun PostGIS exercise for me. Unfortunately I’ve made it more complex because my river database is in SRID 900913 by default, so intersecting that with the Natural Earth admin1 data in a different SRID is not as simple as a one line query. I could just transform Natural Earth on import but ogr2ogr pretends to not know 900913 and that seemed bogus anyway. Some notes from my goofing around:

-- state boundary data is in EPSG:4326
# select ST_SRID(wkb_geometry) from admin1 limit 1;
4326

-- Coerce the test point to the SRID that the state boundary data is in
# select name from admin1 
  where ST_Intersects(wkb_geometry, 
                      ST_Transform(ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'), 4326));
Ohio

-- try querying with a point inside Ohio but with mismatching SRIDs
# select name from admin1
  where ST_Intersects(wkb_geometry,
                      ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'));
ERROR:  Operation on mixed SRID geometries

-- Coerce the test point to 900913, which should not work.
-- Bafflingly does not give an error for mixed SRIDs, just returns 0 rows
# select name from admin1
  where ST_Intersects(wkb_geometry,
                      ST_Transform(ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'), 900913));
(0 rows)

-- Coerce the state boundary geometry to the test point's SRID
# select name from admin1 
  where ST_Intersects(ST_Transform(wkb_geometry, 4269),
                      ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'));
Ohio

Home Internet device proliferation

I have 31 devices with IP addresses in my house right now. 4 computers, a printer, a game console, a router. These I expect. But also 6 Sonos music players, 3 Roku video players, 3 DirecTV boxes, 3 TV displays, and a couple of iPhones and an iPad and a Kindle. And several other devices on my network I can’t readily identify. I’m a geek who collects gadgets, sure, but I don’t think I am particularly extraordinary in that. This proliferation of devices presents several problems.

The first problem is basic network management. The only reason I know this count is I’m enough of a geek that I know how to find my router status page. Some routers I’ve seen only assign 32 IP addresses in total, I wonder how many households hit that limit and have no way of knowing? How does anyone even know what is on their network?

The second problem is tracking down problem devices. For me this usually shows up as “something’s using all the fucking bandwidth” on my slow 1MBps connection. So I look at the router IP traffic display to find the problem IP address. Then the question is, what is the device? If I’m lucky the device asked for a name when registering via DHCP; the name “DIRECTV-H25-9B3FDEB9” is a pretty good clue, and I’ve learned “NP-1GH314015312” actually means “Roku”. Sometimes the MAC address is a clue; you can look up the first 3 bytes to find the vendor. But knowing an ethernet interface was built by “Hon Hai Precision Ind. Co.” isn’t that helpful. Google tells me that’s Foxconn, still not helpful, it took something else that made me realize that was really my Playstation 4. My Kindle shows up with a prefix E0:CB:1D which is “private”, completely useless for identification.

So then I have to get clever to find the device. nmap’s TCP fingerprinting is helpful for figuring out what OS that IP address is running. For the Playstation that showed that it was FreeBSD, and I vaguely remembered that Sony bizarrely used FreeBSD for its OS and that helped me track it down. nmap can’t detect the Kindle OS via TCP fingerprints. For that device I was left with wireless signal strength in my router display. I guessed maybe it was the Kindle by the time it registered for DHCP then physically carried the Kindle nearer to the router to determine the mystery IP address’ signal strength got stronger. Ridiculous.

The third problem is some devices can’t be trusted with Internet access. My Samsung TV displays are in that category, their SmartHub SmartTV crap. Actually in theory I like the idea of it and the Netflix client etc aren’t bad. But there’s lots of reason to be worried about the security exposure of TV firmware. Also the UI is terrible. Samsung thinks the best time to pop up a “do you want to update?” dialog is right when you turn the TV on after dinner and are about to watch a movie. Consumers can’t even meaningfully answer that question; why ask it of them in the most intrusive possible way? Anyway, I decided the TVs didn’t need Internet access anymore. Not easy to disable. For the wired TVs it was enough to unplug the ethernet, but for the wireless ones the OS lacks any way to forget a network. Fortunately I could tell it to use a new bogus SSID and it was literal enough to accept the broken network even though it knew about a working one.

IPython and inline matplotlib

I’m trying out IPython. I’m also playing around with machine learning which means I need some simple data visualization, so I’m playing around with matplotlib. Here’s how to display generated plots inline (as opposed to in a popup window); the docs are inconsistent.

QT: ipython qtconsole --matplotlib inline

Notebook: launch with “ipython notebook”, then run “%matplotlib inline” in a notebook.

Here’s a sample program that generates and shows a plot:

from matplotlib import pyplot as plt
years = range(1950, 2020, 10)
gdp = [300, 543, 1075, 2862, 5979, 10289, 14958]
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
plt.show()

Roku Twitch: variable bandwidth usage

The Roku got a new official Twitch client recently. It has a remarkably neat trick: variable adjustment of bandwidth usage while playing a stream without interruption. I’ll be watching the stream in what looks to be 480p quality. Then it drops to lower quality: 360p, or 240p, or even the impressionistic smeary stream for mobile devices. Then it pops back up to 480p when it can. All the while playback is uninterrupted. Crucially the audio never cuts out or skips, so the overall viewing experience is remarkably smooth.

Here’s a bandwidth graph of 10 minutes of me watching RiotGames’ official LCS channel yesterday.

Roku Twitch bandwidth graph

My network is capable of 2600 kbits/sec but only for a burst of ~30 seconds. Then I’m throttled back to 1024 kbps for awhile. Here you can see the stream is mostly consuming about 1000 kbps but occasionally enjoys the burst up to 1500 and once even dropped down to 660 or so. All the time that was happening my playback was quite smooth and solid, the only indication anything was going on was that the graphics got a bit fuzzy sometimes.

Most video streaming apps online seem to have one HTTP stream for each quality of video, and once you start streaming it you’re committed to that bitrate. The Twitch app must be doing something smarter about grabbing a few seconds of stream at a time and dynamically altering the bitrate depending on measured bandwidth. That may explain the 3s buffering time before the stream plays, too. I’ll gladly take that tradeoff.

In the long long ago of the early 00s Internet, video streaming was dominated by RealMedia’s proprietary protocol. That was UDP, so packet loss could be handled by the app. And it was a progressive codec. I think Twitch is doing TCP and not a progressive codec, so it’s more like it’s just dynamically altering which stream it asks for on the fly. Seems to work pretty well.

(BTW, Twitch is still coy about publishing details on video quality and bitrates. Their’ partners page has some samples though, which claims

  • 240p: 384kbps
  • 360p: 512kbps
  • 480p: 768kbps
  • 720p: 1161kbps
  • 1080p: 1500kbps

I’m suspicious of the correctness of these numbers. They’re too low, also too much like round numbers except 720p. Maybe the numbers are video only and they’re doing transcoding to exactly hit a video bitrate? Seems unlikely.)

Leap second fallout

I looked for evidence of major leap second bugs and didn’t find many. The big news was AWS went down around 30 minutes after the leap second, but that turned out to be an improperly published route, not directly a leap second thing.

But DynResearch published a great graph of BGP route instability around that time, a 15x increase in BGP advertisements over normal.

Leap second BGP spike

I wonder what the cause of that was and whether it caused any problems for civilians. My guess is that it is related to dynamic load balancing algorithms assuming a day only has 86,400 seconds.

More info in this article, which also notes that 2000 networks stopped working briefly.

Leap second 2015

Both my Mac and my Linux box seem to have survived the leap second, at least so far. Both systems just reported 23:59:59 taking two seconds. A friend with a MacOS 10.10 box says he saw 00:00:00 briefly. I saw that in 2012, and it’s a serious bug (the date flips too!) but didn’t today.

while :; do date; sleep 0.1; done

A screenshot from this Javascript viewer. (Which has a fun easter egg; the clock started running backwards after this image.)

23:59:60

League of Legends bandwidth usage increasing

I pulled some new stats out of Logs of Lag, the average bandwidth used by the game client. Each point is the average for all logs I have for the week. It shows that the client has roughly doubled its bandwidth usage over the past three years.

LoL bandwidth usage

The absolute usage is still very small; well under 50kbps, or the speed of good ol’ dialup. (Burst usage is significantly higher though, maybe 4x.) Mostly I find the trend interesting. Also surprised not to see a clear step function as patches are released, although maybe that pattern is hiding in the data.

As with my previous analysis the huge caveat with these reports is that I don’t have an unbiased sample of LoL players. I only have logs  uploaded to me by Logs of Lag users, which are undoubtedly biased towards people with network troubles. I think that bias won’t skew this bandwidth usage number much though, it has much more impact on any inferences I can draw about player ping times, packet loss, etc.

Speaking of those skewed data, here’s an update from last fall’s summary with significantly more sample logs now.

matchLength = 1736.0  (29 minutes)
bestPing = 80ms
medianPing = 90ms
averagePing = 103ms
stdDevPing = 53ms
bytespsIn = 4706 bytes/s
bytespsOut = 666. bytes/s
lostPerMin = 11.5 packets/minute

Running mocha tests

Dusting off some old Javascript, I’d forgotten how to run my Mocha / Chai test suite. Running “mocha” in the main directory is the basic thing, it finds tests in a subdirectory named “test”. The nice way to run it continuously is

mocha -w -R min

SmartTVs

I just bought a new TV. They are now plagued with a huge number of “smart” features you have to turn off to make the set useful. You pretty much can’t buy a TV without these.

First off is all the video processing. The motion interpolation / dejudder / etc that takes a lovely mastered Blu-Ray source and then makes it look like shit and 100ms out of sync with the audio. Fortunately TVs generally have a “game mode”, so-called because gamers want low latency displays. As a side effect it disables all the video processing.

Then there’s the Smart TV stuff. I’ve been buying Samsung TVs and watching their apps evolve. It’s not bad; you can legitimately watch Netflix or (probably) Youtube entirely on your TV now. Only problem is that there’s no simple way to get sound back out of the TV and in to your nice wall-mounted surround sound speakers. So all this smart TV stuff is useless unless you want to listen to 5W of shitty stereo. (Not strictly true; there’s a new HDMI 1.4 standard called ARC that does feed audio back up the cable.)

The Smart TV stuff is a little useful if you really just want a simple TV to watch movies in the kitchen. But for anyone who is at least a little serious about home theater, it’s useless. Worse than useless. Because now your TV has an operating system. So it takes a long time to boot, is vulnerable to security holes, and is popping up features and notifications when you don’t want them. I was particularly charmed to see this year’s Samsung TV includes a virus scanner. In the display. Awesome.

There used to be a class of flat panel displays called “monitors” that were really just a screen; no speakers, no “smart TV”, no bullshit. Unfortunately that market segment is gone. My suspicion is that the TV manufacturers are hoping to one day capture customers and turn them in to Internet service subscribers, so that they make more money than just selling the fancy glass panel. Ugh.

Bonus link: simple TV feature comparison matrix. Samsung’s marketing literature makes it impossible to understand what you are actually buying. What’s the difference between a JU6500 vs a JS8500? About $1000, but their web site does a terrible job informing you what that $1000 buys. This third party site has a simple feature matrix. May they make many dollars in Amazon referral fees.

Addendum

XKCD #463

discoveryd vs mDNSresponder

Good news; Apple is jettisoning the broken terrible discoveryd from MacOS and going back to good ol’ mDNSresponder. Not that I have any love for that stuff either, why can’t MacOS just use the same things the BSD and Linux crowd use? Why reinvent NAT port forwarding requests, etc? Anyway, at least they recognize their mistake in switching to a new broken version of the thing,

Back from January, here’s a good description of what these daemons do. Basically it’s ypbind for a modern age, once again trying to solve the problem of resolving names to addresses in various dynamic environments.

SVG rivers

A bunch of artists all recently have been asking me for scalable vector versions of my river map. A very reasonable request, given the data is natively vector, but all my renderers have been browser-based pixel things. Fortunately the underlying rendering is done with D3, which creates SVG in the browser. So how to save it?

Saving SVG

The simple answer is the SVG Crowbar Chrome bookmarklet. This lets you take, in essence, a screenshot of what’s in your browser but in SVG vector form. I think it’s basically copying and pasting the SVG out of the DOM, but it’s got some cleverness about keeping stylesheets too.

The real answer is some proper SVG writing code. No one seems to have ever really done this in D3 nicely, I think you still need something like the Downloadify Flash shim to enable the browser to write the file. (The very newest version of Chrome does have a file writer, but it’s part of the Mozilla work on editable web pages and seems weird.)

Another proper answer is to bypass the browser entirely and write a Node headless program to create the SVG and write it. I gather JSDOM is the library of choice for a browser-like DOM environment in Node, worth a try.

Resolution

Unfortunately I don’t know much about working with SVG. Everyone wants to edit in Illustrator but I don’t know or own Illustrator. I’m told my SVG Crowbar files do load in Illustrator, so I guess that’s good. They do work in Inkscape too but I don’t know Inkscape very well and it’s pretty clunky.

Anyway, my SVG question is about scale. I’m used to tuning the way things look for pixels. For instance, for river maps for rivers of Strahler 1-10 it looks good if the line width is about strahler/2.0 pixels wide and I render the US to about 2000x1000 pixels. That’s what I did in the one goofy raster image that got Internet famous.

But pixels are lame. What if someone wants to print to a 20′ wide mold for a sculpture? (This is actually happening!) Or make a fine letterpress print (also, happening!) I’m hoping for now the Illustrator jocks can just scale the line width, etc as they need, but I don’t know what’s right.

Resolution independence also raises questions about coordinate rounding, and simplification thresholds, and other details.

Nest thermostat hacking

I got a Nest thermostat a few months ago. I mostly like it, even if it is a bit overdesigned, it’s a lovely product. But a few days ago the battery stopped charging. Turns out charging is complicated on these things; it’s trying to vampire off the furnace control lines. Mine report to be running at about 35V, 20mA. That’s less than a Watt of power, not a huge amount, although it’s been enough so far and Nest tells me it should be sufficient.

Anyway, the diagnostics on the unit for battery charging are not very good. But the Nest helpfully uploads its battery state every few minutes, at least if it has enough battery charge to do that. Unhelpfully the webapp doesn’t show battery history. So I have to make my own.

I ended up using python-nest and writing a simple script to get the battery state.

import nest
username = 'nelson@monkey.org'
password = file('password').read().strip()
with nest.Nest(username, password) as napi:
    for structure in napi.structures:
        for device in structure.devices:
            target = device.target
            temperature = device.temperature
            ts = device._device['$timestamp']
            battery = device._device['battery_level']
            print "%.3f,%.3f,%.1f,%.1f" % (ts/1000.0, battery, temperature, target)

Boy that Python Nest API is funky. And undocumented. I have no idea what a “structure” is supposed to mean. The object doesn’t really exist until you query it with the iterator protocol and it lazily makes an HTTP request. Once it does I think you can also access it as an array, but not before. Then there’s the device which you access with properties, but that only has some data, the battery level is hidden in the device._device object which you access as a hash table. And while the command line tool can print whether the heat is actually running at the moment or not I never could find that in the data structures. At least I got my battery recording.

The Internet of Things enables whole new worlds of yak shaving.

bash: $@ vs “$@”

Brad Fitz’s tweet about how bash treats $@ vs “$@” had me curious. The man page explanation is confusing but indicates these are different.

When the expansion occurs within double quotes, each parameter expands to a separate word. That is, “$@” is equivalent to “$1” “$2”

So what does this mean in practice? Some code:

#!/usr/bin/python
"Print out how many command line arguments there are"
import sys
print "%d %r" % (len(sys.argv)-1, sys.argv[1:])
#!/bin/bash
echo With Quotes
./printargs.py "$@"

echo Without Quotes
./printargs.py $@
$ ./quote.sh foo "bar baz"
With Quotes
2 ['foo', 'bar baz']
Without Quotes
3 ['foo', 'bar', 'baz']

To me the quoted “$@” does what I expect; do its best to pass the arguments along verbatim, as the shell script was invoked. That rewards some advice I learned 20 years ago to just always quote “$@” in shell scripts and the right thing would happen. But if I think about it harder I get confused. For matters of shell quoting and expansion, best not to think too hard.

Update: interesting tweet from Eric Fischer

the problem is that “$@” is “” when there are no args. Magic ${1+”$@”} is “$@” when $#>0, nothing when 0

Rant: why is the Chrome Web Store so awful?

I accept that Google has locked down Chrome extensions and made them hard to install from anywhere other than their own store. Security issue (also, vendor lock-in). But why does the store have to be so awful?

Chrome App Store

The thing I want, the extension I clicked on, is there. In the middle in a 980x700 box. That is the web page I requested. Why is it locked inside a tiny frame with some slightly faded out ugly set of icons beneath it?

Why is the URL for the extension cepmakjlanepojocakadfpohnhhalfol instead of some human readable name?

Why is the 980x700 box so badly laid out? The top gutter is too small compared to the left and right gutters, and there’s no bottom gutter at all, just more ads for other products I don’t want. And so much of the box is given over to a screenshot. I appreciate wanting to demo the wares, but often screenshots are not the best way to understand what a Chrome extension does. There’s so little room left for the text! And screenshots can be so visually noisy they look hideous embedded in the rest of the tiny box inside the app store page, like this one.

The navigation is also funky; clicking tabs like “reviews’ does some Web 2.1 trick where the content and URL change but the page doesn’t actually navigate. This part works reasonably well, it’s certainly faster than reloads, but it reinforces how this thing is not really a web page but a bad app trapped inside a browser, on top of a blurred out version of a store I do not want to shop at.

In the long long ago the Chrome app store had a much nicer simple page per extension. They changed it a couple of years back and I assumed they’d swiftly recognize their mistake.

Installing openaddress-machine on a new EC2 system using Chef

No need to install stuff manually; Mike already wrapped up scripts to set up an EC2 system with Chef for us. Here’s how to use it on a brand new EC2 micro server

sudo bash
apt-get update
apt-get upgrade
apt-get install git
git clone https://github.com/openaddresses/machine.git
cd machine/chef
./run.sh

Done! The shell command openaddr-process-one now works and does stuff.

In brief, this:

  1. installs Chef and Ruby via apt
  2. runs a Python setup recipe. That installs a few Ubuntu Python packages with apt (including GDAL and Cairo), then does a “pip install” in the OpenAddress machine directory. This tells pip to install a bunch of other Python stuff we use.
  3. runs a recipe for OpenAddresses. This uses git to put the source JSON data files in /var/opt.

Update

But really, that’s so manual. If you just pip install openaddr-machine it makes a /usr/local/bin/openaddr-ec2-run script that will do the work for you. That in turn invokes a run.py script which you run on your local machine. It, among other things, runs a templated shell script to set up an EC2 instance and run the job on it.

The shell script that is run on EC2 is pretty basic. It:

  1. Updates apt (but does not upgrade)
  2. Installs git and apache2
  3. clones the openaddress-machine repo into /tmp/machine
  4. Runs scripts to setup swap on the machine, then invoke chef to set up the machine
  5. Runs openaddr-process to do the job
  6. Shuts the machine down.

The run.py script you use on your own machine is mostly about getting an EC2 instance.

  1. De-template the shell script and put it in user_data.
  2. Use boto.ec2 to bid on a spot instance
  3. Wait for up to 12 hours until we get our instance

The details of how the EC2 instance is bid for, created, and waited on are a bit funky but seem well contained.

Installing openaddresses-machine on a new EC2 instance

Just documenting some work I done. The pattern here follows my notes on making openaddresses work in virtualenv, although I didn’t use venv here. This is really how to get the minimal stuff installed on a new Ubuntu box to run our code. Just a bunch of shell commands.

Set up an Ubuntu 14.04 AMI. The smallest one will run it OK

Do the following as root:

# update  ubuntu
apt-get update
apt-get upgrade

# install pip
cd /tmp
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

# install gcc and python dev
apt-get install gcc g++ python-dev

# install openaddresses
pip install Openaddresses-Machine

# install Cairo
apt-get install libffi-dev libcairo2
pip install cairocffi

# install GDAL
apt-add-repository ppa:ubuntugis/ubuntugis-unstable
apt-get update
apt-get install python-gdal libgdal-dev
pip install GDAL

I haven’t run these commands a second time yet, but it should be close. The last line for “pip install GDAL” is probably not necessary, and it’d probably be better to install Openaddresses-Machine last although it may not matter.

Next step: automate this with Chef Solo.

After that: set up Honcho and a Procfile to run my queue service worker.

Ubuntu guest VM frustrations

I’m trying to set up Ubuntu in a virtual machine. My goal is to recreate locally an environment a little like I might get from Amazon EC2, so I can do rapid testing of deploy scripts. I don’t need an exact Amazon AMI, but a clean Ubuntu image is close enough I can get stuff working before dealing with a remote environment.

I’ve got a VM host running. It’s Ubuntu 14.04 running KVM. Seems to work.

I’ve previously gotten Ubuntu’s new Snappy working as a guest. It boots fine and I can access ports. Unfortunately this environment is a strange Ubuntu 15, which has replaced apt with the “snappy” tool. Not enough like an EC2 host to be useful.

I tried using an Ubuntu Cloud image as a guest. They ship 14.04. But it doesn’t boot cleanly:

2015-05-03 18:25:26,540 - url_helper.py[WARNING]: Calling 'http://169.254.169.254/2009-04-04/meta-data/instance-id' failed [119/120s]: request error [(&lt;urllib3.connectionpool.HTTPConnectionPool object at 0x7f0f325e58d0&gt;, 'Connection to 169.254.169.254 timed out. (connect timeout=17.0)')]
2015-05-03 18:25:27,542 - DataSourceEc2.py[CRITICAL]: Giving up on md from ['http://169.254.169.254/2009-04-04/meta-data/instance-id'] after 120 seconds
2015-05-03 18:25:27,550 - url_helper.py[WARNING]: Calling 'http://10.0.2.2//latest/meta-data/instance-id' failed [0/120s]: bad status code [404] [404]

The init scripts are waiting on some network resources to load. The IP addresses are on the local network, and I guess it’s some sort of Ubuntu cloud server configuration thing. I don’t want all that! I just want a basic Ubuntu unmanaged instance to boot. Unfortunately ssh is still refusing logins. It does finally give up but it takes about 4 minutes, way too long for the rapid iteration I have in mind. And then I can’t log in. Apparently there is no default password. This image is really not designed for the quick and dirty hackery I want.

I did learn something about how QEMU/KVM’s networking stuff works. The default IP is provided by slirp, which among other limitations does not support ICMP. So that’s why ping doesn’t work! Also it’s outbound connections only, although the “-redir” flag to kvm seems to offer some basic port forwarding.

I found this guide to using libvirt sort of interesting, it’s simple stuff for managing the virtual machine image. Although again way overkill for what I want.

At this point I think I’m going to give up on running my own KVM guests and hope that EC2 gives me a new machine fast enough that testing machine setup scripts using throwaway instances isn’t too annoying.

Update: my friend Jeff says that I should look at ubuntu-vm-builder. It will apparently make me an image. I sure would be glad to just download one someone made already though.

postgres: setting up permissions for a user

I wanted to give a CGI script access to one specific postgres database, both read and write. This is remarkably complicated. I ended up creating a password protected role named “oarunone” and gave it access to a database named “oarunone” (yes, confusing) and one table named “queue”. Something like:

  • create role oarunone with password ‘secret’;
  • grant all privileges on database oarunone to oarunone
  • grant all privileges on table queue to oarunone

But that’s not good enough. Ubuntu’s default postgres only identifies users via the Unix UID. So you also have to add a line like this to pg_hba.conf. and it has to occur before the catch-all “all” rule.

  • local oarunone oarunone md5

That says allow the role “oarunone” to authenticate with a password (MD5ed), but only from a local Unix domain socket and only to the database “oarunone”.

OpenAddress machine continuous queue

Migurski and I have been working up a new architecture for OpenAddresses, specifically the python code that runs source jobs. Currently everything runs as a big batch job every two days. The primary goal is to get a system that can run a new submitted source instantly, ideally with useful feedback to the submitter.

Mike’s insight was to build a system a little like Travis; something that looks at GitHub commits with a hook, runs a new job every time something is committed, and posts back info via the GitHub status API. GitHub is nice because it provides a file store and change tracking. Ultimately we don’t want to require a GitHub login to submit sources, and we probably want a custom UI, but that can come later.

Here’s the components we’re talking about building:

  1. A GitHub webhook that submits info to our new job server when stuff is checked in.
  2. A new job server that accepts HTTP posts of GitHub events. Mike’s got one working in Flask running on Heroku.
  3. A job queue. New jobs get enqueued by the new job server, then some worker daemon process checks for jobs to run and executes them. Can be a very simple queue, but needs to support job priorities (interactive vs. batch). Right now I’m thinking of writing my own using Postgres running in Amazon RDS, but there’s got to be something I can just use that’s not super overkill. (Update: pq looks good.)
  4. Workers to run jobs. Something to look for new jobs and execute them. Current thought is a persistent Unix server running on EC2. Installs openaddr and its dependencies via pip, then runs jobs via openaddr-process-one, then posts results back to the job queue result queue.
  5. Job completion notifications back to GitHub using the GitHub status API. Mike has been tinkering with code to do this already.
  6. A batch-mode refresher. Something to run sources periodically even if no one’s edited the source specification in awhile. Mostly to catch new data on the remote server.

Here’s some open things to design.

  1. Job status reporting with humane UI. Currently we get very little info back from when a job is run. A few bits of status (did it complete, how long it took), a debug log from the process, and any actual output files. We need more. In particular I think the stuff you currently learn from the debug log needs to be expanded to useful user-level event data. Ie, events like “source JSON parsed”, “source data downloaded”, etc.
  2. UI for creating source specification JSON files. Imagining some guided wizard like UI using Javascript and forms. There’s already a pretty good one on the live site, just needs some expansion. Also ultimately we shouldn’t require a GitHub login.
  3. Security. A bit nervous running completely unreviewed source specs from anonymous people. Isolating the worker in a throwaway machine might help. Or doing some sanitization on inputs.
  4. Statistics reporting. I have a dashboard that works OK for the existing nightly batch mode, but we’ll want something different for this continuous mode thing.

See also OpenAddresses Mark 3, a proposal I sketched in January. What we’re doing here is similar but without the component of breaking any individual source run up into separate tasks.

Cyberduck is responsible for my bad SSL certificate

I figured out what put the rogue SSL certificate on my system, the one that breaks MacOS Mavericks. It came back yesterday 2015-04-27 between 15:38:32 and 16:41:02. The system Console helped me narrow it down to the application Cyberduck, version 4.6.3. I use it sporadically to browse S3 buckets. It’s just the right kind of unusual application that would cause a bug like this that some small group of users on the Internet finds but not everyone.

Cyberduck 4.6.3 placed a bunch of errors in the console, including the smoking gun “4/27/15 3:42:05.621 PM Cyberduck[54126]: Error adding certificate to Keychain”. I also manually verified the login keychain entries show up again as soon as I run Cyberduck after deleting them. (For completeness I should add Cyberduck also complains about an SSL hostname mismatch when connecting to S3, but I think that’s a legitimate and expected error and unrelated to the Verisign certs.)

Version 4.7 (17432) is the latest version of Cyberduck. It doesn’t cause the problem any more. There was a reported and fixed bug in Cyberduck. I’m not sure the Cyberduck authors understand the magnitude of the problem though, or that users of old versions now have broken Macs. We now have a bug report on file, my report text below.

I also don’t understand the root cause of the problem. Cyberduck says they were taking a certificate offered by the server; Amazon S3, in this case. Were they verifying it was a valid cert first? If so, then why is it no longer a valid cert? And why did MacOS security update 2015-004 break it? I’m content to let that all remain a mystery, but I’m curious.

Update: this AWS discussion contains complaints about S3’s SSL certificate. Apparently it’s a key that is weakly signed and various software is deciding it’s no longer valid as they update to stricter requirements. That may explain why 2015-004 changed things.

For the search engines: one of the two bad certificates placed on my keychain by Cyberduck was “VeriSign Class 3 Public Primary Certification Authority – G5”

Bug report for Cyberduck

Prior to version 4.7, Cyberduck had code where it wrote some SSL certificates to the user login keychain. This behavior is documented in ticket #8741 and the code was changed to no longer do that.

However, the certificates old versions of Cyberduck wrote to the Keychain are now causing fairly serious problems with MacOS. Affected Macs can no longer verify Verisign-signed SSL certs in any application. Symptoms are the App Store refuses to load, MacOS software updates won’t get installed, Chrome refuses to load websites and Safari throws errors. It’s pretty bad. The problem seems to be triggered by Mavericks security update 2015-004 (released last week).

The fix is pretty simple: manually delete the spurious entries in the login keychain (so that the system entries are used instead). But users aren’t going to figure that out on their own. There’s no indication to the user there’s a problem with their keychain or that Cyberduck was the app that created the problematic entry. I only figured it out thanks to some lucky timing and a message on the system console.

While Cyberduck 4.7 no longer causes the problem, anyone who used an older version of Cyberduck may still have a broken Mac. Could Cyberduck do something to notify affected users? Maybe a new version of Cyberduck that checks for the bad entries and warns the user, pointing them to a help page?

It’d also be nice to figure out exactly what entries Cyberduck might have written. For me and a bunch of other users it’s two Verisign certs, one named “VeriSign Class 3 Public Primary Certification Authority – G5”. They seem to have come from Amazon S3.

Some references:

http://apple.stackexchange.com/questions/180570/invalid-certificate-after-security-update-2015-004-in-mavericks

https://discussions.apple.com/thread/6984765

https://trac.cyberduck.io/ticket/8741

https://nelsonslog.wordpress.com/2015/04/25/mavericks-security-update-2015-004-has-a-serious-ssl-bug/

inserting lots of data into a remote Postgres efficiently

Update 2017: psycopg2 now has fast execution helpers. Not sure why they didn’t just improve executemany.

I’m using a Postgres server in AWS in the us-east zone. My database client is running in California, so it’s about 150ms away. I do not expect this to be fast. However I don’t expect it to be super-slow either. Inserting 700 rows in a single transaction was taking 60 seconds. That’s absurd! (Rows are ~100 bytes each, this is not a lot of data).

Thanks to StackExchange I found a solution. Here’s some untested code that illustrates the idea:

# Clearly slow to insert one row at a time
for row in myData:
    cur.execute('insert into data values (%s,%s,%s)', row)

# Should be much faster, but isn't
cur.executemany('insert into data values (%s,%s,%s)', myData)

# This hack is much faster
dataText = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('insert into data values ' + dataText)

That funky last idiom basically expands all of myData into one giant SQL string with multiple values. For my use case, that 60 second operation went down to 1.5 seconds. This hack works, but you’re going to bump into a query size limit at some point.

Note that mogrify() isn’t doing anything clever, it’s just doing safe expansion of SQL query strings to avoid Little Bobby Tables. (There’s a Unicode error lurking here; I switched to Python2 just to make this work.) Also note that transactions don’t seem to be to blame here. psycopg2 by default runs a transaction for every connection; nothing commits until you call commit().

I think what’s going on is that psycopg2 doesn’t optimize the implementation of executemany(). Internally it’s just doing something like a loop calling execute() for each row. I don’t have proof of that, but my research turned up other people saying that was the problem. (See here)

(As an aside, what is it with database adapters for various languages that make them so universally bad? psycopg2 isn’t terrible, but it’s hardly joyful Python software. At least it’s better than the mess we had with mysql for so many years. Back in the Java days we used to have a terrible time trying to talk to MySQL as well.)

Cloud database prices

I’m looking at buying a hosted/managed Postgres in a cloud server. Amazon or Heroku.

Amazon RDS has a confusing array of pricing options. The smallest instance (db.t2.micro) is $0.018 / hour, or $13 / month if it’s always on. Data costs $0.115 / GB-month, so a 64GB database would be $7 / mo. Total cost for a smallish database: $20 / month.

Heroku Postgres has a very limited free tier. The hobbyist tier is $9 / month and gives you “10M rows” with who knows what performance. The basic standard tier starts at $50 / month for a 64 GB database. Hard to say for sure, but I think that’s roughly comparable to our $20 / month database on Amazon.

Of course what really matters for a service like this is price scaling, how easily you can add more performance and what you pay for it. I’m not worried about that for my small project, just good to have some ballpark numbers.

Scrolling vs headers and footers

More and more web pages have broken the page down key. Fixed-height headers and footers on top of web content don’t bother me, but the article underneath them never pages correctly. Because it’s paging the full window height and the header/footer has hidden part of the document, so you never see it.

This used to only be a problem on shitty websites that had all sorts of bad layout. But now even high design websites like the In Focus photojournalism gallery have broken the paging behavior with a header. Medium was a holdout for a long time, it even had a fancy thing where the header hid itself when you scrolled down a page. It still does that but now there’s a fixed 20px footer that obscures text that disappears when you page down.

What I’m wondering is why no one fixes this with Javascript. Maybe overriding paging behavior is difficult? I asked Marcin Wichary once about Medium and he said it was hard to make it work consistently in all browsers. There’s certainly ways to scroll the window and I imagine you can trap the page down key to invoke your custom scrolling code. Would be worth tinkering if it could be turned into an extension that worked for sites that don’t work right now.

Mavericks security update 2015-004 has a serious SSL bug

My Mac suddenly started throwing SSL errors when connecting to various sites, like search.twitter.com or support.apple.com. The App Store application refused to load content, too. Long story short, MacOS Mavericks 2015-004 has a bug where an incorrect certificate named “VeriSign Class 3 Public Primary Certification Authority - G5” is placed on the user’s login keychain. The fix is to run Keychain Access and remove it. Note: remove the one in the login keychain, not the System Roots.

Update 2: 2015-004 doesn’t put the entry on the login keychain, something else put it there earlier. 2015-004 does seem to change something though that triggers the verification problem. The fix is still to remove the key from the login keychain, I just don’t know what put it there in the first place.

Update 3: turns out it’s Cyberduck that’s writing the certificate entries.

This error seems really serious to me. Macs that are affected can’t get new software updates. Also Chrome will refuse to load any websites with SSL certs signed by that VeriSign certificate, including Apple’s own sites. Safari will load the site but will display SSL errors. Apparently Chrome is more strict in enforcing SSL security.

(I thought it was particularly interesting that it was impossible to get Chrome to visit Twitter. Twitter only serves HTTPS, not HTTP. And they have HSTS enabled which means Chrome will refuse to load a page without a working SSL certificate. Well that all succeeded, but boy was that a bad experience.)

Here’s some links with more discussion: Ask Different, Security StackExchange, Apple forums. I exported the two Verizon certs that were on my login keychain that were the problem, there’s a zip file here along with some screenshots of failed SSL certs. (That file won’t be online forever.)

I seem to be hitting a serious bug like this in MacOS every couple of months. Along with some broken-by-design things like their SMB client and I really am tempted to try going back to a Windows desktop. Or maybe Linux, if it weren’t so damn ugly.

Update 1: thanks to Ned’s suggestion in the comments I tried figuring out how those VeriSign certificates got in my keychain in the first place. I still don’t know, but looking at backups in Time Machine I can see it was placed there sometime between 2015-01-17 and 2015-02-23 13:48 (the two backups I have from before and after.)
$ grep -i verisign */Macintosh\ HD/Users/nelson/Library/Keychains/login.keychain

The Mac was turned off from 2015-01-08 until 2015-01-17 and again for 2015-01-21 until 2015-02-23. It seems likely the VeriSign entry ended up on my keychain when I turned the Mac back on. But it would have happened quickly; I entered the house at 13:42 and it’s in the keychain at 13:48. And my network is very slow. It could also have happened sometime between 2015-01-17 and 2015-01-21.

FWIW there’s a bunch of updates that installed a few hours after the keychain update, 2015-02-24 04:00 AM, including Security Update 2015-001 and Safari. But the keychain entry precedes those. Between 2015-01-17 and 2015-02-23 I only have a bunch of updates from “Google Voice and Video” and one from Seil, a keyboard kernel hack. Also FWIW I’m not given to manually tampering with my keychain nor blindly approving requests to manipulate it.

Complex QOS rules considered harmful

tl;dr: some router firmware has a catch-all rule that throttles all unidentified UDP traffic to 5% of bandwidth (labelled “Crawl”). This is a stupid rule, disable it.

I just fixed a bug in my router’s configuration that explained why Google QUIC was not working well for me. It may also explain bugs I’ve been seeing in League of Legends, OpenVPN, and other UDP protocols. I’m not entirely certain.

I’ve been running the Tomato v1.28 (Toastman) firmware for a year+ now. It’s an old build. It has 40+ default QoS rules identifying all sorts of protocols from important ones (DNS) to silly ones (RealAudio streaming), and then classifies traffic service level. Unfortunately some of the rules are harmful.

The problem rule in this case was the very last one. “UDP Dst Port: 1-65535, classify Crawl”. And Crawl by default is limited to maximum 5% of total bandwidth! There are a few higher priority rules that classify specific kinds of UDP traffic: DNS, for instance. But any new or unanticipated use of UDP is severely throttled. Such as QUIC, Google’s fancy new web protocol. And Cisco VPN. And maybe OpenVPN.

And maybe League of Legends; it’s a UDP protocol too, and hasn’t performed as well on my slow network as I expected. Just playing a game feels about the same, maybe a little less laggy, but there’s still the same unexpectedly high packet loss. But I think one reproducible bug is gone now. Jayce gates cause a brief surge of UDP packets; it used to be that caused significant lag even when playing alone. Now they don’t cause lag.

The simple fix is to adjust the Crawl class to also get up to 100% of bandwidth (both inbound and outbound). That may still have lower queue priority though. You can also try adding more rules for UDP protocols you care about; QUIC is on ports 80 and 443, for instance. But trying to label all known UDP protocols is a Sisyphean task.

I can’t imagine why anyone ever thought a 5% cap for default traffic was a good idea. Particularly for a UDP protocol which may not even be able to interpret those dropped packets as a signal to rate limit itself. Judging by the comment they were trying to catch unidentified BitTorrent traffic, which must have its own rate limiting. But still, what a dumb rule.

After several years of using QoS on home routers I’m of the opinion that QoS rules cause as much trouble as they fix. It’s certainly caused me a lot of problems. In a home network there’s no meaningful way to shape incoming traffic at all. You can shape the outgoing traffic a bit, and I think prioritizing ACK is probably a good idea. (Although weirdly this behavior is not the default). But in general the QoS implementations out there complicate things a lot and don’t provide a lot of value.

It’s time to go back and look at what the Bufferbloat guys have accomplished recently, and whether fq_codel or something similar has gotten traction. Their approach seems much simpler. Last I checked no Tomato variant supported it.

QUIC problem

Update 2: this was a bug in my router, not QUIC. See below, I also posted to the QUIC protocol group about it.

The Google is broken on my computer. This happened once before. Web sessions to every site on the Internet work fine except Google properties. Those hang for ~15 seconds for every web request in Chrome. Safari requests work fine.

Both times this has happened to me have been up in Grass Valley, the place with the shitty fixed wireless Internet. And both times when I’ve looked in Wireshark there’s some QUIC protocol stuff happening, I don’t know what. But my guess is that Chrome is deferring all requests to QUIC and they have a bug / bad interaction with my ISP where it doesn’t work right.

I could swear I once saw some QUIC diagnostic info inside Chrome. Or at least a way to disable QUIC entirely. Can’t find it now. Of course it’s hard to find things when Google doesn’t work. Edit: found the disable, it’s in chrome://flags. The statistics are in chrome://net-internals/#quic. The moment I disabled QUIC Google searches worked better. Interestingly, simply restarting Chrome didn’t help, at least not completely. I lack the patience to test this carefully, no point if no one’s going to pay attention to the result.

In desperation I’ve tried using Bing. It’s not as good as I remember. In the past I didn’t like the UI but the relevance was mostly good. But now the relevance is bad. They were returning URLs for RSS feeds on Metafilter for searches. WTF?

Update: I have a theory! It may be my router QoS settings. Tomato / Toastman 1.28 doesn’t have a rule for QUIC, but does have a default rule that all UDP traffic otherwise not classified is assigned the category “crawl”, which is limited to just 5% (40kbps) on my network. D’oh! I wonder if this also is responsible for my worse-than-expected League of Legends performance here. I added a rule for QUIC (UDP ports 80/443, classify WWW). Also raised the bandwidth cap on “Crawl” to 100% traffic, that was a dumb default rule. Now to try it out for a few hours...

Python3 zip() is a hassle

A Python3 annoyance; zip() now returns an Iterable, not a list. That means you can’t easily slice it.

In Python 2, this idiom for getting back the first column of a database query was useful:

cur.execute('select ...')
r = cur.fetchall()
firstColumn = zip(*r)[0]

In Python 3, this gives you an error

TypeError: 'zip' object is not subscriptable

The workaround is to wrap the zip in a tuple or list

r = cur.fetchall()
firstColumn = tuple(zip(*r))[0]

Annoying, but it doesn’t actually run any slower. I imagine you could use slice() or itertools.islice() to produce an iterator view of a slice of the zip iterator.

Mac fan control

My ~3.5 year old iMac is making noise. Just a small noise, but it’s high pitched and annoying. Something mechanic, presumably a fan bearing. So I started trying to isolate the source of noise. It isn’t the internal spinning drive, you can turn it off by unmounting all the volumes. I’m not using the optical drive. So maybe a fan?

The tool to test a Mac’s fans is smcFanControl, a simple tool to read the temperature and fan speed settings and alter fan speed. When you run it it requires root access, then goes into your menubar. You can set the minimum fan speed for each fan separately. It works pretty well. I used it to run each fan at full speed and crikey, my Mac sounds like a vacuum cleaner. Never heard those fans run before! Didn’t really notice a change in the sound but it’s hard to be sure. Maybe my optical drive fan is to blame. Unfortunately you can’t set turn the fans off entirely; the apps docs say this is possible but not enabled for safety. A quick search didn’t turn up any easy hacks, either.

On a side note, apparently there’s no good CPU/GPU/Memory burn-in tool for Macs. At least not a free one. The #1 suggestion from Google searches is “run yes > /dev/null”. Which, well, that works a tiny bit but it’s not even exercising the whole core of a single CPU, much less the whole system. There’s a bunch of good tools that run under Windows, too bad no one’s bothered to port one. The core load generator doesn’t need to change (much?) but the GUI is a problem.

Simple Javascript time series charts

I want to draw a time series graph in Javascript. This is one of the simplest kinds of regular data visualizations and all of the libraries I find to do it suck. I looked at this a year ago, is anything better now?

What I want is a library that will automatically assign axes and draw correct time series graphs. The time intervals are not regular. Also sometimes data is missing. Not zero, null. Remarkably, very few charting libraries seem to be able to handle these common requirements. Here is some very quick evaluation, I spent ~3 minutes on each library so may have mischaracterized something or overlooked some greatness.

  • Charts.js: too low level, really a graphics library for drawing colors in canvas
  • Flot: good ol’ flot, just seems too old. Maybe that’s foolish and it’s solid?
  • D3.js: great library but too low level. I don’t want to build my own axis and don’t really want to program at all, just declare data.
  • Metricsgraphics: promising library at the right level, but seemed buggy. I spent about 90 minutes trying to get a time series to render and depending on my Date range, either got a decent graph or got confusing SVG rendering errors involving NaN.
  • Rickshaw, xCharts, Ember, and d3.chart look to all have very slow or no development. Rickshaw was promising, I wonder if it’s just “mature”.
  • Dimple’s time series seems to assume equal spacing
  • NVD3 has been around a long time and is still active. It’s kind of a sloppy project though. The example code on the site doesn’t match what’s live. Some of the examples kill Google Chrome when run. There are no reference docs. I give up.
  • Vega looks too toolkitty and not enough libraryish. It frames itself as an analog to Protovis or D3, and I already know one of those. Also no time series example.
  • new TauCharts looks promising.

I need to investigate Highcharts. It’s not free software, but is free for non-commercial use.

dygraphs is sort of promising. It actually plots my data correctly but the default style is ugly. Also I’m not wild about canvas. It does a lot of fancy time series stuff out of the box though.

dygraph sample

Python3 est arrivé

I’m now using Python3 by default for all new projects. Almost entirely because I prefer sane Unicode handling. But really because Py3 has turned the corner and is now useful for most things. Probably it turned that corner a year or more ago, but it was the OpenAddresses work that made me start using Python 3 regularly. It helps that Homebrew and Debian both make it very easy to install ‘python3’ and ‘pip3’. And of course that most packages I care about are now ported over.

It took Python five years longer than I expected for the Py3 transition to get to this point. Let’s hope we don’t have to do it again.

Address schema

Some stuff of possible interest to OpenAddresses. The US government’s Federal Geographic Data Committee standardized street address schema. The docs are 140 pages of text describing an XML schema, which sure seems wordy, but then it’s also very precise. They even put the XML schema online, here’s a text rendering.

It’s super wordy and contains a lot of detail, but at the core is a schema we could repurpose that says things like “a street address consists of a number, a prefix, a street name, ...”

There’s a good summary of the schema on page 3 of the executive summary. Here’s the meat of it:

Screen Shot 2015-04-09 at 10.57.41 AM

MacOS security update only for Yosemite

Apple designed MacOS with an API that lets you escalate privileges from any user to root without proper authentication. No, really. This leads to CVE-2015-1130, details not yet published. It’s a pretty severe bug from the looks of it; not quite a remote exploit, but once an attacker can run code on your system they are root. Apple pushed a patch for it this week. But only to Yosemite.

The shape of the bug is really ugly too. It looks like Apple put in some weird backdoor API for stuff to escalate to root, so you can run Preferences or the like as a normal user. And they tried to lock that down in various ineffectual ways, like userspace binaries checking if they are running as root, but left the API in the kernel. Ugh.

installing openaddresses-machine in a virtualenv

Trying to get a server up running OpenAddresses in a controlled environment. I’m normally very sloppy and install everything as root in /usr, but I figured I should use virtualenv this time. Machine actually has a very nice Chef setup and bootstraps itself regularly in EC2 and Travis contexts, but I’m stubborn and doing it my own way.

Install openaddresses-machine and it’s simple dependencies

  • Prepare a virtualenv directory and activate it
  • pip install Openaddresses-Machine

Install cairocffi. This required a C library I didn’t have

  • sudo apt-get install libffi-dev
  • pip install cairocffi

Install Python GDAL. This is a mess; I’m not sure why the simple “pip install GDAL” doesn’t work from inside the virtualenv. And I’m not sure the instructions below are correct; it’s probably installing python-gdal globally on the system via and then again in the virtualenv via pip. But that gets all the C dependencies we need somewhere on the system. There’s extra rigamarole to get the bleeding edge GDAL instead of the stock Ubuntu GDAL. Also building GDAL requires a C++ compiler.

  • apt-get install software-properties-common
  • sudo apt-add-repository ppa:ubuntugis/ubuntugis-unstable
  • sudo apt-get update
  • sudo apt-get install python-gdal libgdal-dev
  • sudo apt-get install g++
  • pip install GDAL
  • PSYCH! That won’t work. Follow the instructions in this gist for how to manually configure and install gdal. Apparently its packaging is not compatible with pip?

Logging out of Google

Logging out of Google is a funny process; you get redirected to a bunch of sites one at a time, presumably clearing cookies in different domains. youtube.com, blogger.com, and of course google.com. Here’s the URL for google.com, broken down by CGI parameters

http://www.google.com/accounts/Logout2?ilo=1
ils=adwords,ah,cl,doritos,lso,mail,orkut,sierra,writely,o.mail.google.com,o.myaccount.google.com,s.blogger,blogger
ilc=1
continue=https%3A%2F%2Faccounts.google.com%2FServiceLogin
zx=-910194353

I find that chain of ils parameters interesting. It’s an odd set of properties, including some like Orkut for which I have no account. I wonder if it’s a list of Google services that maintain their own authentication tokens?

I’m having a problem where all Google services are super-slow for me, randomly. Not just Gmail but also even a Google search. Doesn’t happen in incognito mode. My theory was it was related to being logged-in, but logged out didn’t fix it. Being in an incognito window does fix it. Hrm. (Update: logging out does seem to have fixed it afterall, and now that I’m logged in again I’m fine. Perhaps my Google session got stuck on a broken server?)

Some OpenAddresses machine stats

I’ve collected the state.txt files written by OpenAddress machine and stuffed them in a database for ad hoc reporting. Here’s some queries and results

Slowest processing

select source, max(address_count), round(avg(process_time)) as time
from stats where address_count > 0
group by source order by time desc limit 10;

source                          max(addres  time
------------------------------  ----------  ----------
nl.json                         14846597    8769.0
au-victoria.json                3426983     8438.0
es-25830.json                   8778892     6450.0
us-va.json                      3504160     4377.0
dk.json                         3450853     4220.0
pl-mazowieckie.json             995946      4108.0
us-ny.json                      4229542     4047.0
pl-lodzkie.json                 685093      3575.0
pl-slaskie.json                 575596      3331.0
pl-malopolski.json              670892      3216.0

Slowest cache

source                          max(addres  time
------------------------------  ----------  ----------
us-ny.json                      4229542     5808.0
za-nl-ethekwini.json            478939      3617.0
us-va-city_of_chesapeake.json   99197       3457.0
us-ca-marin_county.json         104067      3034.0
us-mi-ottawa.json               109202      2232.0
us-fl-lee.json                  548264      1999.0
us-ne-lancaster.json            97859       1995.0
us-ia-linn.json                 95928       1519.0
dk.json                         3450853     1348.0
us-az-mesa.json                 331816      890.0

Summary of runs

For each run, print out how many sources we tried, how many cached, how many sampled, and how many processed. The counting here is a bit bogus but I think close.

select ts, count(distinct(source)), count(distinct(cache_url)), count(distinct(sample_url)), count(distinct(processed_url))
from stats group by ts;
ts               addresses        source  caches  sample  proces
---------------  ---------------  ------  ------  ------  ------
1420182459                        737     689     557     490
1420528178                        738     691     559     490
1420787323                        740     692     560     495
1421133148                        789     717     558     521
1421392045                        790     718     559     523
1421737732                        790     719     557     521
1421996867                        790     719     558     522
1422342479                        790     718     560     524
1422601615                        790     652     582     503
1422645440                        790     655     585     511
1422748762                        790     650     580     504
1422773454                        790     647     577     506
1422860989                        790     653     582     508
1423034051                        790     658     588     509
1423206384                        790     658     587     508
1423465798                        790     660     588     510
1423638409                        790     659     588     508
1423811369                        790     661     590     508
1424070358                        790     657     586     509
1424243321                        790     645     566     499
1424416039                        790     650     534     469
1424675318        88031206        790     648     563     496
1424849197       111999281        794     658     570     505
1425022188       105056481        794     653     570     508
1425280104       109864743        794     651     567     507
1425453036       111734276        786     655     573     520
1425625770       116323932        786     656     571     519
1425881358       113713353        786     644     563     528
1426054556       117771563        788     666     586     534
1426228915       117335107        788     666     584     538
1427090950       113916633        788     665     581     527

Time to complete successful runs

 select ts, round(avg(cache_time)) as cache, round(avg(process_time)) as process 
 from stats where length(processed_url) > 1 
 group by ts order by ts;
ts               cache            proces
---------------  ---------------  ------
1420182459       63.0             154.0
1420528178       50.0             147.0
1420787323       46.0             166.0
1421133148       43.0             159.0
1421392045       43.0             160.0
1421737732       43.0             163.0
1421996867       45.0             167.0
1422342479       46.0             164.0
1422601615       48.0             228.0
1422645440       56.0             314.0
1422748762       47.0             300.0
1422773454       50.0             289.0
1422860989       61.0             296.0
1423034051       66.0             263.0
1423206384       44.0             260.0
1423465798       51.0             294.0
1423638409       51.0             270.0
1423811369       50.0             260.0
1424070358       55.0             277.0
1424243321       60.0             265.0
1424416039       57.0             298.0
1424675318       51.0             265.0
1424849197       62.0             323.0
1425022188       53.0             284.0
1425280104       59.0             312.0
1425453036       55.0             325.0
1425625770       79.0             367.0
1425881358       77.0             315.0
1426054556       84.0             335.0
1426228915       76.0             361.0
1427090950       71.0             272.0

Most improved

A count of which sources have the most variance in how many address lines we got out. kinda bogus, but fun.

select source, max(address_count)-min(address_count) as diff, min(address_count) as minc, max(address_count) as maxc
from stats where address_count > 0 
group by source order by diff desc limit 15;

source                          diff        minc        maxc
------------------------------  ----------  ----------  ----------
us-mn-dakota.json               138301      27218       165519
us-pa-allegheny.json            53399       474492      527891
us-ne-lancaster.json            44996       52863       97859
us-va-salem.json                9992        614         10606
dk.json                         5258        3445595     3450853
be-flanders.json                2809        3365557     3368366
us-nc-mecklenburg.json          2117        499524      501641
us-co-larimer.json              1118        169500      170618
ca-on-hamilton.json             1112        243554      244666
us-va-james_city.json           1071        33383       34454
us-tx-austin.json               837         374854      375691
us-or-portland.json             786         415220      416006
us-nc-buncombe.json             784         147492      148276
us-nc-union.json                720         81241       81961
us-oh-williams.json             603         18496       19099

Bandwidth caps

My fast cable modem service comes with a data cap. I get an honest 100 Mbit/s, with a 300 Gbyte/month cap. Beyond that it costs $0.20 per gigabyte. I hate the idea of data caps although I sort of understand where the ISP is coming from. If I hit this cap every month I’d be angry, but so far I’ve usually come in far under. Not this month though; between the new PS4 and downloading a bunch of video I’m well over. 360GB and there’s 10 days to go.

Being over the cap has really changed how I think about the Internet. I’m now pricing stuff in my head. Watching a single LoL game broadcast will cost me $0.20. Watching a high quality movie on a stream will cost me $1.00. Do I really need to download a whole season of that TV show I might or might not watch? Maybe I can wait a few days, until April? Maybe I should put off some software updates too. I mean truthfully it’s not a lot of money, and I can certainly afford it, but knowing that I’m paying by the GB changes the way I think about it. (Related: this is why micropayments are a bad idea.)

I’m a bit confused about how my ISP calculates my usage. I also track usage via my router, and the GB usage numbers are wildly divergent.

Month    ISP    Router   Percentage
Jan      167    199       84%
Feb      160    148      108%
Mar      360    235      153%

I certainly understand why the numbers wouldn’t be exactly the same, but it’s been ±15% for the last two months. This month it’s +50%. I may ask about that when the month is over, although I’m pessimistic that customer service will give me a useful answer.

If I maxed my connection I could download about 30,000 GB a month; so my cap is 1% of max. My slow rural ISP has 1/100th the speed but the cap is 1/10th the size, so their cap is 0.1% of max.

NTP kibbitzing

This Metafilter discussion about the ntpd developer needing funding got me thinking more about NTP. I wrote a few comments on MeFi that have good content.

But the big revelation for me is NTimed, PHK’s project to write an ntpd replacement. His notes are very encouraging. The big excitement is that he’s explicitly building a client-only version of the code for 99.99% of users, and he thinks he can keep it to < 10,000 lines of code. That would be fantastic, both for security and for performance. I hope it’s a success. So far it looks very promising.

unicodecsv 0.11.0 speed improvement

My little Python csv parsing benchmark had one really nice effect; someone contributed a patch to remove some unnecessary calls to isinstance in certain circumstances. He claims a 2x speedup. That patch was just released in 0.11.0, so I tested it. These are the same benchmarks and data file I ran and reported before as “Python 2 results”

 61.65s unicodeCsvReader 0.9
118.64s unicodeCsvDictReader 0.9
 41.12s unicodeCsvReader 0.11
 96.34s unicodeCsvDictReader 0.11

Not quite a 2x speedup, but runs in 0.7x or 0.8x the time it used to. That’s quite good for a simple change, and a nice example of open source working well.

I should really stop using the csv DictReader. Or maybe make a new one that’s smarter. The current Python module seems to actually create a real dict object for every row. I think you could make something faster that used a class wrapper for the tuple that emulated dict-style retrieval by looking up column offsets in the row header. At least there’d be less data copied, but maybe the wrapper overhead would negate that. Have to try it to see.

Modern consoles vs bandwidth

I just got a Playstation 4. Sony seems to have dropped any rules related to game update download sizes. Newish games I bought on disc like Shadows of Mordor or Dragon Age: Inquisition require downloading 8GB “game updates” before they’re playable. Sometimes on the first day the game comes out! And multiplayer titles like Destiny are even worse. 16GB to download the game, another 8GB + 16GB of downloads if I recall correctly.

I started setting up this PS4 and 4 hours later, it’s downloaded 80GB. That’s to install 2 games I bought on disc, 3 games from download, and 2 downloaded demos. I’m just grateful I had the foresight to set this up before hauling the console up to Grass Valley and the 1Mbps Internet there. An 8GB download will take literally 24 hours to download there. Also I have a 30GB cap, so let’s hope updates aren’t frequent.

Census of US county parcel records

Fairview Industries has a great map of which US counties publish GIS parcel data. Mike got the shapefile for the database. I went ahead and extracted just the URLs and county names to a convenient CSV file.

The file lists a total of 3214 counties. 2022 have ViewURLs defined and 590 have DownURLs defined.

Here’s my extractor code.

#!/usr/bin/env python3

import fiona, sys, csv

out = csv.writer(open('extracted.csv', 'w', encoding='utf-8'))

out.writerow(('FIPS', 'State', 'County', 'ViewURL', 'DownURL'))

count = 0
gisInvLks = 0
viewUrls = 0
downUrls = 0
with fiona.drivers():
    with fiona.open('counties.shp') as counties:
        for county in counties:
            props = county['properties']
            # Fix mojibake; Fiona read these strings as ISO-Latin-1 but they are actually UTF-8
            cntyNm = props['CntyNm'].encode('latin_1')
            cntyString = cntyNm.decode('utf-8')
            out.writerow((props['StCntyFIPS'], props['StNm'], cntyString, props['ViewURL'], props['DownURL']))
            count += 1
            if props['ViewURL']:
                viewUrls += 1
            if props['DownURL']:
                downUrls += 1

sys.stderr.write('%d rows\n%d ViewURLs\n%d DownURLs\n' % (count, viewUrls, downUrls))

Ubuntu on a Mac Mini

I finally gave up on MacOS for a Mac mini server I have and wiped it and installed Ubuntu 14.04LTS. It mostly went pretty smoothly, Ubuntu makes bootable images for Mac hardware that work fine off of USB keys. And I just wiped the whole disk and removed any vestiges of the MacOS boot loader, I imagine it’s a bit trickier if you care to preserve MacOS.

The one real problem I ran into was the new system hung at boot right after adding swap. That error is a red herring though; really it’s hanging trying to change video modes. Dumb, particularly the lack of a useful console message. The solution is to add nomodeset to the kernel command line in GRUB.

Also a few minor problems. The WiFi adapter doesn’t work, of course, although maybe the non-free drivers I was advised I could install fix that. Ubuntu’s automagic partitioner doesn’t give you a way to resize the swap partition, you’re stuck with it being the size of system RAM. And it did enough other magic things on repartitioning I was afraid to try to roll my own.

I’m pretty unimpressed with how slow this Mini is, now that I have an OS I understand on it. The Plex server seems OK, and it can transcode 1080p video at 5x real time or better. But trying to rsync 300GB of files over gigabit ethernet to it basically pegged the machine; the poor SSH process with the network connection was using 50% CPU even after I told it to use arcfour encryption, supposedly the fastest available. And terminal responsiveness was like 10 seconds at a time, although maybe it’s partly the Linux scheduler to blame for that. Anyway the system has a i5-3210M CPU which apparently is pretty weak, despite having 2 honest cores in it. Will be fine for a file server but I’m glad I built a beefy compute server for real work.

Python file reading benchmarks

After doing my CSV benchmarks yesterday I decided to do something simpler and just compare how long it takes to read files with and without Unicode decoding. My test file input is a 1.8G UTF-8 text file, the actual data is dk.csv, Danish street names. It’s exactly 1,852,070,317 bytes or 1,838,573,679 characters. The file has DOS newlines, so there’s both a 0x13 and a 0x10 at the end of every line. 33,445,793 lines total.

I didn’t use timeit for a proper microbenchmark, but I did warm the cache and make sure the times were repeatable. Some weirdness; sometimes the job takes 2x as long to run. Cannot explain that, maybe some L2 cache contention in a shared CPU? I took the faster timings.

Reading the whole file at once

  • Python 2, reading bytes: 0.5s
  • Python 2, reading unicode via codecs: 5.9s
  • Python 3, reading bytes: 0.5s
  • Python 3, reading unicode via codecs: 1.6s
  • Python 3, reading unicode via open(): 3.7s
  • Python 3, reading unicode via open with no newline conversion: 2.2s

Conclusions

  • Python 2 and Python 3 read bytes at the same speed
  • In Python 2, decoding Unicode is 10x slower than reading bytes
  • In Python 3, decoding Unicode is 3–7x slower than reading bytes
  • In Python 3, universal newline conversion is ~1.5x slower than skipping it, at least if the file has DOS newlines
  • In Python 3, codecs.open() is faster than open().

That last one about codecs.open is really weird. Codecs isn’t doing newline conversion, but even so it’s still 1.6s vs 2.2s. Maybe open() also does some other processing?

Reading the file a line at a time

  • Python 2, reading bytes: 0.6s
  • Python 2, reading unicode via codecs: 43s
  • Python 3, reading bytes: 1.0s
  • Python 3, reading unicode via codecs: 58s
  • Python 3, reading unicode via open(): 3.5s
  • Python 3, reading unicode via open with no newline conversion: 3.3s

Conclusions

  • Python 3 is ~1.7x little slower reading bytes line by line than Python 2
  • In Python 2, reading lines with Unicode is hella slow. About 7x slower than reading Unicode all at once. And Unicode lines are 70x slower than byte lines!
  • In Python 3, reading lines with Unicode is quite fast. About as fast as reading the file all at once. But only if you use the built-in open, not codecs.
  • In Python 3, codecs is really slow for reading line by line. Avoid.

Overall conclusion

Python 3 UTF-8 decoding is significantly faster than Python 2. And it’s probably best to stick with the stock open() call in Py3, not codecs. It may be slower in some circumstances but it’s the recommended option going further and the difference isn’t enormous.

Some of these benchmark numbers are surprising. My guess is that someone optimized Python 3 UTF-8 decoding very intensely, which explains why it’s better than Python 2. And the really terrible times like 40-50s are because some Python code (ie: not C) is manipulating the data, or else data structures are being mutated and it’s breaking CPU caches.

The code

"""Simple benchmark of reading data in Python 2 and Python 3,
comparing overhead of string decoding"""

import sys, time, codecs

fn = sys.argv[1]

def run(f):
    "Run a function, return time to execute it."
    # timeit is complex overkill
    s = time.time()
    f()
    e = time.time()
    return e-s

def readBytesAtOnce():
    fp = open(fn, 'rb')
    fp.read()

def codecsUnicodeAtOnce():
    fp = codecs.open(fn, encoding='utf-8')
    fp.read()

def py3UnicodeAtOnce():
    fp = open(fn, encoding='utf-8')
    fp.read()

def py3UnicodeAtOnceNoNewlineConversion():
    fp = open(fn, encoding='utf-8', newline = '')
    fp.read()


def readBytesByLine():
    for l in open(fn, 'rb'):
        pass

def codecsUnicodeByLine():
    for l in codecs.open(fn, encoding='utf-8'):
        pass

def py3UnicodeByLine():
    for l in open(fn, encoding='utf-8'):
        pass

def py3UnicodeNoNewlineConversionByLine():
    for l in open(fn, encoding='utf-8', newline = ''):
        pass

atOnce = [readBytesAtOnce, codecsUnicodeAtOnce]
if sys.version_info.major == 3:
    atOnce.append(py3UnicodeAtOnce)
    atOnce.append(py3UnicodeAtOnceNoNewlineConversion)

byLine = [readBytesByLine, codecsUnicodeByLine]
if sys.version_info.major == 3:
    byLine.append(py3UnicodeByLine)
    byLine.append(py3UnicodeNoNewlineConversionByLine)

open(fn).read()    # warm cache
for f in byLine:
    t = run(f)
    print('%7.2fs %s' % (t, f.__name__))

Python CSV benchmarks

I tested various ways of reading a CSV file in python, from simply reading the file line by line to using the full unicodecsv DictReader. Here’s what I discovered. Test data is dk.csv, a 3.4M row CSV file with 46 columns. (See also: file reading benchmarks.)

  • The Python2 csv module takes 2x longer than a naive split(‘,’) on every line
  • Python2 DictReader takes 2-3x longer than the simple csv reader that returns tuples
  • Python2 unicodecsv takes 5.5x longer than csv
  • Python3 csv takes 2-3x longer than Python2 csv. However it is Unicode-correct
  • Pandas in Python2 is about the same speed as DictReader, but is Unicode-correct.

I’m not sure why unicodecsv is so slow. I did a quick look in cProfile and all the time is being spent in next() where you’d expect. All those isinstance tests add significant time (20% or so) but that’s not the majority of the 5.5x slowdown. I guess string decoding is just a lot of overhead in Python2? It’s not trivial in Python3 either; I hadn’t realized how much slower string IO was in Py3. I wonder if there’s more going on. Anyway I filed an issue on unicodecsv asking about performance.

I’ve never used Pandas before. I ran into someone else saying unicodecsv is slow who switched to Pandas. It sure is fast! I think it’s a lot of optimized C code. But Pandas is a big package and has its own model of data and I don’t know that I want to buy into all of that. Its CSV module is nicely feature-rich though.

Not sure what conclusion to draw for OpenAddresses. I think we spend ~50% of our time just parsing CSV (for a CSV source like dk or nl). Switching from DictReader to regular reader() is the least pain. Concretely, for a 60 minute job that’d bring the time down to about 40–45 minutes. A nice improvement, but not life altering. Switching to Python3 so we no longer need unicodecsv would also save about the same amount of time.

Python 2 results

 0.17s catDevNull
 0.25s wc
 1.91s pythonRead
 0.58s pythonReadLine
 6.62s dumbCsv
 10.97s csvReader
 29.63s csvDictReader
 62.82s unicodeCsvReader
120.93s unicodeCsvDictReader
 27.93s pandasCsv

Python 3 results

 0.17s catDevNull
 0.25s wc
 5.18s pythonRead
 3.50s pythonReadLine
11.83s dumbCsv
27.77s csvReader
51.37s csvDictReader

The Code

# Benchmark various ways of reading a csv file
# Code works in Python2 and Python3

import sys, time, os, csv, timeit
try:
    import unicodecsv
except: 
    unicodecsv = None
try:
    import pandas
except:
    pandas = None

fn = sys.argv[1]

def warmCache():
    os.system('cat %s &amp;gt; /dev/null' % fn)

def catDevNull():
    os.system('cat %s &amp;gt; /dev/null' % fn)

def wc():
    os.system('wc -l %s &amp;gt; /dev/null' % fn)

def pythonRead():
    fp = open(fn)
    fp.read()

def pythonReadLine():
    fp = open(fn)
    for l in fp:
        pass

def csvReader():
    reader = csv.reader(open(fn, 'r'))
    for l in reader:
        pass

def unicodeCsvReader():
    reader = unicodecsv.reader(open(fn, 'r'))
    for l in reader:
        pass

def csvDictReader():
    reader = csv.DictReader(open(fn, 'r'))
    for l in reader:
        pass

def unicodeCsvDictReader():
    reader = unicodecsv.DictReader(open(fn, 'r'))
    for l in reader:
        pass

def dumbCsv():
    'Really simplistic CSV style parsing'
    fp = open(fn, 'r')
    for l in fp:
        d = l.split(',')

def pandasCsv():
    d = pandas.read_csv(fn, encoding='utf-8')
    # Ensure pandas really read the whole thing
    d.tail(1)

def run(f):
    &amp;quot;Run a function, return time to execute it.&amp;quot;
    # timeit is complex overkill
    s = time.time()
    f()
    e = time.time()
    return e-s

warmCache()

functions = [catDevNull, wc, pythonRead, pythonReadLine, dumbCsv, csvReader, csvDictReader]
if unicodecsv:
    functions.append(unicodeCsvReader)
    functions.append(unicodeCsvDictReader)
if pandas:
    functions.append(pandasCsv)

for f in functions:
    t = run(f)
    print('%.2fs %s' % (t, f.__name__))

OpenAddresses optimization: some baseline timings

Some rough notes for optimizing openaddresses conform. These times are from a January 23 run of the Python code. The machine was busy running 8x jobs, so times may be a bit inflated from true, but it’s a start.

Here’s 3 sources that I know to be slow because of our own code. The time reported here are purely the time doing conform after the thing was downloaded.

  • nl (csv source): 35 minutes, 14.8M rows
  • dk (csv source): 43 minutes, 3.4M rows
  • au-victoria (shapefile source): 46 minutes, 3.4M rows
  • ??? ESRI source. No good examples; most of my conform code treats this as effectively CSV anyway, so going to ignore for now.

I just ran nl again and it took 31.5 minutes (26 minutes user, 5 minutes sys). Close enough, I’ll take these January 23 times as still indicative. At least for CSV sources.

Here’s some fast / short sources I can use for testing. These are total times including network.

  • us-ca-palo_alto.json (csv source) 26 seconds
  • ca-bc-north_cowichan.json (csv source) 24 seconds
  • us-wa-chelan.json (shapefile source) 33 seconds

And here’s a report of top slow jobs that didn’t actually time out. Some of this slowness is due to network download time.

3521s us-va-city_of_chesapeake.json
2807s au-victoria.json
2765s us-ca-marin_county.json
2589s dk.json
2116s nl.json
2032s us-sc-aiken.json
1660s us-va-new_kent.json
1639s es-25830.json
1541s us-nc-alexander.json
1498s us-va.json
1367s us-va-fairfax.json
1352s us-sd.json
1345s us-ca-los_angeles_county.json
1325s us-mn-ramsey.json
1216s us-al-calhoun.json
1015s us-mi-kent.json
973s us-ms-hinds.json
955s us-wa-skagit.json
937s us-tn-rutherford.json
918s us-ca-solano_county.json
918s us-nc.json
786s us-fl-palm_beach_county.json
783s us-wa-seattle.json
776s us-wa-king.json
769s be-flanders.json
762s us-sc-laurens.json
729s us-wy-natrona.json
691s us-il-mchenry.json
682s us-tx-houston.json
678s us-al-montgomery.json
656s pl.json

grep Finished *.log | sort -nr  -k 9 | cut -c 65- | sed ‘s%for /var/opt/openaddresses/sources/%%’ | head -50

Here’s some quicky cProfile output, sorted by cumulative time.

ca-bc-north_cowichan

python -m openaddr.conform ~/src/oa/profile/sources-fast/ca-bc-north_cowichan.json ~/src/oa/profile/caches/cowichan.csv /tmp/o/foo
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    6.053    6.053 <string>:1(<module>)
        1    0.000    0.000    6.053    6.053 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:723(main)
        1    0.000    0.000    6.049    6.049 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:700(conform_cli)
        1    0.000    0.000    3.628    3.628 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:652(extract_to_source_csv)
        1    0.042    0.042    3.628    3.628 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:433(csv_source_to_csv)
    30260    0.170    0.000    3.241    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:187(next)
    30260    0.163    0.000    2.958    0.000 /usr/lib/python2.7/csv.py:104(next)
    30262    2.639    0.000    2.715    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:105(next)
        1    0.042    0.042    2.421    2.421 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:678(transform_to_out_csv)
    15129    0.066    0.000    1.328    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:510(row_extract_and_reproject)
559802/15130    0.636    0.000    1.256    0.000 /usr/lib/python2.7/copy.py:145(deepcopy)
15132/15130    0.147    0.000    1.219    0.000 /usr/lib/python2.7/copy.py:253(_deepcopy_dict)
    30260    0.028    0.000    0.822    0.000 /usr/lib/python2.7/csv.py:151(writerow)
    30260    0.033    0.000    0.599    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:82(writerow)
    15129    0.026    0.000    0.571    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:558(row_transform_and_convert)
    30262    0.085    0.000    0.402    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:46(_stringify_list)
   332882    0.147    0.000    0.312    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:35(_stringify)
   509313    0.236    0.000    0.309    0.000 /usr/lib/python2.7/copy.py:267(_keep_alive)
    15129    0.025    0.000    0.256    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:590(row_smash_case)
    30260    0.170    0.000    0.196    0.000 /usr/lib/python2.7/csv.py:143(_dict_to_list)

us-wa-chelan

python -m openaddr.conform ~/src/oa/profile/sources-fast/us-wa-chelan.json ~/src/oa/profile/caches/chelan/*shp /tmp/o/foo

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   29.549   29.549 <string>:1(<module>)
        1    0.000    0.000   29.549   29.549 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:723(main)
        1    0.000    0.000   29.545   29.545 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:700(conform_cli)
        1    0.000    0.000   19.640   19.640 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:652(extract_to_source_csv)
        1    3.952    3.952   19.640   19.640 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:343(ogr_source_to_csv)
        1    0.163    0.163    9.903    9.903 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:678(transform_to_out_csv)
    44111    0.367    0.000    6.508    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:187(next)
  1764400    2.433    0.000    6.275    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:3012(GetField)
    44111    0.324    0.000    5.837    0.000 /usr/lib/python2.7/csv.py:104(next)
    44112    5.138    0.000    5.370    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:105(next)
    88222    0.095    0.000    3.969    0.000 /usr/lib/python2.7/csv.py:151(writerow)
    88222    0.120    0.000    2.759    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:82(writerow)
    44110    0.078    0.000    2.512    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:558(row_transform_and_convert)
    88224    0.450    0.000    1.791    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:46(_stringify_list)
   972727    0.595    0.000    1.578    0.000 {method 'decode' of 'str' objects}
    44110    0.078    0.000    1.487    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:590(row_smash_case)
  1764440    0.502    0.000    1.328    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:3183(GetFieldDefn)
  2029152    0.652    0.000    1.325    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:35(_stringify)
    88222    0.933    0.000    1.114    0.000 /usr/lib/python2.7/csv.py:143(_dict_to_list)
  7149945    1.114    0.000    1.114    0.000 {isinstance}
  1764400    0.537    0.000    1.109    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:3478(GetNameRef)
  1764400    0.440    0.000    0.988    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:2552(IsFieldSet)
   972728    0.309    0.000    0.983    0.000 /usr/lib/python2.7/encodings/utf_8.py:15(decode)
  1764400    0.504    0.000    0.960    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:2277(GetFieldCount)
    44110    0.715    0.000    0.920    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:592(<dictcomp>)
    88222    0.848    0.000    0.848    0.000 {method 'writerow' of '_csv.writer' objects}
  1764440    0.826    0.000    0.826    0.000 {_ogr.FeatureDefn_GetFieldDefn}
   972727    0.258    0.000    0.782    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:2335(GetFieldAsString)
   972728    0.674    0.000    0.674    0.000 {_codecs.utf_8_decode}
    44111    0.026    0.000    0.636    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:1190(GetNextFeature)

Profile conclusions

For a CSV source, we spend roughly half the time converting source CSV to extracted and half converting extracted to final output. That’s no surprise; the two CSV files are nearly identical. A whole lot of that time is spent deep in the bowels of Python’s CSV module reading rows. Again no surprise, but it confirms my suspicion that DictReader may be doing more work than we’d like.

For a shapefile source, we spend roughly 2/3 of the time using OGR to convert to CSV and 1/3 of the time converting the intermediate CSV to the final output. The OGR code is opaque, not clear how to figure out what it’s really spending time doing inside the C module.

Not clear what conclusions to draw here; there never is with profiling tools. I think my next step should be benchmarking Python’s CSV DictReader and seeing whether some simpler parsing would work significantly faster. I also think it’d be a huge improvement to remove that intermediate CSV file entirely, there’s a lot of overhead reading and writing it. It makes the code way simpler to work with but it should be possible to stream the data in memory and retain most of the same code model.

Not clear any of this optimization is worth the effort.

OpenVPN in practice

My Tomato OpenVPN has served me well on this trip to India. Mostly using it to dodge the Taj Hotels’ hostile wifi, with random ports not routed and some porn filter that blocks any news site with embedded video as well as innocuous sites like reddit.com/r/mapporn.

Running the OpenVPN server on the HTTPS port was definitely the right choice.

It takes too long for Tunnelblick to negotiate a connection to my Tomato router’s OpenVPN server. Like 20+ seconds, often 30. Why isn’t it 1 second?

Setting this up on my home cable modem is a bit silly when I have a nice fast 100Mbit server in a colo. Need to learn to set up OpenVPN on Ubuntu. Now that I’ve done this with the Tomato server that seems easy.

Someone needs to make a privacy-only wrapper for OpenVPN, something just to set up VPN tunnels that route the whole Internet. The whole easy-rsa, cert management, etc process I’m doing now is way too complicated for the simple result I get.

iPad charging vs Air

I plugged my iPad into my Macbook Air to charge and it says “Not Charging”. WTF? Turns out that iPads (sometimes?) only charge when asleep, particularly when plugged in to computer USB ports. That leads to a sort of quantum paradox where the act of observing the thing charging stops it from charging. Stupid.

MacBook Air ports are apparently capable of providing the 2 amps of current an iPad wants to charge. The way to know for sure is to look for “Extra Operating Current” in the USB part of System Information. Oh except the Air won’t put the current out if it’s asleep.

More detail in this article. USB charging is too complicated.

HooToo travel router

This router from HooToo is amazing: $18 for the HooToo Tripmate Nano. Ethernet in, 802.11 b/g/n out, and it acts like a router, bridge, can even serve SMB with a USB disk. And the thing is about 2x2 inches, less than half the size of a pack of cards. $18!

No idea how it works as a bulletproof serious router. I bought it for travel, in particular for hostile hotels that either have no WiFi, bad WiFi, or want to charge you per device. If they have an ethernet cable you’re usually better off than trying their wireless.

$18! How is that possible? Particularly the 802.11n chip. It’s an American company too, or at least they list an address in San Jose. (English is awfully bad on the site.) Hardware design is cheap, obviously, but seems solid enough.

The firmware is clearly some Linux derivative. The Nano just offers a binary, which I unpacked as far as to see it was an initrd image. Another product of theirs includes a “GPL Source download” so they’ve at least heard of open source license requirements.

Compare two OpenAddress runs

I’m re-running OpenAddress many times trying to be sure the output stays roughly consistent. It’s never the same twice; servers are unreliable and the data is changing. Also some code changes make small cosmetic differences like rounding error.

What works best for me is comparing the line counts in the output files:

wc -l out/*/out.csv > wc.txt

diff  --suppress-common-lines -y oa-full-790/wc.txt oa-new-esri/wc.txt

This only highlights sources that output different number of lines; if the contents in the columns is garbled you won’t see that. But it’s a good way to get an overview of what changed between two runs.

What precisely is Linux load average?

I picked up some Unix wisdom years ago from a greybeard to ignore the Unix “load average”. It’s just not a very precise measure of how busy a system is. That was particularly true in the Ultrix 2.2 systems I first learned on. The stupid thing counted zombie processes for calculating the load, and zombies take essentially no resources.

You’re always better off looking more closely at contention for specific resources in your system: CPU, RAM, Disk IO, Network IO. But the load average is one handy little number, what does it mean? I’ll focus on the first number, the 1 minute average. (The time averages are weird exponential decay things, I don’t understand them.)

The official docs say load average is “the number of jobs in the run queue (state R) or waiting for disk I/O (state D)”. So it’s a measure of CPU and Disk contention. The kernel source has a remarkably clear comment, that it’s the number of CPUs that are either running or uninterruptible. That specifically implies it’s the number of CPUs actually tied up doing some CPU task. I don’t really understand uninterruptible in the kernel other than it happens when you wait for disk. Not really a measure of disk bandwidth as disk wait. I also think this description means that time spent in the kernel itself (sys) is counted towards the load average.

So load average is a good measure of whether your system doesn’t have enough CPUs to do the work at hand. Aiming to keep load_avg = num_cpus on a long term average should maximize CPU throughput.

However a lot of our real work is network-bound, either Internet downloads or local network waiting for something like a database to answer. So for many kinds of work we want to run more simultaneous jobs than num_cpus. But a job waiting on the network contributes close to 0 to load average, so the heuristic of aiming for load_avg = num_cpus is not a bad one.

It’s still useful to look more closely at detailed system resource usage metrics. htop and vmstat are great for inspecting memory usage. I like iftop for network. iostat is the traditional tool for disk IO.

I’m running an OpenAddresses run right now with 32 processes on an 8 CPU machine. There’s a lot of network waiting, but num_cpus * 4 is too much. Load Average has been about 20. In previous runs with 16 processes the load average has been about 8–10.

Some useful extra reading:

S3 vs gzip encoding

S3 is an easy way to serve data on the web. It’s also pretty limited. One problem is the S3 web servers don’t do gzip compression on the fly. They don’t parse Accept-Encoding from clients and they don’t opportunistically gzip encode responses. Some details in this blog post.

So if you want to serve content gzipped, your only option is to serve it under two URLs; one with gzip, one without. You’re on your own for figuring out how to tell clients which URL they should use. The Amazon docs talk about how to set this up. In particular you want to hack in a Content-Encoding: gzip in the compressed version so the client knows to decompress it.

There is a hack some folks recommend, which is to only serve a gzip encoded version of your file at the URL. This will work with any modern web browser, but it’s not correct. You’re not supposed to serve gzip to clients that don’t ask for it. This actually matters in practice; curl and wget both don’t know how to handle gzip output. So if you do this hack, those clients will see compressed gibberish.

Note also there’s no way to upload to S3 with compression and create an uncompressed file when it gets there. You have to upload the uncompressed thing. Even uploading the gzip file is a bit tricky because you need to know the full file size to do a simple upload. This StackExchange question discusses how you can do a multi-part upload to sort of stream while you compress.

OpenAddresses wants to serve giant CSV files via gzip. I think the right way to do that is to serve the files explicitly as “foo.csv.gz” and serve a gzip binary blob. No Content-Encoding. That will require the client downloader know to decompress it.

For a business that’s all about charging people for storing and serving bytes, it’s kind of surprising they don’t do the simple obvious thing to give you a 75% reduction in the number of bytes you store and serve. I’m not suggesting any nefarious plot here, but I do wonder what it is about Amazon’s serving infrastructure that makes them unable to do gzip encoding.

Update: Amazon CloudFront started supporting gzip in Dec 2015. Not S3 itself though.

OpenAddress Machine mark 3

this post is a work in progress

Motivation

When I’m back from India late February I’d like to re-design OpenAddress machine to a more decoupled architecture. Right now the system runs one big Python process which runs all sources from download all the way to output CSV. (There is some state carried over from run to run, but not much.) It works pretty well and is simple, and a full run just takes 2–3 hours. But the multiprocessing stuff is brittle and the whole system is both overkill (most sources never change, why reprocess?) and also non-responsive (no fast way to test a new source).

Proposal

Move to a decoupled architecture where tasks are run as fully independent Unix processes. They share state via some centralized database / cloud storage thingy, and also post results in S3 for web serving.

As with the current architecture, the unit of work in the job system is a single source file such as us-ca-san_francisco. It runs as an independent Unix process with no awareness of other sources. It downloads, conforms, summarizes, reports, and uploads its results to the database and to S3.

In addition we also need a task queueing system, something that decides when to run source jobs and posts them on the task queue. That process works mostly by reading the database and deciding what work needs doing. Some rules: “immediately process a new source”. “Check a source weekly for new data and reprocess”. “Clear the whole queue and re-process it”.

Finally we need a task executor that looks at the queue and launches tasks as needed. This could be part of the task queuer, but it helps to think of it as a separate entity. When a task is finished it puts the result on the task record log.

Database implementation

I’m totally agnostic about the data store we use to track runs. It’s a very low demand system just a few hundred megs of data and a handful of transactions a minute. It will require something with consistency and responsiveness. The simple choice is a PostGIS database running persistently on some 24/7 server. I’m not sure what the cloud services equivalent would be, so running with the PostGIS idea, here’s some schema sketches:

Completed task records

  • Task ID
  • Time started
  • Time finished
  • Source name
  • Success / failure
  • S3 output paths: out.csv result, debug logs, etc
  • Whatever else write_state does.

Task queue

  • There’s a zillion ways to do a task queue in a database. Rows are placed in the table by the task queuer, then removed by the task launcher when they are dispatched.

Task implementation

A task should be a single Python program. It takes a source.json specification file and any job metadata that’s needed (hopefully none?) and executes it. For debugging purposes this program should be able to be run standalone on a developer’s machine with no dependencies on the queuing system, the task manager database, or S3.

These jobs will be a natural to run on cheap EC2 spot instances. Right now tasks take 0.5 – 90 minutes to run. A bit wasteful to spin up a whole EC2 instance for 30 seconds of work, but maybe that’s OK. We could also run tasks on a single workhorse machine, that’s effectively what we’re doing now. A single mid-level Linux box can run 16 tasks in parallel. (In fact parallelism is good; the jobs are a mix of load types.)

Alternate: subtasks

This proposal assumes that a whole source from start to finish is run as a single Python process. But in fact processing a source consists of several sub tasks, and it might be good to run them as separate sub-tasks. Here’s what the subtasks are:

  • Download from source URL / ESRI store
  • Sample the source data for user inspection
  • Convert the source JSON/CSV/SHP data to an extracted.csv file
  • Conform the extracted.csv data to OpenAddresses out.csv format
  • Upload out.csv and job data to S3

There’s times i’ve wanted to be able to execute these subtasks separately. Particularly the download part, that is slow and unreliable. To some extent the current data caching strategy in Mark 1 and 2 is dealing with that, and it may be sufficient. But you could imagine breaking every source into 5 tasks and running them separately on a job queue. Worth considering.

History

Why “mark 3”?

OpenAddress Machine mark 1 was Mike’s original work, wrapping the Node code in a bunch of Python scripts to do regular runs and post results in a web dashboard. It is awesome.

We’ve been working on mark 2, the “ditch-node” branch, where we rewrote all the Node code in Python. The overall job architecture is about the same as mark 1, the management of downloads and files and stuff. It’s one big Python process with jobs run in parallel using multiprocessing. We did make some changes to how tasks are conceived and run.

Updates

Some notes after this post was written

  • Ian notes that GitHub triggers and Jenkins could trigger a build on a new source

multiprocessing worker processes dying

Python’s multiprocessing.Pool has a design wrinkle that’s a bit awkward. If you have a pool with N tasks and one of those task subprocesses dies unexpectedly (say, to a SIGTERM or something) then the pool hangs. It looks like N-1 tasks have finished and there’s still one waiting. But it will never complete and your parent process will effectively be stuck. Note that normal termination doesn’t do that, including random exceptions, SIGINT from Ctrl-C, etc. A normal “kill” triggers this though, as certainly does a “kill -9”. Probably a segfault in the Python interpreter will too.

Personally I think this is a bad design choice, but it’s not by accident. There was a huge discussion about this behavior three years ago. I haven’t read it all, but most of the comments seem to be about the wisdom and difficulty of recovering from a bad state. The ticket got closed after someone committed some changes to concurrent.futures (Python 3’s preferred new library). Nothing changed in multiprocessing.Pool.

Recently this issue was revisited for multiprocessing.Pool with a new bug filed that includes a patch. The approach there (and concurrent.futures) is if a child dies unexpectedly, you want to kill the whole Pool immediately with a BrokenProcessPool exception. I’m not wild about this choice, but it’s definitely better than hanging.

None of this applies to the Python distribution we’re running today. The pool will hang. For OpenAddresses I suggest we work around the issue by simply not killing workers. If you want to abort a worker early, try SIGALRM. We could also install a SIGTERM handler to catch the simple “kill” case from an operator, but I’m not sure that’s wise.

In addition, OpenAddresses also has a SIGUSR1 handler that allows someone externally to shut down the whole pool. It’s good for recovering from this state.

Update: we hit this bug again in a new way. Some of the worker processes were getting killed by the Linux OOM Killer. The Python code doesn’t see any exception, it’s just a SIGTERM or something. Only way you know is a record in the syslog. (And the multiprocessing debug logs show a new worker started.)

S3 interface options

I’ve never really done much with S3 and now I am. Here are some tools I’ve tried to manage files on S3. None are very good, maybe someone can recommend better?

The Amazon web console works but is an awkward Web 1.8 app.

s3cmd is the common command line tool. It works fine. Despite it looking like an official Amazon product it’s not,  it’s “Copyright (C) 2014 TGRMN Software” and seems to be by Matt Domsch.

s4cmd claims to be a better s3cmd. Note that “pip install” installs the program as s4cmd.py. My one attempt to use it (“du”) did not work; said “1 task completed” but printed nothing.

s3 FUSE lets you mount an S3 bucket as a filesystem using userfs. The project comes with a lot of caveats, most notably that S3 doesn’t really have a notion of directories and while everyone mostly uses the same object naming convention to create a hierarchical namespace, it’s not entirely consistent. I didn’t try this one.

Cyberduck is a venerable graphical FTP client for MacOS that has S3 support. It works pretty well, it’s the main tool I’m using. You have to keep pressing “Refresh” if you want to see any updates to the bucket state. Also it complains about certificate names not matching when you run it.

Boto is the Python library everyone uses to write code to talk to S3. Here’s the docs. It does a lot more than S3, it’s a general AWS library.

Credential management is a nuisance. Two big opaque strings for keys and no standard on how to find them.

  • s3cmd uses $HOME/.s3cfg
  • boto uses $HOME/.boto
  • Cyberduck uses the MacOS keychain
  • The OpenAddresses tools I’m using take -a and -s command line flags.
  • Environment variables are popular, different tools use different ones. Sadly, environment variables are not private on shared Unix systems. Neither are command line arguments.

Two bugs I filed

One happy side-effect of being so careful working on OpenAddresses is I’ve been finding what look like bugs (or usability difficulties) in other libraries. It’s so easy to just shrug if something doesn’t work and hack around it. I’m trying to dig in and understand failures.

Python issue #23278: multiprocessing maxtasksperchild=1 + logging = task loss. Really nasty, hard to reproduce occasional problem with multiple processes and a task queue losing jobs. Finally pinned it down to a problem using logging from new processes.

Gdal issue #5811: Py3 Unicode problem. Near as I can tell, the Python 3 GDAL bindings simply don’t work with shapefiles that aren’t in UTF-8. I’ve had a hard time narrowing down a small test because the bug is only triggered if OGR doesn’t decide to convert encodings itself and I have no idea when or why it does that.

Happy multiprocessing

I managed to get multiprocessing working for OpenAddress job processing. Looks like it’s working pretty well. We use multiprocessing.Pool to manage worker processes, then set up a SIGALRM to abort jobs that run too long. (Using a nifty decorator to add the timeout). I also added a SIGUSR1 handler in the master job process that lets us abort the run. At least once I’ve had the pool fail where there was work being done but none of the worker processes was trying to do it.

Here’s a happy screenshot of htop showing a run going. Note the nifty custom process names courtesy of setproctitle.

Screen Shot 2015-01-18 at 3.30.17 PM

multiprocessing demo

I spent a few hours today learning about the Python multiprocessing module. It’s pretty slick, including pickling data structure to pass them around and stuff. I did some fancy work of my own to use SIGALRM to implement a per-job timeout. I think it works., see my sample code here.

OpenAddress Machine job management

Our OpenAddresses system wants to run N jobs at once while downloading and processing our ~1000 sources. Mostly to do a bunch of network requests to various servers in parallel, but also for some CPU parallelism in multi-core systems. Normal jobs use very little RAM (100M?) but occasionally a big GeoJSON file blows up to 2G or 4G. Here’s 4 options for job management.

Unix processes. I’ve been running stuff in GNU parallel, forking off a new Python process for each job. 8 simultaneous processes on a 8 CPU system. That’s worked pretty well, see previous blog posts for notes. CPU usage around 250%, memory usage all over the place but generally under 2G. Full job finishes in 3, 4 hours.

Python threads. I just tried openaddr-process for the first time to run a full go (on the same Linux box). That code works by spawning 16 threads. So one big Python process. That’s not working quite so well. Running at a steady 120% CPU; because of Python’s GIL we can’t get more parallelism. The process also has 11G resident. I suspect much of that could be reclaimed, probably left over from when 2 or 3 big GeoJSON jobs ran at once. But that stresses the garbage collector; there’s something to be said about killing a process. (Update: the resident set size got as big as 17G at one point, enough to force swapping. It didn’t seem to thrash though. Also Python is releasing the memory again later, the RSS has gotten as small as 9G again.)

Python multiprocessing. I want to try this. It should be a relatively easy change from threading, but I am hoping gives some CPU parallelism and memory housekeeping. Also we need a way to kill jobs asynchronously and Python’s threading module is designed to make that possible. With multiprocessing you just send a SIGTERM and are done.

Decoupled task architecture. openaddr-process is structured to do the job as one big long-lived Python process. Even with multiprocessing, when an individual job finishes it’s passing Python objects back to the task manager, which waits 3+ hours to collect them all before formatting the crucial report. This is brittle. Long term I’d like to redesign the system to be more decoupled, so that individual jobs run as completely separate processes and autonomously store state in some persistent storage; files and maybe a row or two in a database. Then the overall Machine monitor can just fork off jobs as it needs and collect data off the database. That’s much more like a task queue architecture, a robust thing. I know how to build this with my own servers, less clear how to match it to the EC2 model of cloud computing.

Fiona vs Unicode

Following on my OGR/Python vs Unicode work, I took a look at what Fiona is doing. Fiona is a nice Pythonic interface to OGR with a fair amount of Cython code to bridge the gap from the OGR C library to Python idioms. Fiona explicitly returns all strings as u’Unicode Strings’ in both Python 2 and 3 and has code to handle encodings.

Fiona tries to guess encodings. In theory you can override the guess with an encoding=’foo’ parameter when you open a source, but in practice that seems to do nothing. I tried passing in obviously wrong encodings like ‘ascii’ or ‘shift-jis’ and didn’t see any of the expected errors.

Below is the repr of the string Cassiopée as it comes through from the Shapefile in Fiona, with its own guessing. These all appear correct to me. Note that Python 2 encodes Unicode string reprs as ASCII using Python \x escaping, hence the \xe9 in the output. That’s a single character, the expected Unicode codepoint U+00e9 or é.

Good file (ca-qc-gatineau)

Python2. Fiona: u’Cassiop\xe9e’  OGR: b’76 Rue de Cassiop\xc3\xa9e’
Python3: ‘Cassiopée’  OGR: u’Cassiopée’.

Bad file (be-flanders)

Python2. Fiona: u’Now\xe9lei’  OGR: b’Now\xe9lei’
Python3. Fiona: u’Nowélei’  OGR: exception.

Summary

Fiona seems to be doing the right thing with both my inputs, returning proper Unicode strings in both Python 2 and Python 3. In Python 2 OGR seems to basically not be decoding at all, just returning byte strings that I’m supposed to decode myself. In Python 3 OGR is trying to return Unicode strings but throws an exception on my bad file.

I think from here, for our OGR code I should add something to explicitly decode strings to Unicode in Python 2 and file a bug in Python 3.

Fiona code

'Extract fields from shapefiles using Fiona, a Unicode test'

import sys, fiona, logging
from pprint import pprint

logging.getLogger().setLevel(logging.DEBUG)
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

enc = sys.argv[2] if len(sys.argv) > 2 else None
with fiona.open(sys.argv[1], 'r', encoding=enc) as source:
    for f in source:
        for field in f['properties'].values():
            sys.stdout.write('%s %r ' % (type(field), field))
        sys.stdout.write('\n')

Monitoring CPU usage

Quick way to track how much CPU is being used on your system:

$ mpstat -P ALL 1 1
Linux 3.13.0-44-generic (ub) 	01/15/2015 	_x86_64_	(8 CPU)

04:23:47 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
04:23:48 PM  all   25.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   75.00
04:23:48 PM    0    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    1    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    2    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    3    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    4  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
04:23:48 PM    5  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
04:23:48 PM    6    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
04:23:48 PM    7    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00

That’s a report with 2 processes spinning at 100% on an 8 CPU system. I usually use top and look at Munin graphs, but this is a bit more precise. Leave off the last “1” and it runs continuously, reporting once a second. Leave off both “1”s and it shows you the average since the system booted. Leave off the “-P ALL” and you get just the top line, an average over all CPUs.

OGR/Python vs. Unicode

I’ve been trying to figure out how OGR deals with Unicode, particularly in shapefiles, to solve this issue with OpenAddress conversion. I haven’t found clear docs. There’s something about a SHAPE_ENCODING environment variable and something else about OGR trying to guess. More details in that linked GitHub issue. Anyway, here’s what I discovered.

Good file

I have a working non-ASCII shapefile that seems to be in UTF-8. It’s ca-qc-gatineau for us, stored at http://gatineau.ca/donneesouvertes/telechargement/ADRESSE.zip, and has street names like Rue de Cassiopée that our code is working for us.

When OGR/Python opens the file, the capability OLCStringsAsUTF8 is set to True.

In Python 2, GetField() is returning Python strings of type str, which means “bytes”. Those strings appear to be sequences of UTF-8 code points, the repr() of that non-ascii street name is ’76 Rue de Cassiop\xc3\xa9e’. Basically OGR isn’t trying to handle Unicode at all for us, or rather if it is it’s returning UTF-8 encoded byte strings and all is well.

In Python 3, GetField() is also returning Python strings of type ‘str’, which now means ‘unicode’. Their repr in Py3 is a Unicode string, ‘Rue de Cassiopée’, which makes sense.

In both cases OGR/Python is doing the right thing, or at least something consistent and sensible.

Bad file

I have a non-ASCII shapefile that seems to be in Latin 1. It’s be-flanders for us, stored at https://downloadagiv.blob.core.windows.net/crab-adressenlijst/Shapefile/CRAB_Adressenlijst.zip. It has street names like ‘Nowélei (Jean Baptiste)’ although that é isn’t coming through right.

When OGR/Python opens the file, the capability OLCStringsAsUTF8 is set to False.

In Python 2, GetField still returns ‘str’. And the repr for that street is ‘Now\xe9lei (Jean Baptiste)’. That’s actually not awful; if I know to expect that behavior, I can decode that myself with ISO-8859-1 and get the Unicode string.

In Python 3, GetField() throws an exception.

Traceback (most recent call last):
  File /home/nelson/src/oa/shpenc.py, line 17, in &amp;amp;lt;module&amp;amp;gt;
    field = in_feature.GetField(i)
  File /usr/lib/python3/dist-packages/osgeo/ogr.py, line 3033, in GetField
    return self.GetFieldAsString(fld_index)
  File /usr/lib/python3/dist-packages/osgeo/ogr.py, line 2362, in GetFieldAsString
    return _ogr.Feature_GetFieldAsString(self, *args)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte

I don’t quite understand what is happening here, but I guess something inside the OGR code is trying to decode that sequence assuming it’s UTF-8 and failing. Note my code is not really in the stack trace here, I”m just asking for the field contents. I think this is an OGR bug. Or else I think the Shapefile is corrupt. Setting SHAPE_ENCODING before invoking my code doesn’t help.

Worth noting QGIS displays the string as Nowlei, skipping the non-ascii character.

Summary

It appears that what OGR is doing is trying to guess and cope with the source encoding, presenting UTF-8 byte strings to Python 2 code and Unicode strings to Python 3 code. Which is great! Only things go wrong with the be-flanders file. OGR presents an ISO-8859-1 byte string to Python 2, which you can cope with. OGR crashes in Python 3.

Test code

Here’s the little OGR/Python program I’m using to examine shapefiles. It runs in both Python2 and Python3.

import sys
from osgeo import ogr, osr
ogr.UseExceptions()

in_datasource = ogr.Open(sys.argv[1], 0)
in_layer = in_datasource.GetLayer()
inSpatialRef = in_layer.GetSpatialRef()

in_layer_defn = in_layer.GetLayerDefn()
in_feature = in_layer.GetNextFeature()
print('OLCStringsAsUTF8? %r' % in_layer.TestCapability(ogr.OLCStringsAsUTF8))
while in_feature:
    row = dict()
    for i in range(0, in_layer_defn.GetFieldCount()):
        field = in_feature.GetField(i)
        sys.stdout.write('%s %r ' % (type(field), field))
        in_feature = in_layer.GetNextFeature()
    sys.stdout.write('\n')

Second full OpenAddress run

After the first run against 600+ sources we patched up a bunch of bugs, improved the running infrastructure. Then I ran another set last yesterday, amended a little bit today to re-run jp-* and kr-* after one more bug fix. I wasn’t quite as careful in measuring everything, but here’s some notes on output.

  • 579 input sources: 484 out.csv files, 483 sample.json files
    84% success rate; compare 66% from previous run.
  • 102M output rows.
    Compare 80M from previous run, 100M from Node
  • Roughly 3.5 hours running time, maybe less.
    3 threads stalled on bad servers so it’s not a good measure.

Throwing out the 3 stalled runs, the average source took 137s to execute. Standard deviation of 585s, so it’s a very broad distribution. That first run averaged 104s (SD 265). But a lot more of those runs failed in 1 second!

I’m curious if the new ESRI code is faster or slower than the old code. It’s definitely better in that it works with many more sources. Don’t really have data for it. The ESRI time is probably dominated by slow servers anyway.

Here’s the slowest non-ESRI sources. Given that these times include download times from some slow servers I’m pretty OK with them.

dk            CSV   2000s     3.4M rows
au-victoria   SHP   1620s     3.4M rows
es-25830      CSV   1173s     8.8M rows
nl            CSV   1156     14.8M rows

95 sources failed to produce an out.csv. Of those, 7 did succeed last time we ran, a potential regression. Here’s the cause of each failure:

  • us-il-tazewell: ESRI source, JSON parsing error after many calls
  • us-tx-colleyville us-tx-dallas us-tx-hurst: ESRI sources, found no records
  • us-nc: missing “file” attribute for multiple shapefiles
  • us-dc: bad download
  • us-ca-san_diego: bad zip download

And finally here’s the list of all 95 sources that didn’t produce an out.csv. I should go through and hand-classify the failures again, but I bet most of 88 of them are for the same reason as last time.

au-queensland
be-flanders
ca-ab-calgary
ca-ab-strathcona-county
ca-bc-kelowna
ca-bc-langley
ca-bc-nanaimo
ca-bc-okanagan_similkameen
ca-bc-surrey
ca-bc-west_kelowna
ca-ns-halifax
ca-on-niagra
ca-sk-regina
us-al-shelby
us-ar
us-ca-san_diego
us-co-sanmiguel
us-ct-avon
us-dc
us-fl-alachua
us-fl-collier
us-ga-glynn
us-ia-linn
us-ia-polk
us-id-canyon
us-il-tazewell
us-in-hamilton
us-in-madison
us-in-st_joseph
us-la-st_james
us-ma
us-mi-muskegon
us-mn-dakota
us-mn-metrogis
us-mn-polk
us-mn-pope
us-mn-yellow_medicine
us-mo-barry
us-mo-st_louis_county
us-ms-madison
us-nc
us-nc-1
us-nc-10
us-nc-2
us-nc-3
us-nc-4
us-nc-5
us-nc-6
us-nc-7
us-nc-8
us-nc-9
us-nc-charlotte
us-nc-columbus
us-nc-davie
us-nc-wake_county
us-ne-omaha
us-nm-san_juan
us-nv-henderson
us-nv-lander
us-nv-nye
us-nv-washoe_county
us-oh-clinton
us-oh-hamilton
us-pa-beaver
us-ri
us-tn-memphis
us-tx-colleyville
us-tx-dallas
us-tx-denton
us-tx-el_paso
us-tx-hurst
us-tx-keller
us-tx-north_richland_hills
us-tx-round_rock
us-va-alexandria
us-va-augusta
us-va-city_of_falls_church
us-va-city_of_petersburg
us-va-richmond_city
us-va-roanoke
us-va-stafford
us-wa-san_juan
us-wa-snohmish
us-wi-adams
us-wi-calumet
us-wi-crawford
us-wi-dodge
us-wi-jefferson
us-wi-juneau
us-wi-lincoln
us-wi-oneida
us-wi-richland
us-wi-sauk
us-wi-superior
us-wy-laramie

Python: logging different threads to different files

The OpenAddresses code includes a Python task manager thats spins off a lot of Python threads, one per input file describing a job. We’d like to capture the debug log records for each thread to a separate file, for presentation in a dashboard. How to do that?

This demo program I wrote shows how. The key concept here is a Python logging.Handler() object that uses some per-Thread state to decide where to write the message. In this case I use the Thread name itself, but you could also use some state stored in Thread.local().

Also this feels related.. log4j had a way to store information in ThreadLocal variables that you could then write out to log files. Ie: you could add a special per-thread variable like “job name” or “HTTP session ID” and have the formatter print it out where appropriate. It was quite handy in some use cases. Python doesn’t exactly have that, but the cookbook has notes on doing something similar with Filters.

Update: see also Mike’s alternate approach. He creates a new Handler for every thread, then uses a Filter to only show messages from the thread he cares about. I like how the approach makes more use of logging’s machinery, it is a bit weird how I had to make a whole Handler that did something odd with the output. I think Mike’s approach means for N threads we’ll end up with N Handlers seeing every log message. That’d be inefficient but if there’s not 100+ threads I doubt it matters.

New hard drive

I just bought a 2TB hard drive. I’m running low on disk space; a new 400GB of digitized 8mm video doesn’t help things. Picked up a Western Digital 2TB Black 7200RPM, WD2003FZEX.

My Linux server has two 1TB WD Blue drives in it which have been quite solid. But I’ve since learned Blue is the cheapo option. The Black drives are better and not much more expensive. There’s also Red (fancy firmware for RAID), Green (lower power, 5400RPM), and Purple (streaming video). According to this benchmark I should expect to get about 150 MB/s compared to 120 MB/s for the 1TB drives I have now.

Having seen the IO contention of my OpenAddresses work I’m tempted to try to set up the two 1TB drives in a RAID-0 stripe configuration. But that’s complicated and I’m deeply suspicious of RAID, so probably not. Historically I’ve bought drives in pairs and used rsnapshot to back up from one to the other, I’ve now broken that symmetry. Not sure what to do with the new one yet.

Hmmm, 256GB SSDs are only $120, that’d be a fun toy.

Update: new drive installed fine. With a brand new empty disk I’m getting writes of 189MB/s, which is sure nice. Gets slower on the inside of the disk I imagine. Modern components are relatively easy to plug in, but of course the power cables are all upside down so each one requires a 180° twist.

git inhumanity: detaching your head

mike-the-headless-chicken1One of my favorite examples of git’s inhumane tool design is the warning

You are in ‘detached HEAD’ state.

WTF does that even mean? I do something as simple as wanting to look at a version of the code three revisions back and suddenly I’m decapitated? It’s an alarming bit of language, not to mention completely opaque.

Really the concept is pretty simple. The message could read “you checked out a version of the repo that doesn’t match the head of any named branch”. That would explain the state you’re in and be much less alarming. “Detached HEAD” is a shorter way of saying that, but is a bit of jargon that only makes sense to experts. The experts who don’t need that warning anyway.

The problem is git is designed by people who don’t see opacity as a problem. It’s like the Unix philosophy where “cat” mean “show file” and “rm” means “delete” and “grep” means “search”. I’ve internalized all those words 20+ years ago, but I’ve never forgotten how they are barriers to learning.

Python logging: __name__

I’ve been using the recommended idiom of getLogger(__name__) to log stuff in Python code. That’s supposed to turn into your module name so you get nice names like “openaddr.conform” for the file openaddr/conform.py.

Only it totally breaks if you invoke conform.py as a main function via python -m or the like. Because of course __name__ is set to __main__ in that condition.

Wonder why none of the logging tutorials mention that gotcha?

ssh root attacks

Just discovered my auth.log is spammed with folks trying to log in as root. Some 75% of the requests are coming from 103.41.124.0/24, which is about 20ms away from San Francisco and I’m guessing near Palo Alto. The whois record says it’s a firm in Hong Kong with the email address safestbusiness@gmail.com. Uh huh.

I tried installing fail2ban on Ubuntu 14.04 but it didn’t seem to work. The ugly thing works by scanning log files with scary Perl regexps, no way am I going to try to debug that. The whole premise of it makes me nervous too, I’d rather just ensure my services are secure. That’s adequate as long as you’re not worried about DOS-levels of traffic.

OpenAddress run: time to process

Here’s how long it took to process each source. No idea how much of this time was network, how much processing, etc. Painful irony that many of the slowest ones were the ones that didn’t work. There’s no job-level timeout.

2162.325   us-tx-dallas
1970.223   us-al-huntsville
1843.934   us-nc-alexander
1826.809   au-victoria
1639.524   us-tx-houston
1511.907   us-ca-san_bernardino_county
1423.542   es-25830
1385.237   pl-dolnoslaskie
1255.783   nl
1238.894   us-mn-anoka
1115.263   us-va-fairfax
1100.821   be-flanders
1087.482   pl-lubelskie
932.043   pl-slaskie
852.481   pl-podlaskie
817.774   pl-pomorskie
803.326   pl-malopolski
789.957   pl-mazowieckie
781.457   pl-lubuskie
779.531   pl-kujawsko-pomorskie
779.183   us-wa-seattle
772.016   pl-swietokrzyskie
768.572   us-wa-king
766.155   pl-podkarpackie
736.996   us-tx-denton
726.582   pl-lodzkie
712.528   us-ne-omaha
681.070   us-pa-philadelphia
680.825   us-ms-hinds
639.296   pl-opolskie
611.966   us-va
608.180   us-ca-los_angeles_county
592.763   us-nc-3
591.630   pl-wielkopolskie
581.695   us-co-jefferson
576.934   pl-zachodniopomorskie
559.960   us-fl-bay
557.759   us-oh-hamilton
554.983   us-ca-solano_county
521.117   us-fl-pinellas
520.235   us-oh-franklin
496.750   us-fl-manatee
491.657   pl-warminsko-mazurskie
427.657   ca-on-welland
415.115   us-fl-palm_beach_county
394.993   us-ca-san_diego
378.344   us-or-portland_metro
356.776   us-nc-mecklenburg
356.656   us-nc-5
340.884   es-25829
340.322   us-tn-rutherford
319.549   us-mt
310.424   ca-nb
293.255   us-va-loudoun
284.713   us-fl-charlotte
284.701   us-nm-san_juan
280.506   us-ms-madison
279.436   us-nc-7
273.664   ar-ba-buenos_aires
260.210   us-fl-clay
259.266   us-ut
252.911   es-25831
252.718   no
250.454   us-nc-10
243.587   us-in-hamilton
239.786   ca-on-toronto
236.674   us-va-city_of_chesapeake
233.260   us-id-canyon
227.365   us-nm-alburquerque
226.377   us-oh-cuyahoga
224.207   us-vt
221.414   us-nc-9
213.543   us-ca-san_mateo_county
210.970   us-ca-kern
210.303   us-fl-miami
207.909   us-fl-hillsborough
197.618   us-mn-dakota
197.151   us-fl-brevard
190.312   us-me
189.663   us-il-tazewell
179.207   us-tx-el_paso
179.126   us-pa-allegheny
175.989   us-nc-6
166.787   us-nc-4
165.742   us-co-larimer
155.927   us-ca-santa_clara_county
155.580   us-ga-muscogee
155.365   us-fl-sarasota
152.921   jp-aichi
152.023   us-nc-burke
150.282   us-ca-sacramento_county
142.847   us-dc
138.299   us-nc-1
136.860   us-oh-stark
136.565   us-ca-el_dorado_county
130.320   us-ga-chatham
125.109   us-tx-north_richland_hills
123.697   us-oh-lucas
122.766   us-ca-marin_county
119.822   us-va-stafford
119.769   us-oh-butler
118.186   us-wi-kenosha
110.447   us-ca-orange
110.149   jp-hyogo
103.195   us-nc-cary
102.859   us-tx-austin
99.213   us-ca-santa_barbara_county
98.967   us-il-vermilion
98.502   us-mt-flathead
96.210   us-ms-copiah
95.000   us-nc-iredell
94.719   us-co-arvada
92.375   us-nc-2
91.884   us-fl-volusia
88.892   us-ca-contra_costa_county
88.881   us-co-denver
87.736   us-mo-st_louis
86.178   us-tx-waco
84.266   es-32628
81.907   us-tx-colleyville
80.419   us-oh-greene
78.767   us-oh-delaware
78.532   us-ca-palo_alto
77.562   us-ca-fresno
77.328   jp-nagano
76.621   us-oh-lake
76.158   jp-shizuoka
75.286   us-nc-orange
73.651   us-nc-avery
72.853   us-mt-gallatin
72.545   us-nc-montgomery
72.190   au-tasmania
69.991   us-or-portland
69.405   us-tn-franklin
69.186   be-wa-brussels-nl
68.425   jp-kanagawa
67.906   us-nc-8
65.562   ca-bc-vancouver
65.465   us-il-macoupin
65.074   us-ca-ventura_county
63.371   jp-fukuoka
62.161   ca-bc-kamloops
61.934   us-tx-hurst
60.508   us-wa-city_of_spokane
60.384   us-tx-keller
60.120   us-oh-clark
57.881   us-mt-yellowstone
57.463   us-oh-mahoning
57.326   us-nc-cabarrus
56.569   is
55.605   us-il-jackson
55.457   jp-osaka
55.022   jp-gifu
54.289   us-oh-columbiana
52.161   us-mo-greene
51.536   us-va-arlington
51.290   us-mn-roseau
51.153   us-co-westminster
50.761   jp-tokyo
50.466   us-oh-jefferson
49.832   us-oh-ashtabula
48.766   us-mt-cascade
48.682   ca-on-hamilton
46.963   us-fl-citrus
46.023   jp-ishikawa
46.003   us-oh-trumbull
45.902   us-ca-bakersfield
45.794   us-co-arapahoe
45.746   us-nd-cass
45.516   us-wa-skagit
44.664   us-id-post_falls
44.443   us-oh-richland
44.222   jp-nara
44.064   us-oh-wood
42.650   us-nc-buncombe
42.276   us-co-mesa
42.112   us-nc-alleghany
41.743   jp-mie
41.643   us-fl-lake
41.412   jp-niigata
41.096   us-tx-williamson
40.901   ca-qc-gatineau
40.548   us-va-james_city
40.118   us-tn-jefferson
39.818   us-mn-wadena
39.400   us-va-louisa
39.240   us-oh-tuscarawas
39.075   us-wy-carbon
38.982   us-mt-missoula
38.972   us-md-carroll
38.865   au-queensland
38.796   us-ca-carson
38.714   jp-hokkaido
38.390   us-oh-licking
37.633   jp-kyoto
37.205   us-oh-portage
37.197   be-wa-brussels-fr
37.180   jp-kagoshima
37.177   us-oh-allen
37.004   us-oh-muskingum
36.500   us-il-menard
36.194   us-il-morgan
36.190   us-ak-anchorage
36.092   us-wy-albany
35.545   us-md-howard
35.249   us-ga-gordon
35.069   us-oh-wayne
34.263   us-ca-san_luis_obispo_county
34.092   us-mn-aitkin
34.065   us-nc-moore
34.036   us-wi-green
33.545   jp-kagawa
33.531   jp-okayama
33.191   jp-miyagi
33.138   us-mn-clay
33.088   us-oh-knox
33.008   jp-ehime
32.773   jp-yamanashi
32.620   jp-toyama
32.552   jp-hiroshima
32.001   jp-kumamoto
31.514   us-va-amherst
30.983   us-oh-seneca
30.331   us-nc-alamance
30.328   jp-shiga
30.269   us-oh-madison
30.212   us-wi-trempealeau
29.878   us-mt-lake
29.704   us-wi-calumet
29.582   us-oh-miami
29.470   us-mt-ravalli
29.048   us-ca-placer_county
28.687   ca-on-windsor
28.651   us-oh-hancock
27.639   ca-on-kitchener
27.455   us-oh-sandusky
27.420   jp-miyazaki
26.766   us-oh-lawrence
26.677   us-oh-fairfield
26.407   us-mt-lake_county
26.376   us-mt-madison
25.683   us-oh-huron
25.242   us-oh-erie
24.702   us-il-jersey
24.532   us-oh-guernsey
24.509   ca-bc-north_cowichan
24.407   jp-yamaguchi
24.311   us-nc-lincoln
24.006   jp-aomori
23.981   us-il-mcdonough
23.644   us-il-clark
23.476   us-il-putnam
23.437   jp-nagasaki
22.700   us-oh-ashland
22.108   us-il-schuyler
22.053   us-mt-lincoln
21.906   us-ca-napa
21.409   us-ca-santa_cruz_county
21.344   jp-wakayama
21.323   us-oh-williams
21.184   us-va-nelson
21.170   us-oh-shelby
21.101   us-oh-darke
21.098   us-ca-butte_county
21.091   us-co-fort_collins
20.880   jp-okinawa
20.805   jp-oita
20.732   ca-on-waterloo
20.546   us-oh-ross
20.122   us-oh-athens
20.068   us-wa-chelan
19.955   us-mn-becker
19.913   us-oh-putnam
19.363   us-ky-lexington-fayette
19.221   us-nc-haywood
19.079   jp-shimane
18.733   us-nc-chatham
18.615   us-oh-fulton
18.565   us-md-st_marys
18.356   us-il-massac
18.256   us-mt-silverbow
17.888   us-wy-laramie
17.864   us-oh-ottawa
17.811   us-mn-mille_lacs
17.628   us-oh-gallia
17.486   us-oh-crawford
17.345   us-nc-granville
17.086   us-oh-washington
16.881   us-oh-defiance
16.858   us-oh-marion
16.675   us-ca-shasta_county
16.354   ca-ab-calgary
16.302   us-oh-morrow
16.300   us-id-teton
16.095   jp-saga
16.057   us-oh-highland
15.799   us-va-halifax
15.565   jp-kochi
15.555   us-oh-logan
15.456   us-oh-pike
15.177   us-oh-holmes
15.073   us-oh-henry
15.065   us-nh-jaffrey
14.664   us-oh-clinton
14.541   us-oh-preble
14.537   ca-yk-whitehorse
14.442   us-nc-union
14.295   us-ca-berkeley
14.214   us-co-aurora
13.914   us-nc-city_of_elizabeth_city
13.876   us-oh-perry
13.676   jp-tottori
13.539   us-co-loveland
13.351   ca-bc-kelowna
13.335   us-nc-davie
13.325   jp-tokushima
13.276   us-mt-sanders
13.198   jp-fukui
13.157   us-nc-caswell
13.154   us-nc-city_of_king
13.120   us-mt-teton
12.972   us-co-boulder
12.967   us-mt-blaine
12.919   us-md-cecil
12.675   us-mt-jefferson
12.447   ca-on-guelph
12.382   us-mt-phillips
12.360   ca-bc-prince_george
12.336   us-mt-stillwater
12.278   us-mt-powell
12.269   us-oh-pickaway
12.214   us-oh-harrison
12.183   us-nc-blowing_rock
11.910   us-oh-wyandot
11.700   ca-on-burlington
11.690   us-va-city_of_radford
11.661   us-mo-cole
11.637   us-oh-hardin
11.628   us-mt-broadwater
11.604   us-ca-nevada_county
11.486   us-oh-mercer
11.400   ca-bc-okanagan_similkameen
11.281   us-oh-hocking
11.195   us-oh-meigs
11.153   us-oh-jackson
11.105   us-mt-fergus
10.942   us-oh-carroll
10.685   jp-saitama
10.585   us-oh-paulding
10.562   us-mt-big_horn
10.338   us-oh-van_wert
10.256   us-oh-brown
10.208   us-mt-valley
10.177   us-mt-deer_lodge
10.039   ca-on-oakville
9.806   us-mt-custer
9.804   us-mt-chouteau
9.730   us-va-salem
9.624   us-mt-roosevelt
9.514   us-mt-granite
9.391   us-oh-fayette
9.380   us-mt-carbon
9.232   us-mt-hill
9.210   us-mn-pope
9.134   us-ca-yuba_county
9.118   us-va-greene
9.055   us-oh-monroe
8.944   us-oh-vinton
8.440   us-oh-noble
8.099   us-mt-glacier
8.032   it-er-rimini
8.016   us-ia-pottawattamie
7.963   us-ia-marshall
7.956   us-mn-renville
7.882   us-mt-rosebud
7.764   ca-pe
7.546   us-va-blacksburg
7.546   us-mt-toole
7.523   us-mt-judith_basin
7.382   jp-tochigi
7.328   us-oh-auglaize
7.275   us-oh-adams
7.253   us-mt-musselshell
7.058   us-sd
6.987   us-mt-dawson
6.959   us-va-madison
6.927   us-nc-madison
6.911   us-mt-wheatland
6.894   us-mt-richland
6.827   us-ia-dallas
6.812   us-va-clarke
6.694   us-co-pitkin
6.667   us-ia-dickinson
6.585   us-ia-webster
6.560   us-nc-city_of_carolina_beach
6.412   us-mt-liberty
6.314   us-ia-marion
6.286   us-oh-morgan
6.271   us-ia-sioux
6.261   us-mt-petroleum
6.253   us-ia-crawford
6.188   us-al-shelby
6.133   us-ia-boone
6.026   us-wa-douglas
5.980   us-ia-sioux_county
5.860   jp-fukushima
5.552   us-ia-madison
5.505   us-va-city_of_petersburg
5.420   us-mt-garfield
5.335   us-mt-sheridan
5.186   us-ia-jasper
5.139   us-wi-iron
5.108   us-ia-carroll
5.078   kr-seoul-yeongdeungpogu-old
5.047   us-nm-dona_ana-2
5.013   us-mt-park
5.005   us-va-city_of_emporia
4.999   us-ia-winneshiek
4.996   us-mt-mineral
4.915   us-ia-palo_alto
4.892   us-wa-snohmish
4.869   kr-seoul-seongbukku-new
4.812   us-mt-fallon
4.801   us-mt-pondera
4.767   jp-ibaraki
4.594   us-ia-montgomery
4.562   us-in-st_joseph
4.530   us-mt-sweet_grass
4.496   us-ia-monona
4.491   us-ia-guthrie
4.443   us-ia-buchanan
4.368   kr-seoul-yangcheongu-new
4.308   kr-seoul-tobonggu-new
4.281   us-mt-meagher
4.225   jp-chiba
4.214   us-mt-carter
4.213   kr-seoul-mapogu-old
4.210   us-ia-buena_vista
4.198   kr-seoul-kangseogu-old
4.188   us-ia-wright
4.152   us-mt-prairie
4.141   jp-akita
4.135   jp-yamagata
4.127   kr-seoul-tongjakku-new
4.121   us-ia-shelby
4.120   us-nv-las_vegas
4.111   us-fl-alachua
4.079   us-ia-harrison
4.064   us-mt-powder_river
4.019   jp-gunma
4.016   kr-seoul-seodaemungu-new
4.009   us-ia-clarke
4.000   us-ia-benton
3.970   kr-seoul-yeongdeungpogu-new
3.960   us-ia-greene
3.950   us-ia-hardin
3.937   us-ia-franklin
3.911   us-ia-bremer
3.871   us-mt-daniels
3.865   us-ia-winnebago
3.757   us-pa-beaver
3.747   us-va-fluvanna
3.731   us-mt-mccone
3.518   ca-ab-grande_prairie
3.516   us-mi-ottawa
3.351   us-va-city_of_falls_church
3.319   us-ia-cass
3.311   kr-seoul-kangnamgu-new
3.309   us-ia-kossuth
3.306   us-mn-otter_tail
3.296   us-ia-delaware
3.294   kr-seoul-tongdaemungu-old
3.288   us-tn-memphis
3.243   us-ia-monroe
3.236   us-ia-cherokee
3.232   us-mt-golden_valley
3.223   us-ia-ida
3.207   us-ia-sac
3.195   us-ia-hamilton
3.194   us-ia-howard
3.180   us-va-middlesex
3.134   kr-seoul-songpagu-new
3.115   ca-bc-victoria
3.111   us-ia-calhoun
3.077   us-ia-decatur
3.071   kr-seoul-tongdaemungu-new
3.032   kr-seoul-kangbukku-new
2.957   us-mt-wibaux
2.898   kr-seoul-mapogu-new
2.890   us-ia-mills
2.851   us-ia-emmet
2.801   us-ia-lucas
2.752   kr-seoul-seongbukku-old
2.601   us-co-sanmiguel
2.595   kr-seoul-tongjakku-old
2.552   us-ia-pocahontas
2.546   kr-seoul-yangcheongu-old
2.498   us-ia-humboldt
2.490   kr-seoul-keumcheongu-old
2.433   us-ia-lyon
2.430   kr-seoul-kangnamgu-old
2.424   us-ia-clarke_county
2.412   us-ia-fremont
2.407   kr-seoul-kwangjingu-old
2.405   us-co-gilpin
2.375   us-tx-round_rock
2.365   us-mt-treasure
2.342   kr-seoul-kwanakku-new
2.328   us-mi-kent
2.325   us-ga-glynn
2.325   kr-seoul-kangseogu-new
2.325   jp-iwate
2.320   kr-seoul-seochogu-old
2.312   us-fl-collier
2.240   kr-seoul-kwanakku-old
2.200   kr-seoul-noweongu-new
2.190   kr-seoul-yongsangu-new
2.170   kr-seoul-noweongu-old
2.159   us-ak-matanuska_susitna_borough
2.117   kr-seoul-seochogu-new
2.032   us-mn-wilkin
2.026   kr-seoul-yongsangu-old
2.024   kr-seoul-kwangjingu-new
1.954   kr-seoul-chungnanggu-new
1.950   us-in-marion_county
1.875   kr-seoul-chongnogu-new
1.805   us-va-augusta
1.805   kr-seoul-kangbukku-old
1.798   ca-bc-west_kelowna
1.792   kr-seoul-chunggu-new
1.779   us-wi-oneida
1.774   kr-seoul-songpagu-old
1.767   kr-seoul-seongdonggu-new
1.753   kr-seoul-kurogu-new
1.750   us-wi-superior
1.733   us-nc-wake_county
1.724   us-mn-yellow_medicine
1.706   kr-seoul-kangdonggu-old
1.705   ca-bc-vernon
1.694   kr-seoul-chungnanggu-old
1.692   kr-seoul-chunggu-old
1.673   kr-seoul-seodaemungu-old
1.671   kr-seoul-seongdonggu-old
1.667   kr-seoul-kurogu-old
1.654   us-wi-adams
1.649   kr-seoul-kangdonggu-new
1.566   us-ct-lyme
1.565   kr-seoul-chongnogu-old
1.532   us-ct-watertown
1.519   kr-seoul-tobonggu-old
1.463   us-va-richmond_city
1.407   kr-seoul-keumcheongu-new
1.149   us-la-st_james
1.141   us-sc-lexington
1.141   us-nv-nye
1.137   us-ia-polk
1.134   us-ca-san_francisco
1.127   us-ct-haddam
1.121   us-mo-st_louis_county
1.120   us-mi-muskegon
1.115   us-mo-columbia
1.113   us-ri
1.108   us-wi-sauk
1.108   us-va-city_of_norton
1.105   us-wi-dodge
1.091   us-co-gunnison
1.091   us-ca-alameda_county
1.090   ca-bc-nanaimo
1.089   us-la-acadia
1.088   us-wa-san_juan
1.081   us-va-alexandria
1.079   us-va-roanoke
1.077   us-sc-berkeley
1.073   us-mn-polk
1.072   us-nv-henderson
1.070   dk
1.067   us-wi-fond_du_lac
1.064   us-in-madison
1.057   us-wi-juneau
1.040   us-mo-barry
1.003   ca-ns-halifax
0.986   us-al-calhoun
0.980   us-ca-amador
0.979   us-nv-washoe_county
0.953   us-ky-oldham
0.889   nz
0.863   us-va-essex
0.780   us-wi-jefferson
0.754   us-wi-vernon
0.720   us-nc-columbus
0.676   us-ny-nyc
0.658   us-ia-linn
0.654   us-ar
0.645   us-wi-richland
0.615   ca-ab-strathcona-county
0.609   ca-bc-surrey
0.547   us-wi-crawford
0.545   us-ma
0.532   us-wi-lincoln
0.529   us-ct-avon
0.524   us-va-accomack
0.524   us-nc-charlotte
0.516   ca-bc-langley
0.513   us-nv-lander
0.483   ca-sk-regina

OpenAddresses run: causes of failures

206 of the 608 sources I tried with the new Python code didn’t work. I went through and hand-classified them by type of failure. (Related: we need better error reporting in the code, I could only do this by reading stderr logfiles and guessing.)

I’d guess about half the failures are problems with the source not being online at the time. And maybe only a quarter of the problems are bugs in the Python parsing code. But not sure without looking more closely.

Update: I triaged and either solved or filed issues for the following failures:

  • Parser doesn’t handle malformed CSV
  • Parser doesn’t handle GML files
  • Excerpt failed (partial fix; the conform continues)
  • Run worked but no output CSV
=== Problems with the parser ===

Parser doesn't handle malformed CSV
https://github.com/openaddresses/machine/issues/36
  48 files: kr-seoul-*

Parser doesn't handle GML files
https://github.com/openaddresses/machine/issues/38
  15 files: pl-*

Excerpt failed
https://github.com/openaddresses/machine/issues/35
  is
  jp-akita, jp-chiba, jp-fukushima, jp-gunma, jp-ibaraki, jp-iwate, jp-saitama, jp-tochigi, jp-yamagata
  au-queensland
  ca-ab-calgary
  us-mn-dakota

Shapefile parsing problem
  ca-bc-okanagan_similkameen
  10 files: us-nc-? us-nc-10
  us-nc-lincoln
  us-ne-omaha
  us-va-stafford

CSV parsing problem
  be-flanders
  ca-pe
  us-co-mesa
  us-va

JSON parsing problem
  us-al-shelby
  us-ga-muscogee
  us-id-canyon
  us-in-hamilton
  us-mn-pope
  us-mn-wadena
  us-ms-hinds
  us-ms-madison
  us-nm-san_juan
  us-oh-hamilton
  us-pa-philadelphia
  us-tx-denton us-tx-el_paso us-tx-keller us-tx-north_richland_hills
  us-va-alexandria
  us-va-city_of_emporia
  us-va-city_of_petersburg
  us-wi-adams us-wi-crawford us-wi-dodge


=== Mysteries ===

Run worked but no output CSV
  ca-bc-surrey
  us-ak-matanuska_susitna_borough
  us-al-calhoun
  us-mi-kent
  us-mi-ottawa
  us-mn-otter_tail
  us-nv-las_vegas
  us-pa-beaver
  us-sc-berkeley
  us-sc-lexington
  us-sd
  us-va-accomack
  us-va-city_of_norton
  us-va-essex
  us-va-fluvanna
  us-wi-fond_du_lac
  us-wi-vernon
  us-wy-laramie


=== Malformed sources ===

Multiple shapefiles without a file attribute
  ca-bc-kamloops
  ca-bc-kelowna
  us-nc-davie
  us-oh-clinton
  us-wi-calumet


=== Problems getting source data ===

Download failed
  dk
  ca-ab-strathcona-county
  ca-bc-nanaimo
  ca-bc-vernon
  ca-ns-halifax
  ca-sk-regina
  us-ar
  us-ca-alameda_county
  us-ca-amador
  us-ca-san_francisco
  us-co-gunnison
  us-in-st_joseph
  us-mn-metrogis
  us-nc
  us-nc-wake_county
  us-ny-nyc
  us-va-augusta
  us-va-richmond_city
  us-wa-snohmish
  us-wi-superior
  za-nl-ethekwini

ESRI download failed
  us-ct-avon us-ct-haddam us-ct-lyme us-ct-watertown
  us-fl-alachua
  us-ia-linn
  us-ia-polk
  us-in-madison
  us-in-marion_county
  us-ky-oldham
  us-la-acadia
  us-mi-muskegon
  us-mn-polk
  us-mn-yellow_medicine
  us-mo-barry us-mo-columbia us-mo-st_louis_county
  us-mt-park
  us-nv-henderson us-nv-lander us-nv-nye us-nv-washoe_county
  us-tn-memphis
  us-va-roanoke
  us-va-salem
  us-wa-san_juan
  us-wi-iron us-wi-jefferson us-wi-juneau us-wi-lincoln us-wi-oneida us-wi-richland us-wi-sauk

Bad zip file
  nz
  ca-bc-langley
  ca-bc-west_kelowna
  us-co-sanmiguel
  us-fl-collier
  us-ga-glynn
  us-la-st_james
  us-ma
  us-nc-charlotte us-nc-columbus
  us-ri
  us-tx-round_rock
  us-va-city_of_falls_church

First run of Python OpenAddress code against full source set

After a couple of weeks of steady work the Python code to process OpenAddresses is nearly feature complete. I did a big run last night over all the sources we have. It went well!

Output statistics

  • 608 input sources: 402 out.csv files, 372 sample.json files
  • 80M out.csv rows. (Compare 100M from the Node code)
  • 3 hours, 5 minutes running time
  • < 16G RAM running 8x parallel
  • 11.5G of useful output files
  • 100+G disk used (temp files left on error)
  • 7G of cached source data: 3.5G zip, 3.5G json
  • 150Wh = $0.50 of electricity

Operational behavior

I ran the whole thing with 8x parallelism using GNU Parallel on my Linux box. The box is nothing special; a quad core i7 with 16G of RAM and a very ordinary 7200RPM hard drive. Home network is 100Mbit for downloads.

I think disk contention was the primary bottleneck, an SSD might make a big difference. So would keeping data in RAM while we process it, I think I overwhelmed the disk cache. FWIW the disk has a benchmarked performance of about 120 MBytes/second. But having listened to the thing, there was an awful lot of seeking going on. Parallelism isn’t friends with a single spinning drive.

Below are some munin graphs for the day of the run. There’s two runs here; an aborted run to the disk sda (which filled), then a successful run around 04:30 to 07:30 to the disk sdb. Not sure the graphs have a whole lot of information. They do show some serious IO contention; the CPU graph shows as much time spent in IO wait as doing actual work and disk latencies hit 500ms for awhile there, ugh. The memory graph is too messy to read but I do know the system never needed to swap.

Python 2 vs 3 gotcha: dict views

Python 3 changes something subtle in the core dict data type.

$ python2 -c 'print(type({}.items()))'
type 'list'
$ python3 -c 'print(type({}.items()))'
class 'dict_items'

The return type of dict.keys(), values(), and items() is no longer a simple list, it’s some fancy iterable. Unfortunately that iterable type doesn’t support other list methods like sorted. I guess the new type is more efficient, but it sure is a nuisance.

The simple workaround is to turn the result into a list.

sorted(list(myDict.items()))

But it’s more complicated than that, in fact there’s a whole PEP 469 about it.

Update: derp, I made a mistake. There’s no need to make the list, sorted(myDict.items()) works fine. However there are still other cases where you need to turn the dict_items type in to a real list.

I’m mostly having a good experience with Python 3 but run into weird little changes like this that bite you from time to time.

 

GNU parallel for openaddr-process-one

I’ve been running batches of OpenAddress conversion jobs for bulk testing with a simple shell for loop

for f in us-ca-*.json; do
  openaddr-process-one &quot;$f&quot; /tmp/oa
done

But it’s better to do this in parallel, particularly since the work is a nice mix of CPU, network, and disk IO. Below is my first ever GNU parallel script to do that.

How much parallel? My system has 16 gigs of RAM and 4 honest CPUs (looks like 8 cores because of hyperthreading). I originally tried running “--jobs 200%” but because of the hyperthreading that results in 16 jobs which feels like a lot. So I’m keeping it at 8.

With 8 jobs in parallel we process 29 files in about 14 minutes. Running that in serial took 48 minutes. Los Angeles County alone takes 11 minutes and Solano County takes 10, so a total of 14 minutes to run 29 files sounds pretty good to me.

us-ca-los_angeles_county downloads fast, all its time is being spent in my Python conform code. There’s 3M rows so it’s no wonder it’s slow, but that seems too slow. Good place to focus some code optimization effort.

Solano county takes 10 minutes to download. It’s one of those ESRI webservice things, 391 requests for 500 records at a time and each one takes 1 or 2 seconds. I’ve been thinking we ought to have a separate pre-caching process for the ESRI combining, store the GeoJSON ripped data in S3 somewhere. There’s no way to test for data changes on the ESRI services so we can’t cache if we go direct, this way we could insulate the rest of the machine from the slowness of the services and the caching problems.

We wrote the code to be careful about RAM, processing everything as streams. Most jobs only take a polite 70M to run, but us-ca-kern, us-ca-marin_county, and us-ca-solano all mapped 1G+. Those are all ESRI type services, maybe the code is buffering all the data in RAM? Need to look more closely.

I suspect the main point of contention for running in parallel is disk IO. There’s a lot of file writing and copying; my own conform code basically writes the whole dataset twice. In theory I could get that down to once but it makes the code significantly more complicated.

Running this in parallel like this makes me realize there’s still work to do on the logging configuration. I want to be able to say “log only to a file named on the command line with a configuration specified in a file named here”; my logging config code doesn’t allow that. I can use the command line config to log to a file, then we just shove all of stderr to /dev/null. It’d be nicer to ask parallel drop stderr from the jobs its running but I couldn’t figure out how to do that. Even better would be to make it so I can configure the Python logging the way I want.

#!/bin/bash

# Quickie script to run a bunch of openaddr-process-one jobs in parallel

srcdir=/home/nelson/src/oa/openaddresses-me/sources
out=/tmp/oa
sources='us-ca-*.json'

# Only try to process sources with a conform
sources=$(cd &quot;$srcdir&quot;; grep -l 'conform' $sources)
sources=$(echo &quot;$sources&quot; | sed s/\.json$//g)
mkdir -p &quot;$out&quot;

# Echo a bunch of commands to run; these could be piped in to shell to run sequentially
#for s in $sources; do
#    echo openaddr-process-one -v -l &quot;$out/$s.log&quot; &quot;$srcdir/$s.json&quot; &quot;$out&quot;
#done

start=`date +%s`
parallel -u --jobs 8 openaddr-process-one -v -l &quot;$out/{}.log&quot; &quot;$srcdir/{}.json&quot; &quot;$out&quot; ::: $sources 2&gt; /dev/null
end=`date +%s`
echo `echo $sources | wc -w` jobs run in $[end-start] seconds

sshfs / SublimeText = lost file

I had a bad experience with my Mac yesterday. I was trying to edit a .py file in SublimeText which was saved via sshfs, while also reading it on the local machine with the disk. Something went wrong with the save and before I knew it I had a 0 byte file on the disk and an empty buffer in SublimeText. File completely gone. (And in this case about 30 minutes of work lost; was just about to git commit, too :-().

I made it worse by not thinking carefully and closing the tab in Sublime. I think if I’d not done that, I could have hit undo and gotten the file contents back. For that matter I may have told Sublime to reload the file myself which was a mistake.

Still no idea why sshfs screwed up so badly. Or if it was an interaction with SublimeText.

littleBits remote temperature sensor

My friend gave me a littleBits Smart Home kit for Christmas. Fun electronics toy; you snap together a simple network of components like temperature sensors, LED displays, and a “cloud module” to build devices. I set up a simple thing that gets the room temperature, displays it on an LED, and also feeds it to the cloud device. It works!

Update: left it running a couple of days, 100% stable. A bit bandwidth hungry though; about a megabyte an hour uploads, or 300 bytes a second. And about half that download. I suspect it’s sending a single voltage value once a second and the rest is overhead.

Here’s a Python program I wrote to fetch the data from the device. The wrinkle here is that there’s no simple “get current number” polling interface; it’s all subscriptions and streams. That seems to be on purpose and while I can sort of see the rational, it does make the HTTP client 4 lines of code instead of 2.

#!/usr/bin/env python3
from pprint import pprint
import requests, json, sys, os
token = '27ebe6c681d8db547ff8ac02714e6c07ed08084cf844ffc247cc9f926f155b4'
device = '00e0547ff8ac'

headers = {
    'Accept': 'application/vnd.littlebits.v2+json',
    'Authorization': 'Bearer %s'; % token,
}

try:
    resp = requests.get('https://api-http.littlebitscloud.cc/devices/%s/input' % device,
                        headers=headers,
                        stream=True,
                        timeout=5)
    output = next(resp.iter_lines(decode_unicode='ascii'))
    resp.close()
    data = json.loads(output.lstrip('data:'))
except Exception as e:
    sys.exit(1)

out = os.path.dirname(os.path.realpath(__file__)) + &quot;/data.tsv&quot;
with open(out, 'a') as fp:
    fp.write('%d\t%d\n' % (data['timestamp'], data['percent']))
sys.exit(0)

python string formatting: truncation

Learned a new trick in python today, truncating strings in format specs using .precision.

>>>"%.2s" % "abcdef"
'ab'

Using this while yak-shaving, improving my Python logging formatting by truncating the log level name from a string like WARNING to a single character W

%(levelname).1s %(module)s:%(lineno)-4d %(message)s

W process_one:40   Nothing processed
I process_one:103  Wrote to state: /tmp/testOA-tJZweo/us-ca-oakland/index.json

MacOS sshfs: improving Finder performance

I’ve been using sshfs to access a Linux volume about 30ms away from where I am. I don’t expect this to be lightning-fast, but Finder was acting very slowly. Like 10 seconds to open $HOME, a directory with 143 files in it. Every directory took a few seconds the first time it was opened in Finder, even though network traffic was tiny. Presumably lots of little synchronous reads.

Long story short, the solution is:

-o noappledouble,noapplexattr

Using this in OSXFUSE sshfs is a lot faster. Maybe 2 seconds for that Finder window, not 10. The key feature is “noappledouble”. This tells sshfs to completely deny all access to any ._ and .DS_Store files. Not only does that keep this garbage out of your Linux filesystem, it avoids lots of network round trips as Finder tries to open them. (Not sure why a client cache doesn’t fix that, but oh well.) That option can cause Mac system calls to fail, and while I’m not certain I think the noapplexattr may help with that.

The advice to use these options is scattered all over the net, most of it seems to be a cargo cult inspired by this 2008 post. I did not find good docs for what we should be doing here in 2015, the best I could find are these old docs for MacFUSE which at least explain what the options do. I’m too lazy to read the source.

 

OpenVPN: UDP vs TCP

One thing I can’t decide with OpenVPN is whether to use UDP or TCP for the tunnel. The online guides for this are nonsense, babbling about how “TCP is more reliable so use it if you don’t want corrupted file transfers”. That’s not how it works.

My own impression is UDP is clearly a better choice for low level IP tunneling, in the abstract. The OpenVPN community seems to prefer UDP as well. OTOH it may not always work. Some networks don’t really route UDP correctly and I have a suspicion random UDP ports are more likely to be blocked than random TCP ports. (Best idea; run your VPN endpoint on TCP port 80. Ugh.)

In practice, from my Grass Valley client with the weirdo fixed wireless network, UDP isn’t working. Well it sort of works but the link is limited to 60kbps instead of the burst max of 2000kbps, and it’s flaky. Online docs suggest this is an MTU problem, in particular if you don’t have MTU path negotiation working. I could well believe I don’t. This FAQ suggests setting “mssfix 1200” as a workaround but it didn’t help. I tried the “tun-mtu 1500 fragment 1300 mssfix” config the docs suggest as a workaround but that broke the connection entirely. No idea why, but the log had some warning about “FRAG_TEST not implemented”. Maybe it’s because I only set it on one side of the tunnel (see this FAQ). Whatever, TCP is working, I’ll stick with that.

My Mac has another problem where the network doesn’t work for the first ~30 seconds after the VPN link establishes. It feels like some sort of timeout problem, maybe it’s using the wrong route or DNS is messed up or something. It may be specifically a Chrome problem.

Update: months later I realize this was a router QoS problem.

Weird network crash; VPN related? router bug?

Just had a weird crash on my network in Grass Valley. I was trying out my new VPN setup on my iMac, tunneling all my Mac’s traffic through an OpenVPN connection to my router in San Francisco. Worked great! Then I got clever and tried to open http://192.168.0.1/, my router status page, curious what the VPN route would do. That page looked like it loaded but I think Chrome was loading a stale page; once I clicked on any other page on the router status panel it failed.

But not just the web page failed. My network failed. In my whole house, every device dead. The router wasn’t responding to DHCP requests. Even worse, the router didn’t come back after power cycling it. Three times. The power light came on but there was no DHCP service on the Ethernet, no WiFi. It was like the router had failed to boot. I finally got the router to come up on the fourth try. That time I’d disconnected my ethernet switch (and the rest of the home network) from the router first.

I have no theory for what went wrong. It seems implausible that client traffic on a VPN would kill the router, but not impossible. But I have zero idea why the router wouldn’t boot successfully until I disconnected the rest of the LAN. Sadly, I have no logfiles from the router to help.

Now I’m scare to try using the VPN again. But, well, what’s the worst that could happen?

.. And we’re back, on the VPN again, and I can’t trigger that crash again. Maybe a fluke? I think the page I was loading when the network died last time was Tomato’s Device List. It seems very unlikely, but maybe that somehow does some funky ethernet tickling that got my switch in a bad state? Weird.

I did work to understand tunnelblick a little more. It creates a new network interface utun0 that’s a point to point link between two addresses in the VPN block. Then it adds a network route with destination “0/1” with the remote end of the VPN as the gateway. I guess that is a catch-up IPv4 route, which sits above “default” in priorities but below any more specific routing table entry like 192.168.0 going over my LAN. The result seems to work correctly, Wireshark confirms most of my traffic is going over the VPN tunnel but I can still connect to hosts on my LAN.

Ancient shell aliases

My .bashrc includes some shell aliases that I’ve been using for 20+ years now.

alias h=history
alias ls='ls -F'
alias cp='cp -i'
alias mv='mv -i'
alias pd=pushd
alias rotd='pushd +1'
alias ll='ls -l'
alias jobs='jobs -l'
alias type='type -a'

alias nethackb='nethack -B -u Elric'
alias nethackp='nethack -P -u Innocent' 
alias nethackv='nethack -V -u Zzrt'

Zzrt was the first character I ever ascended on.

Tomato router OpenVPN setup

Got inspired this morning and set up OpenVPN on my router so I can proxy my traffic through it when I’m traveling. I think I got it working.

My goal here is mostly to get a working network environment when on hostile hotel wifi. I don’t really care about encryption security, although that’d be nice, and I explicitly don’t want to bridge my network so it looks like I’m inside my house LAN. Purely a tunnel for working around badly configured public networks. I may still be better off just buying VPN tunneling via Cloak or something similar with a simple client and reliable servers, but I wanted to try it myself.

For my server, the Tomato firmware on my router has an OpenVPN server built in, under the “VPN Tunneling” tab. It’s just like all the other Linksys-derived open router firmwares, but is poorly documented. So I followed this DD-WRT guide for the basic outline of what to do and an article about Tomato for some specifics of what’s in the Tomato GUI. The OpenVPN docs look quite good too, but I didn’t use them.

Key configuration options I altered:

  • Basic: Start with WAN, TUN interface, TCP protocol. VPN subnet 192.168.23.0; I think this can be most any private use network but you want it to not conflict with whatever public network you might be on.
  • Advanced: do not push LAN to clients. Do direct clients to redirect Internet traffic. Respond to DNS and advertise it.

I’m not positive that TCP is the right thing. I did that because on a badly configured network TCP is more likely to work than UDP. But UDP is probably the right protocol to be using for tunnel traffic. It’s a shame you can’t easily just do both in the server config.

Generating keys is harder, you’re quickly in the morass of X.509 certs and OpenSSL. Fortunately the easy-rsa package automates most of this for you, creating your own certificate authority and keys and certificates for both server and clients (a big pile of .crt and .key files) Don’t forget to build-dh to set the crypto up, too, building dh2048.pem. Should build a key for each client, with an easily remembered name. ./build-key name

For the MacOS client I’m using TunnelBlick. It seems surprisingly good and usable for open source software, I’m curious why folks prefer the commercial Viscosity. Installation was mostly straightforward. The wrinkle is you need a .ovpn file to configure the client. Happily, TunnelBlick will generate a template for you; just alter a few parameters like the VPN server name. You also need to copy a client key over, one of the ones you generated with easy-rsa.

For the iOS client I’m trying OpenVPN Connect, which I think is the only realistic option. It seems to work. The process of configuring the client and keys is pretty ugly, the only one that really would work for me was using iTunes file sync to copy stuff to the client.

It all seems to work. It’s a bit hard to test since I’m inside the network I’m then tunneling through, but I could verify that the clients connected and were given addresses in the VPN network block. I need to go to another network to verify it’s really tunneling traffic right.

Shame the usability on this stuff isn’t better. It suffers from crypto-nerd security-over-usability disease. OpenSSH nailed the whole “generate crypto automatically” thing years ago, since these certs are only self-signed all the authentication and naming stuff should be ignorable. Would also be nice if the OVPN file contained the key material as well so you just had a single file to install. Even a zip file would be better.