Some Bits: Nelson's log

34 posts in January 2015

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