Some Bits: Nelson's log

126 posts in 2014

git pull: merge vs rebase

In my previous post I jumped through some hoops to do a “git fetch; git rebase” instead of a “git pull” so that I ended up without a merge commit in my timeline. (See explanation here). Those two commands are very manual, what else can we do?

One simple option is to do git pull --rebase, which rebases instead of merges.  However that can apparently cause problems depending on what’s in your local repo. I have no idea what rebase does if there would be a merge conflict.

The git up user-contributed command is another solution. I think at its heart it’s a wrapper for fetch + rebase, but it has some other smarts in it. No idea if it can cause problems.

This StackExchange answer has a much more thorough investigation. He recommends doing a git update followed by git merge --ff-only. I guess fast forwards are “safe”; using this flag prevents git from automatically creating a merge commit if it can’t fast forward. There’s a lot more detail there, worth a close read.

I’m going to follow the StackExchange recommendation of setting git config --global pull.ff only and see where that gets me. I think it’s entirely safe; if I do a pull the worst that will happen is I’m on my own to do a manual merge. I may still keep using that git up Ruby command, too.

And now my rant. Fuck git. It’s insane to me that you have to do this kind of contortion. The default obvious tool should be the right one. I hate the neckbeardy attitude you read in most git discussions where the Superior Nerd gets to say “actually, it’s complicated because it needs to be blah blah”. That’s crap; it’s complicated because git has a bad UI and a bit too many exposed sharp corners for civilian use. (I particularly like the StackExchange guy’s observation “Note that the purpose of Git is to make it easy to share and consume the evolution of a codebase, not to precisely record history exactly as it unfolded.”) Git is amazing in many ways and has enabled a lot of things, but I sure wish a more humane alternative were the popular one.

GitHub collaboration notes

After my whining about pull requests Mike gave me commit access to the repo. Here’s some quick notes on some simple git stuff he helped me do. The setup is we both started working in on separate projects. He made a private branch, made a bunch of changes, then pushed them to the ditch-node branch. Meanwhile I had made my own pyconform branch off of ditch-node before his changes and wanted to bring mine in with his. We could have just merged, but Mike asked me to rebase so that my changes came after his to keep the history tidy. That was easy because there were no conflicts. Here’s how it went.

# Push my pyconform branch up to GitHub
  506  git push -u origin pyconform

# Fetch Mike's changes in ditch-node
  507  git fetch origin ditch-node

# In my pyconform banch, rebase with the changes in ditch-node.
# This happened automatically without extra work on my part, no conflicts
# No commit necessary.
  510  git rebase origin/ditch-node

# Try to push my newly altered pyconform branch to GitHub
  513  git push
# That didn't work because we've altered history and Git is confused.
# So now we have to force the push to rewrite GitHub's version of things
  514  git push -f origin pyconform

# At this point my pyconform branch is done and looks as if I'd forked it off
# of Mike's changed, even though really we were working in parallel. Now it's
# time to merge my changes back to ditch-node and get rid of the pyconform branch

# Switch to ditch-node
  515  git checkout ditch-node
# Pull in the changes that are on GitHub
  516  git pull
# Merge from my pyconform branch
  517  git merge pyconform
# Push the merged commits back up to GitHub
  519  git push
# Delete my branch locally
  520  git branch -d pyconform
# Delete the branch on GitHub.
  521  git push origin pyconform
# Ooops, that didn't work, so do this magic to remotely delete the branch
  522  git push origin :pyconform

I regret not being more comfortable with this kind of git usage. I am sort of OK with git by myself but it’s a lot more complicated when collaborating.

openaddresses-conform Node code notes (plus bonus Python)

I’m working on porting openaddresses-conform from NodeJS to Python. First time I really sat down and read the code from start to finish. It’s remarkably clean and easy to follow, once you read past all the async-back-bending.

The basic flow of the tool is to take arbitrary source files, convert them to CSV files in a schema similar to the source, then convert that source CSV schema to the out.csv schema of OpenAddresses, the one with LON,LAT,NUMBER,STREET. It works by creating a lot of files on disk to hold intermediate results of transformations.

Here’s the core logic, which starts at processSource(). ConformCLI() is the command line tool entry point.

processSource(): download a source from the Internet, conform it, upload out.csv to S3.

conformCache() is the meat of the extract and transform process. It has comments!

  • Convert to UTF8: if source.conform.encoding is set, use iconv to convert source file to a new file with UTF8 encoding.
  • Convert to CSV: turn all types of sources in to a CSV file (see below on convert.js)
  • Merge columns if source.conform.merge is set.
  • Advanced merge columns if source.conform.advanced_merge is set.
  • Split address if source.conform.split is set.
  • Drop columns: prepare a new CSV file with just the core LON,LAT,NUMBER,STREET fields picked out of the processed source CSV.
  • Reproject to EPSG:4326. Only for CSV and GeoJSON files, creates a VRT file pointing at the processed source CSV and uses ogr2ogr to convert it to WGS 84.
  • Expand abbreviations: Fix Capitalization & drop null rows. This code is a bit woolly; it has a comment “I haven’t touched it because it’s magic” and there are no tests.

convert.js has five separate functions for converting different source types to a CSV file in the source schema.

  • shp2csv(): uses OGR2OGR to convert a shapefile to a CSV file. Also reprojects to EPSG:4326. Quite simple code.
  • polyshp2csv(): very similar to shp2csv(), but handles polygons.
  • json2csv(): uses geojson-stream to convert a GeoJSON file to a CSV file. Figure out headers from the first object’s properties. Converts polygons to points with a very simple average.
  • csv(): uses Node CSV modules to read the source CSV file and transform it into a cleaner CSV for further processing. Implements source.conform.headers and source.conform.skiplines.
  • xml(): uses ogr2ogr to convert an XML input to CSV, with reprojection. Very simple code, may not be used yet?
  • there’s code for computing the center of a polygon that’s duplicated in polyshp2csv() and json2csv().

openaddresses-conform has a small test suite. I believe it works on full source files, it’s more like functional tests than unit tests, running big chunks like conform or download and verifying the output is reasonable.

Existing Python port

Machine has its own Python code for doing the equivalent of downloadCache() and updateCache(). It’s quite different from the Node code strategy and is extra complicated because of the way Machine was a wrapper for invoking the Node code.

Very little of the extract and transform logic of conformCache() has been ported to Python but @iandees did some back in November. That code lives mostly in conform.py:ConvertToCsvTask. It works differently from the Node code. It basically takes whatever input file has been downloaded and uses Python OGR bindings to convert it to a CSV file in the schema of the source, plus an extra computed centroid. There’s no code yet to extract attributes or merge columns or anything. It’s streaming code, never loads the whole thing in to RAM.

I’m considering this choice to lean so heavily on OGR to process source files, it’s different from how the Node code is designed. I asked Ian and he said at the time all sources could be processed with ogr2ogr, so no need to write extra code for source CSV parsing, etc.

  • Check the type is .shp, .json, .csv, or .kml
  • Open source with OGR and figure out what field names are in it.
  • Set up OGR to transform the source SRS to EPSG:4326
  • Create a CSV file using csv.DictWriter with headers from the field name.
  • Iterate over features in the open OGR
  • For each feature, write a row to a CSV file with columns set to all fields from the feature. Also compute a centroid column.

I’ve never used the Python OGR bindings before. It’s pretty un-Pythonic and now I understand why Fiona exists. This list of Python Gotchas in GDAL will be a useful reference going forward. Apparently all the calls to Destroy() are unnecessary, but you do need to take care to manually dereference data sources.

NFS: Ubuntu server, MacOS client

I’m finally fed up with Mavericks broken SMB implementation. It’s appalling how bad it is. For awhile I had it working by forcing SMB 1 via cifs:// share naming, but that stopped working. Suddenly SublimeText and TextEdit were creating files with mode 0764, god knows why. MacOS touch was creating 0644 as expected. Anyway, fed up, it’s broken, so I’m going back to NFS. (Apparently Yosemite is shipping a new SMB 3 stack, maybe that’s better? Yosemite is broken in so many other ways though...)

I used NFS 3 years ago and those notes still apply. However, some changes.

Ubuntu server: as simple as can be. The wrinkle is that unless you want to get all fancy with Kerberos or idmapd or something user IDs don’t get mapped. Last time I just changed my numeric IDs on my Mac to match the Linux server. This time I’m trying something new, this cheese in /etc/exports:

/home/nelson 192.168.0.0/24(rw,insecure,async,no_subtree_check,all_squash,anonuid=30193,anongid=30193)

I’m abusing NFS anonymous ID mapping to force all requests to look like user ID 30193 and group ID 30193, my personal IDs on my Ubuntu box. It looks wrong on the Mac client, and it’s not appropriate for a multiuser server. But it gets the basic job done.

Mac client: more confusing now. Mavericks removed the graphical NFS configuration tool that I used to use. However the default automounter setup is not so bad. The path /net/ub/home/nelson is magically the NFS share ub:/home/nelson and seems to automount usefully. I think it’s using NFSv3. Haven’t needed to tune any parameters yet.

It wasn’t my primary goal, but as a bonus I get better speed out of NFS. The SMB 1 implementation seemed limited to about 10 megabits / second when writing to the server. NFS is running at the full 100 megabit link speed.

Happy Leap Week!

So leap weeks are a thing. In the ISO week date system “week 1” is “the week with the year’s first Thursday in it”. Today, Monday Dec 29 2014, is actually ISO week 1 for the year 2015. How’s that for confusing?

Rumor has it this weird calendar math is responsible for Android Twitter being broken. Some part of Twitter’s servers were returning a date a year in the future, in the year 2015, which is causing invalid OAuth signatures because of an expired certificate or something like that. Presumably the engineer used the ISO week-year by accident.

This is a bug that keeps on giving; two years ago iPhones got stuck in Do Not Disturb mode, probably for the same bug.

In Java SimpleDateFormat the difference is whether you ask for “yyyy” or “YYYY” and the docs don’t make it obvious you really want “yyyy” unless you’re doing something weird.

In Unix date’s format language (strftime?) the weird year to avoid is %G. %Y does what’s expected.

$ date -u
Mon Dec 29 15:47:54 UTC 2014
$ date -u +'%G-W%V-%u'
2015-W01-1

GitHub pull requests are too heavyweight 2

New version of an old rant. The GitHub pull request model makes sense if you plan to submit one giant PR a week. It’s terrible for rapid collaboration. Today I wanted to submit a 5 line patch to openaddresses/machine, in the branch ditch-node. I already have a fork NelsonMinar/machine. I had to:

  1. Switch to master branch in my clone of NelsonMinar/machine
  2. In my clone, manually set up an upstream remote for master
  3. Pull changes from upstream merge them with a fast forard.
  4. Push the merge result back to GitHub
  5. Repeat steps 1-4 manually for the ditch-node branch. I guess you’re expected to do this manually for every branch you care about.
  6. Create a new branch in my clone. I branched off the ditch-node branch
  7. Make my changes and commit them.
  8. Push my new branch back to GitHub with “--set-upstream origin”
  9. Use the GitHub UI to create a pull request.
  10. Fix the pull request so it’s a diff against ditch-node, not master. Note the branch I’m creating the PR in was branched off of ditch-node; no idea why GitHub didn’t respect that.
  11. Submit the pull request. Never ever touch that branch again until it’s accepted.
  12. As a bonus, the project maintainer warns me he has to rebase my pull request so it’s going to break my fork until I update.

It’s too much work on GitHub to follow along some repo and make occasional friendly improvements to it. I could use some simplified workflow which is just “keep my forked repo updated at all times with upstream unless it would clobber some work I did”. I imagine I could write a script to do that.

Maybe GitHub expects frequent committers to have write access and not go through pull requests. I like the review and auditing of pull requests, though.

Update: John Firebaugh recommends git-up and git hub to help make this better.

Need a simple reprojection tool

I want a simple tool to reproject a crappy whole-sphere image like this to something nice like Mollweide or Winkel Tripel. It seems like this would be easy enough with gdal, just have to learn enough about CRS to do it. The source looks like Plate Carree, no doubt produced by someone naive with a raster array of lat/lon samples.

Here’s a great StackExchange answer on reprojecting a bunch of tiles that’s more complicated than I need.

Edit: Mike M. to my rescue. He saw my blog post and offers

1. Turn the raw JPEG into geodata by creating a VRT file with a projection and an extent.
gdal_translate -a_srs EPSG:4326 -a_ullr -180 90 180 -90 -of VRT moon.jpg moon.vrt
2. Reproject the raster into the projection you want.
gdalwarp -t_srs EPSG:54009 moon.vrt moon-moll.tif
I chose projection 54009 based on a simple search for Mollweide on Spatial Reference, finding this: http://spatialreference.org/ref/esri/54009/. VRT is an XML-based format that leaves the original JPEG untouched: http://www.gdal.org/gdal_vrttut.html.
moon-moll
I should turn this to a single-serving site. Upload a Plate Carrée, download in one of several tasteful projections.

video frame rates

A question I’ve been pondering: are there only a few standard video frame rates? Asking on StackExchange and on Metafilter.

My suspicion is that in practice only 24, 25, and 30 fps works everywhere. I definitely had some issues trying to play downloaded YouTube 60 fps video. And my 15 fps experiment was a failure. Part of what’s complicating things here is that unlike resolution changes, frame rate resampling is a tricky non-continuous problem. Converting 30 to 60 is easy, just double. 24 to 60 is not awful, double 2 of every 3 frames. But converting 19 to 60 is, well, prime numbers don’t divide well. OTOH I would hope the file formats let you express whatever the source truly is and make it the player’s problem to represent it correctly.

Particularly peeved that 16 fps is not supported anywhere; that was the 8mm standard.

Code in The OpenAddress Machine

I’m trying to help with the OpenAddress project, particularly Mike Migurski’s “machine” code for running a full analysis of the data. Particularly particularly the ditch-node branch. Managed to get the tests running after some version hassle.

Now I’m taking inventory of what all code is in the repo to understand where to work. These notes are probably only useful right about now (December 2014) and only for the ditch-node branch.

openaddr/*.py

This is the big thing, about 1700 lines of Python code. The architecture is a bit confusing. I don’t really understand how it’s managing threads / processes for parallelism. Also the actual ETL code is a bit convolved with the download and cache code, including S3.

  • __init.py__: grab bag of top level stuff. Key methods:
    • cache() and conform() are wrappers around Python code to download and process data from sources. This code wraps Python modules and uses multiprocessing.Process to run them as separate jobs. (see also jobs.py) The comments say these are Node wrappers, but they no longer are in this branch.
    • excerpt() pulls bits of data out of source files for user presentation. Contains some logic for parsing CSV, Shapefiles, etc to get a few rows out of them. See also sample.py. Excerpt does not use Process.
  • cache.py: Download from HTTP, FTP, and ESRI sources. I believe this code entirely writes to local disk and does not use S3. The ESRI code has logic about doing database-like queries on URLs and rewriting the ESRI proprietary JSON to GeoJSON
  • conform.py: python code to translate source data to the OpenAddress CSV output schema. Uses the OGR Python bindings, etc. I believe this is not complete.
  • jobs.py: script code to run a bunch of cache jobs, conform jobs, etc as separate threads. I’m not clear how this multithreading interacts with the multiprocessing code in __init.py__
  • process.py: a main program. this invokes all the work described in jobs.py, then does some processing to extract report-like information (like the map). This is doing I/O via S3 and caches, not so much local disk.
  • render.py: Cairo and geo code to draw the map of data sources
  • run.py: a wrapper for running stuff on EC2
  • sample.py: extract some sample features from a GeoJSON file, used for excerpts?
  • summarize.py: produce a report about the job run using an HTML template.
  • template/state.html: the actual HTML file that is visible at http://data.openaddresses.io/. Or rather a Jinja2 template.
  • template/user-data.sh; not sure what this is. It seems to be a templatized “run” script that installs everything from scratch on a new machine. I imagine this is what Mike runs first on a fresh EC2 instance.
  • geodata/*: shape files. I think this is used by render.py to draw pictures of FIPS codes.

openaddr-*

Not part of the Machine repo, these are four small Node projects that contain code for managing OpenAddresses data. This is the code that’s being “ditched” in the branch, and in fact I think it’s no longer used outside the tests.

  • openaddr-source: this is the openaddresses project itself. The main thing is sources/*.json, a bunch of JSON files that describe data sources and their conforms.
  • openaddr-download: code that takes a source URL as input and downloads it. lib/connectors.js has the actual code to do FTP and HTTP requests. Also is able to get data out of ESRI services using esri-dump, another program by Ian Dees that has both Python and Node versions.
  • openaddr-cache: another downloading program, this one is focussed on caching source data in S3.
  • openaddr-conform: the big program, glues together all the other scripts into a single thing that takes a source JSON as input, emits a processed CSV as output. So it has a little download and cache logic in it as well as a bunch of ETL code for extracting data out of source files and emitting it in the simple CSV schema OpenAddresses publishes. it in turn relies on ogr2ogr and other tools for extraction.

test.py, tests/

Test suite for The Machine. All the code is currently in test.py, just 11 tests. tests/ is test data files.

chef/

Scripts to set up an Ubuntu server to run The Machine. I haven’t actually run these on my dev box, just copied out bits of it as necessary. Some of the things it does:

  • run.sh: install Ruby and chef, the invoke chef-solo
  • role-ubuntu.json: spec for The Machine. Installs Python, Node, and four openaddr-* Node modules.
  • **/default.rb: specs for each package. There aren’t many interesting bits here. Node is wired to version 0.10.33. Python installs Cairo, GDAL, and PIP. The openaddr-* modules get installed in /var/opt. Only openaddr-conform is now needed for the tests to run in ditch-node, although I’m not sure about the full machine loop.

kvm and Ubuntu snappy

I just launched my first Linux virtual machine ever, thanks to Ubuntu Snappy. Ubuntu 14.04 as the host and the stripped-down Snappy as the guest OS. The “locally with kvm” instructions worked fine except I had to add -nographic to the kvm command line to get it to launch headless.

The guest image has 512MB of RAM available, but the host qemu process has 940MB mapped. Wonder what that’s about? Presumably there’s ways to configure the resources availalbe on the guest machine.

I like the idea of Snappy, an Ubuntu distribution specially stripped down for VM guests, Docker, etc. I don’t know the market well enough to know if it’s competitive. I am much more inclined to use a guest OS if it feels like Ubuntu though. Confused about what snappy is doing as a package manager. apt-get is not enabled. dpkg is there and a bunch of stuff is installed, but I think you manage the Ubuntu core OS with snappy.

The guest reboots in about 11 seconds.

disk speed

2TB USB drives are now under $100. Which is awesome! But boy that’s a lot of disk to write. How long does it take?

Sadly my iMac is USB 2.0 only. In practice that gets about 21 MBytes/second with the disk. At that speed it takes about 27 hours to read or write all 2TB.

My Linux box has USB3 ports, so the data interface is no longer the limiting factor. In practice I’m getting about 110 MBytes/second, at least at the start of the disk. That’s 5 hours and is presumably gated by how fast the bits are spinning by the read head. Update: took nearly 7 hours, aggregate speed was about 82 MB/s.

(Side note:  how do you know you have a USB 3 connection? The plastic inside the port is colored blue, that’s the first tip-off. On Linux you can also inspect the interface speed with “lsusb -t”; 5000M means USB 3. Details on Stack Exchange.)

I’m not finding a reliable source for theoretical throughput on a 5400 RPM spinning platter. Numbers I’ve seen are in the realm of 50–150 MBytes/second. I’d forgotten it depends on the density of the disk. The little 2.5″ disks I prefer should be faster than bigger 3.5″ disks, all things being equal.

There are a few 7200 RPM 2.5″ portable drives out there now, but they’re unusual enough that they are expensive and I don’t fully trust them. Naively, at best that’s a 33% speedup for bulk throughput, not a huge difference. Faster seek times though.

All the rivers (Australia)

Got a decent looking work print of a map of all the Australian rivers, as inspired by Chad Ajamian’s map. It’s on Imgur as a JPG, wordpress.com seems to have done a reasonable job with the full PNG, compressed it better than I can (!).

I produced this in TileMill, using data imported to PostGIS with ogr2ogr. I hoped to use the new MapBox Studio but it’s kind of a pain. Working with local data sources is awkward and there’s no simple exporting to a hires image. TileMill still gets the job done, what a champ! QGis also works and is faster (caching?), but its pixel rendering isn’t as beautiful as TileMill’s.

Map is styled on two parameters. Color is brown or blue depending on whether the stream is perennial, line width varies by UpstrGeoLn, the length of all line segments that contribute to this line segment. That’s not a bad proxy for stream importance, actually, I’m using it in lieu of Strahler number. I like the results.

Here’s the relevant part of the TileMill style sheet.

#streams2[perennial="Perennial"] {
  line-color: @stream;
  line-width: 0.5;
  [upstrgeoln > 10000] { line-width: 1.0; }
  [upstrgeoln > 100000] { line-width: 1.5; }
  [upstrgeoln > 1000000] { line-width: 2; }
}

australian-rivers_c21b28

SRID 900914

Here’s a new one on me; I used ogr2ogr to import the Australian river data into PostGIS and it ended up being labeled with SRID 900914. WTF? According to this discussion that’s what ogr2ogr does if the SRID isn’t already defined in the PostGIS tables. It adds a new entry with the CRS info gleaned from the source file. And since the largest defined SRID in most PostGIS installations is 900913 (the bogus Google entry) why, the next one created will be 900914.

The data is actually in EPSG:4283 which PostGIS already knows about.

While I’m here, this Stack Exchange answer has some useful ogr2ogr flags for big imports. -progress and --config PG_USE_COPY YES. According to the docs COPY may now be the default, but I’m not sure it is. Adding it cut my running time to 20% of without.

python-pip is broken in Ubuntu 14.04

Running pip on my Ubuntu 14.04 box gives the error “ImportError: cannot import name IncompleteRead” when trying to import the requests module. Turns out this is a known bug going back to at least April. It’s subtle though; a different Ubuntu box with the same versions of python-pip and python-requests is fine. It’s apparently a bug in python-requests, see also Migurski’s workaround.

A quick workaround is to remove Ubuntu’s python-pip and install pip manually.

Classifying Australian rivers

So the Australian river database doesn’t have Strahler numbers for streams, which I need to classify streams in order of importance. I got a very nice reply from the AHGF team asking about Strahler number with some ideas on what to do.

One option is to classify on a different measure. AHGFNetworkStream has a couple of features that are useful; UpstrGeoLn and UpstrDArea. They are “Combined geodesic length of contributing upstream AHGFNetworkStream features (incl. segment).” and “Combined albers area (m²) of contributing upstream AHGFCatchment features (incl. segment).”, respectively. Ie: how long the line is that feeds into this line, or how big the area that feeds into this line. It’s worth a look. Of course what I really want is actual water flow, but that’s not readily available.

The other option is to calculate the Strahler number myself. It seems like a simple enough algorithm. As long as the data is clean, that is, a strict tree. The AHGF folks warned me their data has loops and splits that might cause problems.

ESRI tools apparently calculate Strahler, but that’s not useful to me.

GRASS also apparently has some Strahler calculations. (Or Horton, which is similar. “Stream order” is the generic term.) More details here. I wonder which is easier; using GRASS or writing my own code? :-P

Notes on Australian rivers

Inspired by this map of all Australian streams I’m taking a crack at extending my rivers map to Australia. There’s a great open data site which has what I need, sort of.

I’ve found two different layers that are likely candidates. I think what I want is AHGFMappedStream from SH_Cartography. There’s also a AHGFNetworkStream in SH_Network but it has slightly fewer entries and also has stylized geometries.

Here’s an image zoomed in near Strahan in Tasmania. Brown is the network view, blue is the mapped view.

Screen Shot 2014-12-04 at 5.04.19 PM

 

Hierarchy appears to be only “minor” or “major”. “Perennial” is an interesting field.

Unfortunately what I can’t find is the Strahler number of a stream. I need that, both for nicely rendering bigger streams in heavier lines and also to simplify when zoomed out. I think I can figure out calculating it myself (using NextDownId on the table) but it’s a pretty big project. May be easiest to do that on the Network layer; it appears I can join across layers on HydroID.

$ key="HIERARCHY"; ogrinfo -al -sql "select $key from AHGFMappedStream" *.gdb -geom=no | head -100000 | fgrep "$key" | ~/src/accumulator.py
   29682 .8906   HIERARCHY (String) = Minor
    3646 .1094   HIERARCHY (String) = Major
       1 .0000 HIERARCHY: String (0.0)

Here’s the full schema. The site has some PDF docs that are helpful too.

Layer name: AHGFMappedStream
Geometry: Multi Line String
Feature Count: 1927331
Extent: (113.375345, -43.629382) - (153.632074, -9.242297)
Layer SRS WKT:
GEOGCS["GCS_GDA_1994",
    DATUM["Geocentric_Datum_of_Australia_1994",
        SPHEROID["GRS_1980",6378137.0,298.257222101]],
    PRIMEM["Greenwich",0.0],
    UNIT["Degree",0.0174532925199433]]
FID Column = OBJECTID
Geometry Column = Shape
HydroID: Integer (0.0)
AHGFFType: Integer (0.0)
Name: String (0.0)
Hierarchy: String (0.0)
Perennial: String (0.0)
AusHydroID: Integer (0.0)
From_Node: Integer (0.0)
To_Node: Integer (0.0)
NextDownID: Integer (0.0)
Enabled: Integer (0.0)
FlowDir: Integer (0.0)
SrcFCName: String (0.0)
SrcFType: String (0.0)
SrcType: Integer (0.0)
SourceID: Integer (0.0)
FeatRel: DateTime (0.0)
FSource: String (0.0)
AttrRel: DateTime (0.0)
AttrSource: String (0.0)
PlanAcc: Integer (0.0)
Symbol: Integer (0.0)
TextNote: String (0.0)
GeodesLen: Real (0.0)
UpstrGeoLn: Real (0.0)
Shape_Length: Real (0.0)

Vector rivers back online

I brought my vector rivers map back online. It was a casualty of my server meltdown a few months ago, and I thought that no one really used it and it requires 3 daemons to work and it was a pain so why bother? I put a note saying “email me if you miss it” and every couple of weeks someone wrote, so I felt bad and finally fixed it today.

Code rots. Fortunately this didn’t rot too badly. All told took 5 changes (see Dec 2 2014 a7a9424..77debec), 14 lines. And a bunch of stuff to install, although it’s easier now in Ubuntu 14.04 which has newer versions of PostGIS and pgdbf.

It’s funny I never thought of the actual river maps themselves as my product, but rather my nerdy code project. I suspect at most two people have gotten my code working themselves, so that was a failure. But a lot of people like looking at pretty river maps. I should make an effort to make an even prettier one, just for the aesthetics.

Other project is to productonize the thing, specifically startup scripts and logging for Gunicorn. Kind of a PITA, may not bother.

netstat only shows some stuff as tcp6?

Weird, Apache doesn’t show up as tcp when running netstat -l on my Ubuntu 14.04 box.

tcp 0 0 *:ssh *:* LISTEN
tcp 0 0 localhost:postgresql *:* LISTEN
tcp 0 0 localhost:smtp *:* LISTEN
tcp6 0 0 [::]:http [::]:* LISTEN
tcp6 0 0 [::]:munin [::]:* LISTEN
tcp6 0 0 [::]:ssh [::]:* LISTEN
tcp6 0 0 localhost:postgresql [::]:* LISTEN
tcp6 0 0 localhost:smtp [::]:* LISTEN
udp 0 0 107.150.51.74:ntp *:*
udp 0 0 localhost:ntp *:*
udp 0 0 *:ntp *:*
udp6 0 0 fe80::52e5:49ff:fea:ntp [::]:*
udp6 0 0 localhost:ntp [::]:*
udp6 0 0 [::]:ntp [::]:*

Apache is definitely running on port 80 and serving live traffic. It does show up with the tcp6 entry, and I believe [::] means “all addresses” so that must account for it. Odd not to see it bound to the old IPv4 name. (Same with munin, but not ssh.) I wonder if this change was in netstat, the kernel, or how Apache binds ports? Anyway you can’t just ignore the tcp6 part of netstat even if your box doesn’t have a public IPv6 address, IPv4 stuff may be hiding there.

Life at 100Mbit

I can report that having 100 Mbit at home is a good thing. I know, who would have guessed? The raw speed makes an enormous difference. For instance a couple of days ago I installed Skyrim. 10 GB of download. On my old DSL that would have been 4 hours, something to schedule overnight. Now it’s less than 20 minutes. Also means I can stream an HD movie without worrying whether something else using the link will ruin the playback.

But the best thing is having so much capacity greatly simplifies the router. I used to go to great lengths to have QoS routing. Right now I’m experimenting with not bothering at all, it’s completely disabled. I don’t notice any problems even when running a full speed BitTorrent both up and down.

Part of the advantage is my Internet is now faster than a lot of the backbone, so “full speed” for the average site won’t saturate my link. I also think it matters that the packets are relatively smaller. On my shitty 1Mbit link a 1500 byte packet is 12ms wide. Even with perfect packet scheduling there’s going to be uninterruptible 12ms delays sometimes. With this good link that time goes down to 0.12ms, making it much easier to share the link between multiple applications.

More Logs of Lag aggregate stats

Following on my analysis of the average LoL game, here’s some scatterplots and histograms of various statistics for games. Specifically, for each game I’m looking at match length (0-3600 seconds is typical), best ping (10-150ms is typical), median ping (10-150ms is typical), and packets lost / minute (0-1 is typical, but long tail).

A huge caveat for this data: this is not a valid statistical sample of all LoL players. This is a random sample of Logs of Lags users, almost certainly biased towards people with network problems. I don’t intend to publish this data widely because it’s not a fair sample.

Honestly, the scatter plot is not the best treatment here; too many dots, not enough correlation. The histograms at top and right examining single variables are probably more interesting. Some notes:

  • Median ping and best ping are pretty tightly correlated. No big surprise there; they are nearly identical on a connection with low jitter and no packet loss. Not sure about the diagonal lines above the x=y line, maybe an artifact of how the game synthesizes a fake ping number in the presence of packet loss?
  • People’s pings are an interesting bimodal distribution, roughly peaking at 50ms and 110ms. I can’t account for the relative unpopularity of 80ms. Well if this were all North American data I’d say it was west coast vs. east coast, but I get a fair amount of European uploads too.
  • Packet loss / minute has a lovely long tail distribution. FWIW, I call anything over 5 a “bad link”; that’s ~30% of my logs, perhaps I should move that number up.
  • I was hoping to see evidence of correlation between packet loss and best ping, on the theory longer connections would be worse. I don’t see any evidence of that in the picture, it’s just a mess of dots. Need a better analysis tool. Same problem with packet loss vs. match length
  • Similarly, I can’t draw any conclusion from median ping vs. match length. That previous graph I did suggests the average ping for players does not go up during the game.

MacOS: sshfs and FUSE

When I first started using Macs the situation with FUSE, the user-space filesystem shim, was a mess. But it’s stabilized now and it appears OSXFUSE is the winner. Their binary packages for OSXFUSE and sshfs work just great. Here’s some very n00b friendly instructions.

sshfs -C ub:/home/nelson /Volumes/ub

I’m not sure if it’s possible to automount. sshfs needs my ssh credentials which aren’t available at login. probably not worth the hassle.

Unfortunately git prompt does not work well with sshfs; if you’re in a git-controlled directory it tries to do a whole bunch of file stats over sshfs, which is slow even though sshfs has some caching.

unset PROMPT_COMMAND

Even better, I use liquidprompt which lets you disable git in certain paths via LP_DISABLED_VCS_PATH, for just this reason.

The other drawback with sshfs is Finder is very slow. MacOS seems to do a lot of work on every single file, even when all it ends up displaying is the filename.

Companies selling “make your network better” products

Some interesting companies I ran across, all selling products to make home internet better. I can’t tell if any of these really work or not, just an interesting market category.

Netduma is going to sell a router optimized for gamers. Very little info on the website but so far it seems like better firmware, along the lines of what you get if you know how to make Tomato or DD-WRT work. Ie, “Anti-Flood” sounds like QoS scheduling. This product seems smart, in that it’s very hard right now to buy a good consumer router with good firmware. And they could get deeper into tweaking TCP/IP (like messing with windows, Nagling, etc), but even just doing decent QoS and buffering is a big help.

Speedify is a service that offers channel bonding for higher throughput by using multiple links. It sounds a little like a VPN, their client sends your traffic through to their “speed servers”. I’m skeptical this will really work in practice, but it’s interesting.

WTFast promises faster gaming, “cut your latency in half or better!”. The site is very marketing heavy and sounds like snakeoil to me, but maybe it could work. They have a “Gamer Private Network” which they claim is faster than the public Internet. There’s a $250k Kickstarter for router hardware, selling a 300MBps wireless router for the very good price of $50. They have a working software client and these Redditors report it helps them. I suppose a VPN service optimized for gamers makes some sense.

Bandwidth usage of LoL games over time

I had a theory that packet loss often gets worse after about 20 minutes of a League of Legends game, because people tend to group up and there’s more team fights. As a quickie-test of that theory, here’s a graph of the average characteristics of thousands of LoL netlogs for games that last 30-60 minutes.

Screen Shot 2014-11-19 at 4.32.19 PM

Not a lot of trend here. Bandwidth (grey line) does go up over time, but not radically. That could be just as much because cooldowns tend to go down as folks gear up as any effect of people grouping up. No useful visible trend in ping or lost packets, but that may be because the analysis is not good enough.

Lots of errors in this. The regular drops every minute are probably an aliasing problem having to do with the way the logs sample every 10 seconds.. usually. The population of netlogs is a mix of various game types, although by limiting it to 30+ minute games it’s mostly the main Summoners Rift games. (ARAM would significantly distort my hypothesis.)

Averages are a terrible way to calculate aggregate stats about packet loss and ping. But I don’t think they’d hide a trend of average ping or packet loss going up as a game progresses, I’d expect to still see it. Maybe not with the packet loss; the aggregate loss is so low perhaps it’s just not visible.

Testing DNS without cacheing

Helping a friend figure out a DNS problem, passing on some ancient wisdom about how to test if your DNS is right. The key thing is to avoid all the caches, make direct queries to the servers of authority.

$ whois somebits.com

Ask the Internet name authority about the domain somebits.com. Lots of crap is returned there, what you care about is the name servers.

$ whois somebits.com | grep 'Name Server'

Name Server: NS1.HOVER.COM
Name Server: NS2.HOVER.COM
Name Server: NS3.HOVER.COM

So now we know that there are three authoritative DNS servers for the domain. Let’s ask one of them for information (and strip out comments, lines starting with semicolon)

$ dig @NS1.HOVER.COM somebits.com any | grep -v '^;'

somebits.com. 900 IN NS ns1.hover.com.
somebits.com. 900 IN A 107.150.51.74
somebits.com. 900 IN SOA ns1.hover.com. dnsmaster.hover.com. 1394118405 10800 3600 604800 900
somebits.com. 900 IN NS ns2.hover.com.

ns1.hover.com. 900 IN A 216.40.47.26
ns2.hover.com. 900 IN A 64.98.148.13

The important thing here is learning the A record for somebits.com, pointing to 107.150.51.74. That’s the DNS record for my server.

If you’re debugging a DNS problem, start with this type of query. Go straight to the Name Server of authority. If those records are wrong then it’s hopeless. If they look right then something else can still have gone wrong. Particularly cached data, whether cached in DNS or else cached by client software. Google Chrome seems overaggressive about caching DNS info, for instance. Java used to be awful.

Node.js sqlite3: very slow bulk inserts

I’m running into a baffling problem where the straightforward way to use prepared statements in the MapBox sqlite3 Node.js code is super slow. Like inserting 100 rows in a table takes 16 seconds!

Update: found the problem, I wasn’t using transactions right. See bottom. Simple solution for faster bulk inserts in sqlite3: do them with a transaction.

The API docs have a strange note for Statement.finalize() which says “if you experience long delays before the next query is executed, explicitly finalizing your statement might be necessary”. I’m seeing exactly that. But after you’ve finalized it you can’t reuse the prepared statement; what’s the point of using statements at all then?

There’s notes online that naive bulk inserts in sqlite3 are slow, nothing to do with Node. See StackOverflow and Blog::Quibb. The quick fix I learned from both of those is to wrap the insert block in a transaction, because without that sqlite3 treats each insert as a separate transaction and is understandably slow. OK, so we’ll use a transaction.

But even with transactions using prepared statements is still slow in the Node version. I don’t know if this is a bug, me not understanding sqlite3 right, or me not understanding Node right. I am using serialized mode and trying to do simple nonconcurrent programming. The delay only occurs when the database is closed, btw, sqlite3 is accumulating the changes in a journal before committing them.

Three approaches:

  1. Call db.run(‘INSERT...’) a bunch of times. This is fast, but only if I wrap the inserts in a transaction.
  2. Prepare a statement once, then call stmt.run(‘INSERT...’) a bunch of times. This is slow whether I use a transaction or not.
  3. Prepare a separate statement for each row, then call stmt.run(‘INSERT...’) on it and then stmt.finalize(). This is fast.

Sample code is in this gist. “db” and “finalize” both take about 400ms on my Linux box. “reuse” takes 16 seconds to insert the 100 rows.

Update: the problem was I was creating the prepared statement before I did the “begin transaction”. Apparently that means the prepared statement is executed without the transaction context. Beginning the transaction and then preparing the statement, the three methods all run fast. I suspect the call to finalize has nothing to do with it, but I’m not sure.

Here’s the revision view: version one had the begin transaction too late.

Node.js sqlite3 error handling

This post is an exercise in trying to learn how to debug errors in Node.js programs.

Trying to write some sqlite3 code in Node.js. MapBox has a lovely Node module, but the docs are a bit thin and assume Node expertise I do not yet have. This morning’s challenge is trying to gracefully handle an error if database.run(“DROP TABLE”) fails. All work is running after database.serialize, so no concurrency.

By default with no error handling code, an error will cause an Unhandled ‘error’ event that kills the process. But you can’t just catch an exception because this is Node.js and exceptions don’t really work. So instead you need to specify a callback to database.run(), to get the Error (or else inspect the results of a successful statement.) Fair enough.

But what is the Error object in the callback? The sqlite3 docs don’t document this anywhere. In Chrome I’d just console.log() the object and use the lovely inspector. Node’s equivalent to the inspector is util.inspect, and you want to set showHidden to 1 to really see it. And voila:

{ [Error: SQLITE_ERROR: no such table: logs]
  [stack]: [Getter/Setter],
  [arguments]: undefined,
  [type]: undefined,
  [message]: 'SQLITE_ERROR: no such table: logs',
  errno: 1,
  code: 'SQLITE_ERROR' }

So this object looks like an ordinary Error object, with the message property. In addition it has errno and code properties. And now I know.

Another way to have learned all this would be to use the Node debugger. It’s pretty primitive, but you can set breakpoints in your code with the “debugger;” statement or from the debugger command line with “sb(lineno)”. Once it breaks you want to run “repl” to switch to the scope of your running script, then you can inspect objects. It all works but is a bit awkward without a GUI. I miss Chrome’s beautiful debugger; should try out node-inspector or something similar.

The irony of all this is I don’t even need too handle this error; sqlite supports “DROP TABLE IF EXISTS”. But oh well, now I know more about sqlite3 error handling and how to debug Node programs.

running tcpcrypt on Ubuntu

Excited by the new TCPINC effort, I went to build and install tcpcrypt, a sample implementation of a proposal. The GitHub project has recent activity and the code mostly builds.

I had to install these packages to get it to build:
autoconf libssl-dev libcap-dev libnetfilter-queue-dev.

It runs, too, and installs OK. Funky way it works using iptables to redirect traffic. The tcpcryptd self tests to check.tcpcrypto.org worked, but using curl to load the check page at http://tcpcrypt.org/test.php didn’t. Turns out the problem was curl doesn’t follow redirects and that’s the only way you know the test works, “curl -L” or “wget” works. I ended up setting up an SSH tunnel to test from my Mac and was able to get http://tcpcrypt.org/fame.php to work correctly and register as #809 on the Hall of Fame.

I’m curious if anyone plans to use this code as the basis for a real implementation. If so would be worth my time to make the build process easier. Also maybe remove some of the swear words from the code :-P

tcpinc

This is exciting: IETF has a working group on adding encryption to TCP. TCPINC.

They’re explicitly punting on authentication and certificate verification. That’s smart. The result won’t protect against MITM attacks, but it will still provide significant improved protection against passive traffic collection. Also authentication is really hard whereas basic wire encryption is not.

They also explicitly mandate NAT compatibility, which is a practical choice but means users are mostly not protected from traffic analysis. I can live with that.

The failure of IPSEC is one of the greatest mistakes the Internet architecture has suffered so far. SSL is a total hack and botch compared to properly encrypting data traffic. I’d argue doing it at layer 3, the IP layer, is better than doing it in TCP. But encryption is sort of a session-oriented thing so I can see why they want to start with TCP.

Hearthstone game logs

I’m playing a little of Hearthstone, Blizzard’s casual online CCG. It’s quite a fun little game, each turn is like solving a puzzle.

There’s a world of Hearthstone trackers out there that record your games and collect statistics. They are scary though, that whole industry is a little shady and I don’t trust them not to install malware. Also most of the trackers work by image detection (!) and there’s reports that some are messing with SSL certificates. Screw that.

There’s an alternative: Hearthstone has a debug log option that causes the game to write a bunch of debug info to a file. It’s not really a game log, it’s mostly about memory management, etc. But it has enough data to reconstruct the game. On the Mac the logging is enabled with ~/Library/Preferences/Blizzard/Hearthstone/log.config and the log ends up in ~/Library/Logs/Unity/Player.log. It’s a big file, 1 megabyte after a single game, but the Blizzard launcher seems to clean it up every launch.

There’s a few tracker apps that use this logging and are open source. I tried TrackOBot and it’s nice, runs on Mac just fine. There’s also Hearthstone Deck Tracker which is way fancier but is Windows only.

The drawback is that the log doesn’t record everything. Trackobot can see what cards you’ve played, for instance, but not what your whole deck is. And it doesn’t capture actions like which cards attacked what. But for high level stats of “I tend to win with Warlock” it’s not bad.

Ubuntu 14.04: converting m4a audio to mp3

I want to convert a bunch of .m4a files that youtube-dl created to MP3 files. The files are audio only, 128kbps, AAC encoding. They play in VLC but a lot of AAC-supporting software like Sonos can’t read the .m4a files and I don’t care why, just want to convert it to the shitty 18 year old format that works everywhere.

First challenge is that ffmpeg has completely disappeared from Ubuntu 14.04. It’s been replaced with avconv. There was some nerd fight and a fork, no idea what or why or which fork is better. Sigh. Ubuntu went with the fork avtools, so I will too. (There is an ffmpeg PPA). “ffmpeg” is now “avconv”, and “ffprobe” is now “avprobe”.

sudo apt-get install libav-tools

for f in *; do
  avconv -i "$f" -metadata album="Album Title" "${f%.m4a}".mp3;
done

I realize this is all very basic, but every time I try to do any AV codec stuff I get very confused. I wasted a lot of time playing with quality options before deciding avconv was choosing a reasonable setting that I couldn’t really override, probably based on the source material. (Although apparently there’s at least two MP3 codecs buried in there being autoselected.) Also I tried using “-threads auto” to speed things up but no luck, maybe the MP3 encoder is single threaded or maybe it’s all IO bound anyway. It’s re-encoding about a megabyte a second, fast enough for my small job. GNU parallel is another solution here.

Sadly the source tracks have no useful metadata in them like song title or artist. I did throw in an album name at least.

Just un-opensourced something

I’m a big fan of open source and have been for at least 24 years. Today is the first time I ever un-open-sourced something. Logs of Lag, my League of Legends analysis tool.

It wasn’t a good candidate for open source. It’s a free web service I run, not software people install locally. And I don’t expect any useful contributions from drive-by programmers. Also I’m a little worried someone could take all my code and legally clone the site entirely, maybe in Chinese or Korean. That’d make me sad; I’d rather be the one running that service. Why give away my work without any expectation of getting something in return?

I did get a little help once, another LoL developer named Masch helped me figure out a scroll overflow problem. Then again he could have done that just viewing the page source. I’m happy sharing how the thing works with people if they can learn from it, but don’t see any need to give a blanket license to use all the code to set up a competing service.

There’s some reusable / shareable library code in the middle of my thing, the actual netlog parser, I’d be glad to make that open source if anyone asks.

all my music albums sorted by date

Useful bit of shell for looking at my music library by age acquired:

find . -type d -links 2 -exec \
  stat -c "%Y %y %n" {} \;    \
| sort -n                     \
| cut -c 12-22,50-

The find shows all leaf directories. The stat command prints the file modified time for the directory in two formats. Sort by timestamp, then use cut to extract just the date and pathname from stat.

The find -links is said not to work in the MacOS bizarro filesystem. Works fine on Linux, didn’t test through an SMB mount.

I’m using the directory mtime, the good ol’ Posix way to sort of tell how old a directory is. Or rather, last time a file was added/removed from the directory (IIRC). The 20+ year legacy of Unix not really supporting creation times on files reliably. (Quick, what’s the difference between mtime and ctime? And why is atime such a bad idea for web servers?) ext4fs has a new attribute called “birth time” that looks useful, but the userspace tools still don’t know how to read it.

Calistore 0.8 quickstart (Ubuntu) and thoughts

I’ve been curious about Camlistore for awhile, a project from a lot of smart people like Brad Fitzpatrick and Aaron Boodman and the like. It’s a content addressable filestore “for life”, a sort of Dropbox / Lifestreams kind of thing for storing all your personal data. Ambitious and necessary. My immediate use case is as a replacement for the horrible Unison and rsync tricks I do with a USB drive to keep two Macs sort of in sync.

They’re up at 0.8 now and have fewer dire warnings about how it’s not ready for users yet. I just asked Brad F and he said “I’d wait a bit for 0.9.”, which I good-naturedly take to mean “sure 0.8 is worth looking at” :-) Quick start on getting it going in Ubuntu, based on the Camlistore docs

  1. Install the Go Language. Don’t bother looking for an APT repository, the official one is out of date and the third party PPAs are all abandoned. Just install straight from the golang site.
  2. Download and build Camlistore from the github repo
  3. Run the camlistore daemon. It should advise there’s a UI on http://localhost:3179/ui/
  4. I had a problem with the UI requiring a basic auth HTTP login; maybe the “allow localhost” stuff was fooled by my ssh port forwarding. So I edited ~/.config/camlistore/server-config.json to add a username and password

I also watched Brad’s video from Feb 2014 to FOSDEM. Nice overview and some demos.

The main takeaway is the way Camlistore works is a blob server + a metadata indexing system. The blob server is a simple content addressable file system, keeps track of syncing raw data whose only name is the SHA1 hash of the data. Then there’s other metadata blobs which contain things like “blob with SHA1 f392... is actually IMG_0902.jpg, a 3000x2000 JPEG with this creation data”. The problem with content addressable file systems is that the moment you change the file it’s basically a brand new file. They have a concept of “permanode” that provides permanent identity for things independent of their content. It sounds like a lot of work is put into the indexer system to make it a usable filesystem.

Speaking of usable, the main UI they show off is a Web UI. Fancy real time updating searches. Demo was managing a bag of phonecam images. There’s also a FUSE filesystem that in the demo seemed very slow because it was syncing to a remote server. (Slow, like “touch foo” took 5+ seconds.) Not sure if there’s a faster way to sync to a local server, then have it sync those updates to the remote server. Seems like you’d have a consistency problem for the metadata on permanodes. Maybe they rely on timestamps to sort out a merge?

There was also a quick demo of “thirdleg”, a sync from one store to another through a third thing, like a portable drive you’d carry from A to B. That’s exactly what I need for my use-case above, but I’m not sure if I’d want to rely on FUSE to be my filesystem for actually using my synced files.

My main takeaway is that they have a pretty good take at a low level distributed data store suitable as a sort of synced remote filesystem. I was a little less convinced about the applications demoed, like that Camlistore will end up being most useful as an underlying layer for something and we haven’t quite seen the apps that use it yet. For near term usefulness the key thing is probably how responsive that FUSE file system is. Need to try it out.

krebsonsecurity as malware domain

I’ve switched Chrome ad blockers to µBlock, which claims to be lighter weight than AdBlock and AdBlockPlus. Also the author is a slightly cranky open source guy who refuses to even take donations, and I like that. So far my only complaint is a few pages don’t load well and a couple of ecommerce things failed unless I disabled it.

Just tracked down one failure: http://krebsonsecurity.com/2014/10/chip-pin-vs-chip-signature/ displays as plain text, no CSS or Javascript or anything. Turns out the entire krebsonsecurity.com domain is blocked by the “domainsonly” list from DNS-BH Malware Domains. Which is sort of hilarious given Krebs’ work publishing about malware. I can’t tell if that’s a bug in the list, that Krebs was actually compromised at some point, or if it’s just some pissing match between security nerds. I think the last explanation is most likely, Krebs is often the focus of strong opinions. If so that’s stupid and annoying though; these black hole lists should only be applied very sparingly. FWIW the ban goes back to 2010.

µBlock’s tools for understanding stuff aren’t bad. If you right click the icon and choose “Options”, there’s a “Statistics” tab where you can reload a page and see what was blocked and by which rules. It doesn’t show which ruleset contains the rule though, so you have to hunt for that.

I think it’s hilarious that Chrome’s New Tab page blocks 3 requests, all matching the rule google.*/gen_204?. Tracking images? The new tab page loads like 15 other resources from Google that are allowed.

Update: the Krebs list was commented out with a datestamp of 2014-10-29, two days before I wrote this blog post.

Did MacOS 10.9.5 break SMB again?

I had Samba working more or less right between a Linux server and a Mac client. But recently all the files are showing up as permission 700 on the mac client, creating symlinks makes bogus files on the server, etc.

Unfortunately I don’t know what broke it. I upgraded Ubuntu 12.04 to 14.04 and kept my old smb.conf file. I also updated to MacOS 10.9.5. Either could have broken it.

On the Linux box, I started with a clean fresh default config file from 14.04 and just added some minimal stuff for myself. The old config file had some cruft like “map archive” that may or may not have been good. I mean, it used to work, but who knows. Anyway the new config file looks correct, but with Samba you can never be sure.

On the Mac, 10.9.5 includes an ominous patch note “improves the reliability of accessing files located on an SMB server.” Given how badly Apple has broken their Samba client in the past, I don’t trust any changes.

My work around now is to mount the fileshare as “cifs://ub/” on the Mac instead of “smb://ub/”. Apparently this forces MacOS to use an earlier protocol and implementation that’s not as broken in Mavericks.

Is my host secure in IPv6?

I want to verify that my Ubuntu 14.04 box is secure in IPv6 space. netstat shows various things are listening on IPv6 ports. Do I have a publically reachable IPv6 address? I think not. ifconfig shows this IPv6 address:

inet6 addr: fe80::52e5:49ff:feae:3a13/64 Scope:Link

ServerFault has a useful explanation. The Scope:Link means Link-local address, something explicitly not routed and only reachable on the local Ethernet segment. This means that these servers are reachable by anything else on that same Ethernet segment, which might mean other servers in the rack in my colo. I believe all IPv6 address that start with fe80:: are link scope.

There’s a bunch of online services that will test ports or do nmap for you for IPv6.

Windows is worse than MacOS

I bitch about MacOS a lot, complaining about the rough edges in what is mostly a good product. But MacOS really is bad at one thing: desktop gaming. Some times I’m tempted to switch back to Windows just so I can play game. This week I was desperate to play Civilization: Beyond Earth before the Mac port is finished. So I booted my Bootcamp partition into Windows for the first time in two years.

Wow, what a terrible experience. Pretty much all the badness centers on software management, installs and upgrades. I was prepared for the initial thing to take forever; it was a two year old Windows 7 image, after all. Some 60+ updates and a few reboots later and all was set up. That wasn’t so bad really.

What was bad was installing software with Steam. In particular, the way you have to “install VC redist”. Steam makes the wise choice to require a separate install for every game, basically the 2014 solution to the 1995 problem of DLL hell. But the installers are fucking ridiculous. It takes 30+ seconds to do the install. What the hell is it doing? Copy a few files, maybe update a registry key or two, and you should be done. And for some reason I had to install like 15 of these for Steam the first time, then another 4 for Civ:BE.

The Bootcamp experience is not good either. The display drivers don’t work perfectly, for instance the sleep mode doesn’t shut the back light off. And I’m scared to try updating the 3 year old driver. You can’t use the vendor display driver, you have to use Apple’s, and all Apple ships is one giant install disc every once in awhile. Two, actually, you have to pick the release based on knowing what model iMac you own. Only iMac’s don’t have model numbers, so you have to remember the year you bought the thing instead.

Windows itself is still mostly, well, Windows. It’s funny how much I’m used to the Mac way of doing things now. I miss my menu bar. I can never tell if Chrome is running and just has no windows, or what. I even hacked the registry to enable reverse mouse wheel. And the stupid system is still prompting me for urgent reboots by switching me out of my full screen game, interrupting me with a popup dialog.

sshuttle

I took a quick look at sshuttle, a poor man’s VPN. It creates an ssh tunnel to any Linux host you can ssh too, then munges your OS to route most, but not all, traffic through the tunnel.

I’m confused about how it works. On my Mac I couldn’t find any evidence of it in ifconfig or the routing tables. It does set some ipfw rules, and more if I enable DNS as well. Can ipfw manipulate traffic in this way? There’s some more commentary on this 4 year old Hacker News discussion.

The big drawback is it only handles TCP, with an option to also handle DNS traffic. But not arbitrary UDP or all IP. I think for many practical things that doesn’t matter, but it is a drawback.

The nice thing is it’s super easy to set up and doesn’t require any server infrastructure. It’s a clever hack. Clients work on MacOS and Linux, at least.

13936 Go games

Inspired by a visualization of which chess pieces die in aggregate games (see on Reddit today) I looked at 13,936 Go games and made a simple map of where people place stones. HSL scale linearly proportional to number of moves, the text is the percentage of games where someone placed a stone on that spot. (A bit fudged; didn’t account for how some games have people placing a stone more than once in the same spot.)

Screen Shot 2014-10-20 at 5.06.38 PM

No big surprises, but it’s nice to do little projects like this.

Data storage for Logs of Lag

My little Logs of Lag project is doing pretty well, I need to create some sort of more serious datastore for it. It’s a small service, at most 1000 logfiles uploaded a day (each about 20k per file), but over time that adds up. Right now my data store is “put a file with a random name in a directory”. And I have no database or analysis of all the files.

The high-end solution would be to start putting data files in AWS and create a local Postgres database for aggregate statistics. I know how to build this. But that adds two big moving parts, one of which I have to maintain myself. And it’s kind of overkill for the relatively small amount of traffic I have (and am likely to ever have).

So I’m thinking now just to keep storing the files themselves on the filesystem, but spread it out over a bunch of directories so I don’t have a single giant directory. The Linux kernel no longer chokes on lots of files but shell tools are still a PITA. File names are base 64 encoded things so maybe hash by the first two characters, for 4096 directories. That’ll carry me to about 16M log files (4096 files per directory), good enough. The file system only has 60M inodes available anyway. (Unfortunately - is a valid leading character in the filenames. Oops.)

I definitely want a database, I’m curious about aggregate stats. I’m thinking of keeping this all asynchronous. When a user uploads a log it doesn’t go straight to the database, just written to a file. Then a cron job picks up the files and does the postprocessing. That works fine as long as the database data still isn’t needed by the user application. It’s not right now, in fact the server isn’t needed at all, the user gets 95% of the value solely in client side javascript.

What database? I should probably bite the bullet and just use Postgres, but I hate having to manage daemons. I wonder if SQLite is sufficient? It supports concurrent read access but only one writer at a time, and the writer blocks readers “for a few milliseconds”. I think that constraint isn’t a problem for me. Right now I’m tempted to go for that, just for the fun of doing something new.

Another problem to solve is the log parsing code. Right now logs are parsed by the client browser, in Javascript, and the client sends both the raw log text file and the parsed data (as JSON) to my server. (The server is a Python CGI which just writes the files to disk.) I’d like to retain that client-only capability, but also start parsing logs on my server. I don’t really want to maintain a second parser in Python.

So maybe I write the server parser / database stuff in Node to reuse the Javascript parser. Here’s MapBox’s node-sqlite. There’s zero need for me to make these scripts asynchronous, so the Node paradigm is not a great match, but I can certainly make it work.

(Naively I’d thought Node startup times would be bad, like Java, but that’s not true. From Node v0.10 on Ubuntu: “NODE_PATH=/tmp time node -e 1” is about 27ms, compare Python 15ms. Not enough difference to matter. strace shows Node makes about 230 system calls for an empty script (it’s nondeterministic!), compare Python’s 883.

ubuntu 14.04, udev, ethernet

After 10 years of fiddling with remote servers, I finally killed one so I couldn’t access it on reboot. The system came up fine but not the network. The nice remote admin logged in and found that the Ethernet device was now named /dev/p4p1 and the config files were expecting /dev/eth0. He updated the config and it works, for now. I’m scared to reboot again since I don’t understand what caused it to change in the first place.

tl;dr: installing biosdevname causes devices to be renamed at boot.

Summary: I installed biosdevname and I think that caused my ethernet device to get a different name after reboot. A fresh Ubuntu 14.04 system uses biosdevname to give Ethernet devices names like /dev/p4p1. These names are based on the physical location of the adapter on the PCI bus. An old Ubuntu system upgraded to 14.04 may not install biosdevname and instead use older working names like /dev/eth0 that are configured by MAC address in /etc/udev/rules.d/70-persistent-net.rules.

Some detailed notes on what may have broken it:

  • The system started as Ubuntu 10.10, I did two do-release-upgrades to bring it to 14.04. After installing 14.04 it booted correctly at least once, configured as /dev/eth0 for ethernet. Now it wants /dev/p4p1
  • After the working boot I installed a few packages that I regret installing. Specifically biosdevname libsystemd-daemon0 systemd-shim systemd-services discover linux-image-3.13.0-36-generic.
  • I removed the 3-13.0-36 kernel and then had to do some awkward stuff to fix grub to use the linux-image-3.13.0-37-generic I already had. I think I got that right.
  • I don’t think the systemd packages would cause any problems, but I don’t know for sure. I don’t think I’m running systemd as a whole.
  • I’m not sure what discover does. My hope is it’s an install-time thing only.
  • biosdevname’s whole job is to give names to devices, so it seems a likely troublemaker. One theory is that the mere presence of it being installed alters the boot methods of Ubuntu in some way. But that’s a total guess. This forum post gives some credence to things.
  • /proc/cmdline says
    BOOT_IMAGE=/vmlinuz-3.13.0-37-generic root=UUID=e7833d2a-17a4-4598-95e2-65d354589db9 ro quiet splash

Some notes on how it’s supposed to work:

  • /etc/udev/rules.d/70-persistent-net.rules is supposed to give a persistent name to the device. Mine seems to be saying “call this eth0”. That may be a legacy from the 10.10 or 12.04 history of the system, and was apparently working until yesterday
  • I have another system that began life as ubuntu 14.04. Its ethernet is /dev/p2p1. It has no files in /etc/udev/rules.d
  • My system appears to be booting with Upstart, not systemd. (PID 1 is init, not systemd). Details on systemd and Ubuntu
  • These Arch Linux notes on the upgrade to the new persistent naming scheme are interesting. Also these systemd docs. But since I’m not using systemd, they are probably not relevant.
  • This GenToo doc on udev upgrades is also useful.
  • Here’s an Ubuntu bug saying the 14.04 docs have not been updated to reflect that 70-persistent-net.rules is no longer used. Also here
  • biosdevname installs /lib/udev/rules.d/71-biosdevname.rules which may override that 70-persistent-net.rules thing.
  • Apparently the kernel has a command line parameter biosdevname=0 to disable renaming. (net.ifnames=0 in Fedora). 71-biosdevname.rules also can be edited to do that.

After 2+ hours of reading I convinced myself it was safe to reboot. It was! I removed the /etc/udev/rules.d/70-persistent-net.rules file that was effectively being ignored after biosdevname was installed.

I filed a bug: https://bugs.launchpad.net/ubuntu/+source/biosdevname/+bug/1382600

Related: bless Arch Linux. I’ve never run it, but their incredibly detailed Wiki documentation on how Linux systems work is so useful. Sometimes you have to go to the low level tools manufacturers to understand how something works.

Notes on setting up a new Ubuntu 14.04 box

I’ve now recovered from my server hardware failure on Saturday. I can’t say enough good things about my remote rsnapshot setup. I’d kind of forgotten that backup even was running and it totally saved my ass. The hard drive had failed, the system wouldn’t reboot, would have been a nightmare getting it back. And while I don’t have any essential data on the remote server I do have a bunch of logsoflag logs I’d hate to have lost. Not to mention the server setup at all.

I ordered a new machine and set up Ubuntu 14.04 on it. I have no automation for building these servers, the overhead is hard. Couldn’t even easily import crap over from my backup of the Ubuntu 12.04 box, too much has changed like the shift to Apache 2.4.

Here’s a dump of the journal I kept as I set up the new server, the steps I took. Nowhere near complete.

Change root password and reboot
Set hostname, reboot
Edit /etc/network/interfaces to use Google DNS. “ifdown p2p1; ifup p2p1” and hold breath.
Edit /etc/default/rcS to set FSCKFIX=yes
Partition the extra disk, make file system, add to fstab
Create user nelson, add nelson to sudoers, also to group sudo.
Restore /home files from backup, put /home/nelson in order

Install unattended-upgrades
Install mg git gcc make munin nmap rtorrent screen mtr traceroute zip unzip curl optipng graphicsmagick gawk libimage-size-perl ntp
Install munin munin-node sensors
Install postfix bsd-mailx

Set up remote rsnapshot

Install apache2
enable a lot of mods
reconfigure deflate to not be stupid

http://nelsonslog.wordpress.com/2011/03/13/gzip-encoding-chrome-dev-tools-bug/

apache2 2.4 auth changes http://httpd.apache.org/docs/2.4/upgrading.html
set up backups

Set up web sites

Restore /var/www/* from backups
Reinstall sites in /etc/sites-available/* and enable
/etc/logrotate.d/apache2

Restore user contrabs from /var/spool/cron

Some notes from old setups:

http://nelsonslog.wordpress.com/2012/01/07/ubuntu-server-notes-from-an-old-debian-user/

http://www.somebits.com/weblog/tech/blosxom/server-migration.html

Apache 2.4 security stuff

My new server setup has mostly gone well, but I got tripped up by an error
authz_core client denied by server configuration

Turns out this is a change made between Apache 2.2 and 2.4. It’s reasonably well documented by Apache itself and this Stack Overflow post goes into more detail.

Long story short, for directories outside /var/www where I had some stuff stashed to load (namely CGI scripts), I had to Require all granted in Directory blocks for those oddball directories. I guess Apache moved to a “not allowed by default” model, which makes a lot of sense from a safety point of view.

Note that Munin in Ubuntu 14.04 has Apache 2.2 style config files, despite Apache 2.4 now being the default Ubuntu server. They have a bug tracking this.

Apache optimization still too hard

Setting up my new server, I’m struck by a few things.

  • Ubuntu doesn’t install mod_deflate at all by default
  • The default mod_deflate configuration is very conservative, effectively only compressing HTML. I replace it with a config which says “compress everything but GIF, JPG, MP3, that kind of thing”. Apparently it breaks IE6 or something to compress Javascript or JSON or the like. Who gives a shit?
  • I have no idea what, if any caching Ubuntu HTTPD does by default
  • I don’t even know how to test it any more. Chrome’s developer tool audit suggests stuff is being marked cacheable for 3600 seconds, which it complaints is “too short” but actually as default policies go, isn’t terrible

Hitting reload or Cmd-R on http://logsoflag.com/#8guI7GZ2OhU causes Chrome to reload everything. Hitting return in the location bar or pasting it in causes Chrome to load most things from cache, only loading the page itself and the JSON blob in the AJAX from cache. I don’t know if Chrome is being strictly standards-compliant or is a bit extra aggressive in trying to load things from cache.

I feel like I used to understand HTTP caching a lot better, but it’s been a couple of years since I looked closely at what was being cached and how. I also seem to remember there were more tools online that would load a page and give you advice on how to better optimize performance. Like there used to be a server hosted variant of YSlow, right? All I know to use now is Chrome’s developer tools in the browser.

Logs of Lag summary stats

My Logs of Lag tool now has collected some 25,000+ logfiles. It’s a heavily biased sample: people mostly bring logs to my site if they have network trouble, but some stats nonetheless. Numbers are the average of each stat, with SD in parentheses

  • Best ping: 85ms (153)
  • Median ping: 97ms (389)
  • Packets lost / minute: 8 (120)
  • Game length: 28 minutes (13 minutes)

Would be nice to publish something from this data. I sure wish I had a way to get a representative sample. I wonder if I can convince some group of players to just upload their logs, whether they have problems or no. Would still be biased but maybe useful.

Here’s the kludgey script I use to generate a CSV file of all the results, which I can then feed to my 20 year old C program that calculates averages and standard deviations. Very quick and dirty, I should tackle a project of handling user data as more than flat JSON files.

for f in *; do
  ~/lol-netlog/logToJson.js < $f | 
  jq '"\(.matchLength),\(.packetsLost),\(.packetsLost/.matchLength),\(.medianPing),\(.bestPing)"'
; done > /tmp/logs.csv

Full window maps

I like making slippy maps that fill the browser window. Every time I do this, I forget how to do it right. It’s easy to screw up and make a map that causes the window to have a vertical scrollbar, or that doesn’t fill the whole window. Firefox used to have a different CSS model which caused some of my maps to only fill the upper left of the window, like 2 map tiles. Chrome recently changed and now my maps are broken that way in Chrome. Here’s a screenshot of how it looks:

Screen Shot 2014-09-27 at 11.10.06 AM

So how to fix it? The notes below are only testing desktop Chrome 37.0.2062.124 on a Mac. This d3noob block has a full window Leaflet map that works well and is simple. The crux of it is

body { padding: 0; margin: 0; }
html, body, #map { height: 100%; width: 100%; }

<body>
  <div id="map"></div>
</body>

If you don’t set the margin on the body to 0, then Chrome’s default is an 8 pixel margin on the entire body and you end up with scrollbars because the 100% map now hangs 8 pixels off the window. The padding: 0 may not be necessary; Chrome’s default seems to be no padding on the body already. But it’s harmless and seems like a good idea for a full reset.

It’s also common to see overflow: hidden on the body, to suppress all scrollbars. I think that’s also harmless and even possibly a good idea, but is not strictly necessary. It also causes problems for other full screen webapps that aren’t maps. Logs of Lag has a “natural” height of about 800px. I used to set overflow: hidden to work around a scrollbar bug, but then that broke the case where the window is shorter than 800px and you really do want a scrollbar. Not something that’s likely to come up in a map, but maybe in other full window app contexts.

The height: 100% must be set on all of html, body, map. If it’s not set, then the height calculates to 0 and you end up with nothing displayed. The width: 100% seems unnecessary, you can remove it entirely and it still renders full width. But it seems harmless.

I wasn’t able to reproduce the “show only two tiles” brokenness in my screenshot above in Leaflet with a simple example of a page with just a map div. It may be not possible any more, not sure.

The bug is showing up for me with my Polymaps maps though, even if I set all the widths and heights and stuff as described above. Turns out for Polymaps you also have to set the size of the SVG that you put inside your map div. I did this by hacking in a svg { width: 100%; height: 100%; } in my stylesheet, which obviously only works if you have no other SVG elements on the page. Since Polymaps is long since EOL, there’s not much point trying to figure out anything better.

Services I host, setting up a new server

I have a server in a datacenter in Kansas. Or rather, did: the hardware went boom. Fortunately I have backups, unfortunately I have to set up again a bunch of hand-crafted services and crap I put there. I greatly simplified things when I set this server up, back in March 2012, but I still have to install and tweak a bunch of stuff by hand.I think all the services I run publicly come via port 80 and Apache. Best as I can tell here’s what I care about:

  • logsoflag.com: Apache virtual host with some CGI writing to local directories.
  • windhistory.com: Apache virtual host, nothing but static files.
  • somebits weblog: Blosxom CGI
  • somebits web server: random stuff, mostly (all?) static files.
  • rivers map: nginx, Tilestache, GUnicorn, Postgres, oh god so many things.

It may be a few days before the replacement is online. I’m trying to move logsoflag and windhistory to my home DSL system as a stopgap for the weekend. I’ll wait for the new server to set up the somebits blog, etc. I may not bother with the river and airport maps at all. They’re neat, and somewhat easy to get running again, but it’s a lot of extra servers to manage for not a lot of benefit.

I sure wish system automation tools were better; I’d love to script all this setup so I can migrate more easily. But Chef, Puppet, and Docker are all a fair amount of work to set up. The other option is a virtual image snapshot I can just clone, either a Linux VM based thing or Vagrant or something. But that’s wonky. It would not be inappropriate for the river project though.

Update: I’ve gotten two recommendations for Ansible as a lightweight system configuration tool. It looks basically like a sane wrapper around scripts that ssh to a machine and install packages, copy files, etc. YAML declarative “playbooks” define how to set up services. (Very simple example of running it.). I’d definitely look to use this if I were setting up machines regularly. May not bother for one single system.

I managed to get all the web stuff except the river map working on my home server on cable modem. It only took a couple of hours. So maybe I don’t need to sweat over the server setup too much. I’ve got the Apache virtual host stuff configured well enough now that it’s pretty painless.

Sonos hacking

I love my Sonos devices, they are reliable and sound great. I’m also curious how they work, and I do wish there were better diagnostics for media files that refuse to play.

Turns out the Sonos has an admin web interface on port 1400. A URL like http://192.168.0.20:1400/support/review brings up a bunch of debug data; substitute the IP address for one of your Sonos devices. It loads slowly. Also appears to be centralized, no need to find the right device first.

I also found my way to SoCo, an open source hacker interface to the Sonos. Command line control over playing, queuing, etc. Neat stuff and seems to work.

What I haven’t found is any way to get an error message why a track won’t play :-(

I thought the Network Matrix was interesting. Screenshot below. STP presumably refers to spanning tree. Sonos’ core magic is the way music plays completely correctly, synchronized, in an unmanaged wireless network. Presumably this is the status of the magic that makes that work.

Screen Shot 2014-09-26 at 10.58.02 AM

SF bandwidth usage before and after

in mid-July I switched ISPs, from sonic.net DSL with 6/1 Mbps speeds to astound.net cable with 100/5 Mbps. Best thing ever, 100 Mbps is like seeing through time. It is sometimes faster for me to download something over the Internet than to get it off my LAN, which is just ridiculous.

Getting a higher speed doesn’t seem to have changed my usage. I average about 150GB a month both before and after. Here’s a table of usage for the past few months

Date Download Upload Total
2014-09 133.03 GB 7.13 GB 140.17 GB
2014-08 102.84 GB 5.22 GB 108.06 GB
2014-07 102.81 GB 8.29 GB 111.11 GB
2014-06 144.46 GB 11.42 GB 155.88 GB
2014-05 136.55 GB 11.61 GB 148.15 GB

Compare to bandwidth usage in Grass Valley, with a 1/0.1 Mbps link, where I average 15 GB a month. The big difference between the two houses is totally behavioral. I deliberately only download video, stream video, update Steam and iOS and stuff in San Francisco with the fast link.

VPN server notes

I need a VPN server for when I’m travelling. I used to use sonic.net’s great service, but now that I switched ISPs I need my own mostly to get IP tunnelling to circumvent stupid hotel networks. Options:

  • Cloak. Their service works well, particularly the iOS client. It’s cheap ($10/mo for unlimited bandwidth). The drawback is that a lot of their VPN server endpoints are on IP blacklists for websites, which is just terrible.
  • Tomato firmware. Run this at home and use my cable modem service as a VPN. Not ideal, but Tomato has a built-in service that looks easy to configure.
  • PPTPD, as documented here. Apparently pretty easy but a bit kludgey, not clear how secure it is.
  • OpenVPN, maybe as automated here. I think this is the more serious option but I’m warned it’s hard to get working right.

The VPN server and client world is terribly confusing and usability is awful. I’m hoping I can just skate through with Cloak for my light usage.

IP address is not identity

I’m using Cloak as a VPN provider while travelling. Great product, excellent MacOS VPN client. Unfortunately they terminate your VPN links at random servers in VPS clouds like Linode. And those IP addresses are blocked by sites like Yelp and Pinterest. Pinterest goes so far to say as “there’s a bot in your network”, which really means “we blocked that block of IP addresses because someone once ran a bot there”.

Stupid.

Apple hates signals

Why do so many MacOS apps fail to quit in response to a simple kill command? softwareupdated, mtmd, I think ocspd and maybe even mdsworker. kill doesn’t kill them, have to kill -9. That doesn’t help anything.

Today’s mess: I deleted 20 old files from my Downloads folder. So now Time Machine is insisting on pegging one CPU at 100% and running the battery down, preparing another backup or something. The backup drive isn’t plugged in, this is the local backup thing which I generally like when it’s not being stupid. Even better; after the kill -9 launchd spawned the process again. Of course.

 

MacOS file sharing and CPU usage

Why does MacOS file sharing take so much CPU? I’m rsyncing 30GB of files from one Mac to another. Using MacOS file sharing, 10.9.4 server and 10.9.2 client. The client is a MacBook Air and the fan is whirring away. Some kernel_task associated with the copy is taking 50% of one CPU; the rsync processes are taking another 13%. It’s not awful, but that’s a shitton of CPU for doing something that should be low impact. The iMac server is using 15% of a CPU to serve the files too.

Automatic Dashboard

JeffN was kind enough to point out the new Automatic Dashboard. Automatic is a gizmo that plugs into your car service data port and relays data to an iPhone app. It records fuel usage, speed, GPS track, etc. Neat data, but the presentation has been really limited so far to a mobile-only experience. Well now they have a webapp and it looks great.

The map view is most interesting to me. All built using MapBox.js. The data for it is stored in URLs like https://api.automatic.com/v1/trips?page=1&per_page=100&start=1407222000000&end=1409756534672. Requires authentication, my eyebrows slightly raised that my user ID isn’t in the URL: implicit by authentication.

trips returns an array; one example element below. I’ve zeroed some of the IDs. The path data is most interesting to me. It looks to be pre-encoded as a polyline, which the javascript renders in SVG. It doesn’t load more detailed data when you zoom in, I think this is it. A bit of a hassle to reverse engineer this to normal lat/lon data, but it’s probably all some standard MapBox data format so should be possible. Update: apparently it’s the Google Maps polyline format.

The graphs are nice. They’re SVG and I see nvd3 is loaded in the page, so I assume that’s what they’re using.

{
  &amp;quot;vehicle&amp;quot;: {
    &amp;quot;uri&amp;quot;: &amp;quot;https://api.automatic.com/v1/vehicles/C_0000000000000000&amp;quot;,
    &amp;quot;color&amp;quot;: &amp;quot;&amp;quot;,
    &amp;quot;id&amp;quot;: &amp;quot;C_0000000000000000&amp;quot;,
    &amp;quot;display_name&amp;quot;: &amp;quot;Audi A6 Quattro&amp;quot;,
    &amp;quot;year&amp;quot;: 2005,
    &amp;quot;model&amp;quot;: &amp;quot;A6 Quattro&amp;quot;,
    &amp;quot;make&amp;quot;: &amp;quot;Audi&amp;quot;
  },
  &amp;quot;score&amp;quot;: {
    &amp;quot;score2&amp;quot;: 50,
    &amp;quot;score1&amp;quot;: 50
  },
  &amp;quot;drive_events&amp;quot;: [],
  &amp;quot;average_mpg&amp;quot;: 20.803669567728743,
  &amp;quot;uri&amp;quot;: &amp;quot;https://api.automatic.com/v1/trips/T_0000000000000000&amp;quot;,
  &amp;quot;end_time_zone&amp;quot;: &amp;quot;America/Los_Angeles&amp;quot;,
  &amp;quot;duration_over_75_s&amp;quot;: 0,
  &amp;quot;duration_over_80_s&amp;quot;: 0,
  &amp;quot;path&amp;quot;: &amp;quot;karlFrrzaVCf@Er@c@Gc@IcAQmAU}Bk@cDw@{D{@qA]oAe@iAo@}@_@]EK~Bg@pHMbBa@Kg@Wi@c@aB{Ae@a@iBsAcBiAgCsByBeBcAo@sHqEWM{Ac@kBg@cCw@_GeD_BeAw@u@mCeDoCeDq@k@e@YiAe@cCm@kA]y@k@KOkCzDu@|Aq@nBShAM~@IfAEpA?hCNxBVpBVjArAbEvCdJbAhDb@|Bj@zDP`CZlGh@~O\\hFTlBb@~CZ|A~@zDfChKb@nBh@xCZhCVjCNfCh@fZh@nSNlFBzCAtCGrDo@nLQjEIxEC~CBjBFbDHT@bD?pIGP?PC|BBlBDhAXElBc@a@iDQ]K_AAg@Fg@N[xCm@JB|ChE^zAa@J&amp;quot;,
  &amp;quot;end_location&amp;quot;: {
    &amp;quot;lon&amp;quot;: -121.0936601,
    &amp;quot;lat&amp;quot;: 38.9406032,
    &amp;quot;display_name&amp;quot;: &amp;quot;Bell Rd, Auburn, CA&amp;quot;,
    &amp;quot;name&amp;quot;: &amp;quot;2705 Bell Road, Auburn, CA 95603, USA&amp;quot;,
    &amp;quot;accuracy_m&amp;quot;: 10
  },
  &amp;quot;distance_m&amp;quot;: 6805.27783203125,
  &amp;quot;end_time&amp;quot;: 1409172044053,
  &amp;quot;start_time&amp;quot;: 1409171491960,
  &amp;quot;id&amp;quot;: &amp;quot;T_0000000000000000&amp;quot;,
  &amp;quot;duration_over_70_s&amp;quot;: 0,
  &amp;quot;fuel_cost_usd&amp;quot;: 0.753902077674866,
  &amp;quot;fuel_volume_gal&amp;quot;: 0.203262895345688,
  &amp;quot;hard_brakes&amp;quot;: 0,
  &amp;quot;hard_accels&amp;quot;: 0,
  &amp;quot;user&amp;quot;: {
    &amp;quot;id&amp;quot;: &amp;quot;00000000000000000000&amp;quot;
  },
  &amp;quot;start_location&amp;quot;: {
    &amp;quot;lat&amp;quot;: 38.9280456,
    &amp;quot;lon&amp;quot;: -121.0552683,
    &amp;quot;display_name&amp;quot;: &amp;quot;Lincoln Way, Auburn, CA&amp;quot;,
    &amp;quot;name&amp;quot;: &amp;quot;13500 Lincoln Way, Auburn, CA 95603, USA&amp;quot;,
    &amp;quot;accuracy_m&amp;quot;: 50
  },
  &amp;quot;start_time_zone&amp;quot;: &amp;quot;America/Los_Angeles&amp;quot;
}

 

Screen Shot 2014-09-03 at 8.16.43 AM

First light: WebTule

I’m working on a data exploration tool. Sort of a simplified version of GGobi, for web usage. Give it a CSV file and it lets you explore scatterplots of various columns. I did a custom version for Battlefield 4 a few months ago, now working on a generic tool.

So here’s “first light”, taking the HYG Database of stars and trying to recreate the Main Sequence diagram. It’s visibly at least a little right, once you realize the Y axis (magnitude) is inverted.

Screen Shot 2014-09-02 at 5.46.08 PM

Pie chart alternative

Pie charts are bad; they’re hard to read, particularly for small percentages. This Pornhub Insights report (SFW) has an interesting alternate type of pie chart.

pornhub-traffic-mobile2The angle of each wedge is constant, 360°/5 = 72° in this graph. It’s the radius of each wedge that conveys the data. In other words it’s basically a bar chart, but turned into a circle. That’s a nice compact layout. And it visually conveys that the numbers sum to 100%. If I measure this right the wedge radius is proportional to the square root of the value, so that the wedge area is proportional to the value. That’s more correct for visual perception. It also works well for showing a 40:1 ratio like the data above; in a linear bar chart the 1% data would only be a couple of pixels high.

I’m sure Pornhub didn’t invent this, but it’s a neat technique I haven’t picked up on before.

Update: Mike B tells me this is called a Polar Bar Chart. Or a Coxcomb chart, after no less than Florence Nightengale.

youtube-dl rate limiting bumpiness.

The results of using youtube-dl to download at 50 kbytes/second:

Screen Shot 2014-08-28 at 9.22.15 AM

Basically it uses max bandwidth for a bit, then stops. The average rate is indeed 50 kbytes/sec, but it’s 1 second of 300 kbytes/sec (max rate) followed by 6 seconds of none. Not exactly the intended effect.

I’m not clear on how much a user-space app can even do to throttle bandwidth on a TCP socket like this. I’d assumed they were stalling the pipe, only reading 60 kbytes/second, and the server is filling the pipe and something’s buffering. But that graph looks more like youtube-dl reading the whole buffer all at once, then sleeping a long time.

The code looks like it’s doing something reasonable. If I understand the main loop right, it reads block_size bytes (1024), then sleeps for a carefully calculated amount of time to maintain the rate. So it’s at least trying to read little bits in short intervals, I wonder why it’s not working? I should test it on a faster network and see if it does the same weird thing.

 

League of Legends game protocol

I continue to be interested in understanding League of Legends lag. It’s a custom UDP protocol, so the usual way of measuring TCP packet loss doesn’t work.

I realized today the game must have something like a sequence number in the protocol. Apparently the LoL protocol is based on ENet, an open source “reliable UDP library”. There’s no dissector for ENet included in Wireshark but Google searches suggest several people have written them. packet-lol also has a LoL dissector but it is a couple years old, no idea if it’s still valid.

I’ve been hanging out on Freednode ##loldev recently, a nice little IRC channel. One thing they’re working on is documenting the observer protocol on a GitHub Wiki. But apparently that’s a totally different protocol from the UDP live game, based on HTTP requests for 30 second chunks of the game as well as keyframes, etc. A fair number of third party tools use the spectator protocol, sites like riftwalk.gg are doing some great game analysis. Neat stuff, but not relevant to the lag experienced while playing the game.

Here’s a big stack of links I’ve collected relevant to LoL protocols.

netconsole

I have a headless Linux box and every time I reboot it there’s a several minute anxiety where I don’t know if it’s working or not. (I reboot only every year or so, I think fsck’s timer kicks in and it takes awhile.)

I want to see the console while its booting, without a monitor. I don’t want to fuss with serial cables. Netconsole looks like an option; kernel module that sends UDP log messages via a pre-arranged MAC address. Before the TCP/IP stack is initialized. Docs: Ubuntu, Arch, kernel.

SMART errors: living dangerously

My once-yearly look through root’s mail on my home server reveals errors from smartd

Device: /dev/sdb [SAT], 17 Offline uncorrectable sectors
Device: /dev/sdb [SAT], 17 Currently unreadable (pending) sectors

The error started 14 May 2014 10:57:07 +0000 at 5 errors, then jumped to 17 two hours later and has stayed at 17. It’s just a backup disk, so I’m going to live dangerously and see what happens. The disk is 2.5 years old and has a three year warranty.

Possibly related, rsnapshot hasn’t run cleanly in weeks and I didn’t notice because errors go to a local mail spool I never check. I should rethink that.

 

MacOS dd timings

I need to clone a 2TB USB disk on my Mac. Going to use dd. What’s the right block size?

The bigger the better, apparently, but there are diminishing returns. “bs=128k” is good; reading from USB and writing to /dev/null that gives me 38Mbytes / second, which IIRC is about the rate for a 5400 RPM disk. 16384 gives about 20Mbytes / second. The default 512 byte blocks gives 1.2Mbytes / second.

I love that the default is 30x slower than maximum. The legacy of SysV’s 512 byte disk blocks is never going to end.

$ dd if=/dev/rdisk2 of=/dev/null bs=128k count=10000 skip=1m
10000+0 records in
10000+0 records out
1310720000 bytes transferred in 34.233990 secs (38287094 bytes/sec)

Update: that was for timing disk reads. Disk writes were slower, a test copy from one USB disk to another on my iMac showed 17 MB/s, which would take 32 hours to copy a 2TB disc. I thought at first that was because writes are slow but then I remembered the iMac is USB 2.

My Linux box has USB 3 and can read the disk at 100 MB/s. Shouldn’t have trusted my memory about disk speeds! And a copy from disk to disk on my Linux box is showing 117 MB/s, or about 5 hours to do the copy. Bonus: I trust Linux not to be doing something weird behind my back with the disks.

The full 2TB copy ended up taking about 6.5 hours, for an average rate of 85 MB/s. I forget slow the end of a disk is.

1Mbps is inadequate

So there I am, playing along in League of Legends, a tense game but we might win yet if I just position Annie right and time her stuns (an exercise in counting to 4). It’s exciting and fun. Suddenly the game lags out; characters freeze, skills don’t respond, things start sliding around and teleporting. Basically unplayable, 10 seconds later suddenly I get the packet that says “you died”.

Curse and swear. Switch to the bandwidth monitor, some random IP address is taking all my bandwidth. All 1 megabit. Go to the router status page, do the OUI identification of the Mac address, see it as an iPhone. That narrows it down to 3 iPhones. During death timers I find all three and put them in airplane mode, but by then it’s too late.

1 Megabit internet is just not adequate anymore. Seems crazy to say it, but there it is. The direct cause this time is some random iPhone deciding that right then was a good time to download a software update. At full speed, of course, because throttling is not a concept that’s well implemented in TCP/IP. In San Francisco I have a 100 Mbit link that’s either faster than the server or else the download completes so quickly I don’t notice. In Grass Valley, with the 1Mbps fixed wireless (the best I can buy), nope.

The underlying problem here is the US broadband infrastructure and the FCC’s collusion with the cable/telco duopoly ensuring no investment in the captive market. Fuck them.

 

softwareupdated (MacOS sucks)

I’ve lost track of all the confusing ways MacOS updates itself. But one of them that keeps biting me is that it insists on updating iTunes. I don’t want iTunes, I’ve set it to mode 000, I don’t want to waste my limited bandwidth downloading copies of it. Sometimes a popup appears in the upper right saying “updates available Install?” and there’s no way to see what it will install. So as a sucker I click Install, and suddenly here I am downloading iTunes.

The best part of all this is there’s no way clean to cancel the update. The App Store program will show the update progress bar, but the Cancel button does nothing. Using MacOS’ excellent Activity Monitor I can see the process doing all the downloading is softwareupdated. It ignores or catches ordinary kill signals. My only option seems to be a kill -9. Awesome.

WebGL vs Shutdown (MacOS sucks)

I went to a WebGL test page that warned it might crash your machine by drawing lots of polygons. Boy it wasn’t kidding. Locked up Chrome, locked up the Mac graphical shell. I could log in via ssh and the machine was fine, not even anything spinning CPU, but couldn’t kill the Chrome processes. kill -9 did nothing. So then I rebooted. It didn’t reboot either, the best MacOS could do was to shut down sshd so I couldn’t even log into my machine.

It’s pretty awful that some Javascript can kill all of MacOS. Chrome should know better. V8 should know better. WebGL should know better. OpenGL should know better. The Mac graphical shell should know better. The Mac kernel really should know better, because you really can’t count on anything else to. All fail.

Gaming PC parts list

A friend of mine just ordered parts for a PC, using the Logical Increments lists. Here’s what he came up with.

 

Title Price Quantity Has
Cooler Master HAF X - Full Tower Computer Case with High Airflow Windowed Side Panel and USB 3.0
$159.99 1 0
Intel Core i7-4790K Processor- BX80646I74790K
$339.99 2 1
Crucial MX100 256GB SATA 2.5″ 7mm (with 9.5mm adapter) Internal Solid State Drive CT256MX100SSD1
$109.99 2 1
MSI ATX DDR3 2600 LGA 1150 Motherboards Z97-GD65 GAMING
$175.99 2 1
Noctua NH-U14S for Intel LGA 2011,1156,1155​, 1150 and AMD AM2/AM2+/AM3/3​+,FM1/2 Sockets, U Type, 6 Heatpipe,140mm CPU Cooler Cooling

Offered by Amamax (USA Seller).

$69.99 2 1
Seagate Barracuda 1 TB HDD SATA 6 Gb/s NCQ 64MB Cache 3.5-Inch Internal Bare Drive ST1000DM003
$52.92 2 1
Arctic Silver 5 Thermal Compound 3.5 Grams

Offered by LLYtech.

$7.70 1 0
EVGA GeForce GTX760 w/EVGA ACX Cooler 2GB GDDR5 256bit, Dual-Link DVI-I, DVI-D, HDMI,DP, SLI Ready Graphics Card (02G-P4-2763-K​R) Graphics Cards 02G-P4-2763-KR
$239.99 2 1
EVGA SuperNOVA 750G2 80PLUS Gold Certified ATX12V/EPS12V 750W Power Supply 220-G2-0750-XR
$112.99 1 0
G.SKILL Ares Series 16GB (2 x 8GB) 240-Pin SDRAM DDR3 1600 (PC3 12800) Desktop Memory F3-1600C10D-16​GAO

Offered by DotComFriday.

$149.99 1 0

Remote file system bad display (MacOS sucks)

Finder’s access to remote filesystems will sometimes show stale data. I’m copying a 2.5GB file to an SMB share (Linux samba). While copying I look at a folder, then click the little down arrow to open the subfolder in the window. It shows no contents, it must be an empty folder! So go to delete, and then it pauses saying “deleting 5 items”. Ha  ha, joke’s on me. Cancel the delete, try again. This time wait 3–5 seconds for the file content to list, and poof there are the files now. At least I cancelled the delete in time.

I’m not complaining that the remote filesystem is slow, particularly when a big copy is happening. No. I’m complaining that Finder is showing incorrect information.

 

Some quick ad campaign stats

I ran some simple ads to promote Logs of Lag, my League of Legends netlog parser. I’m having a hard time getting attention and thought it’d help to get a bit of paid traffic. I invested, oh, $20 in all of this, trying to bottom feed some traffic. Results after a week or two of trying:

Google Adwords

0.18% CTR. 4468 impressions, 8 clicks, $2.73

Screen Shot 2014-06-26 at 2.03.14 PM

Very bad results, particularly on the search ads. Google’s minimum bid for a relevant keyword like [league of legends lag] seems to be at least $1, and apparently Google is happier showing no ads than showing cheap ads. 4339 of the impressions were via the Display Network. Near as I can tell AdWords gives me no way to see where those ads actually displayed. Bummer.

Bing Ads

0.59% CTR. 848 impressions, 5 clicks, $0.17

Straight-up clone of the Google ad campaign. But Bing Ads is quite happy to show ads for $0.10 CPC, so the good keywords I wanted got some impressions and clicks. No display ads at all; not sure if I wasn’t eligible or there was just no inventory.

Twitter Ads

Too early to tell. But my ad is a poor match for Twitter. All you can promote is a tweet, and I didn’t want to write a special ad tweet for my website. Also hard for me to imagine a Twitter user will be inspired to try my tool by a Twitter ad, particularly on a mobile device. I think Twitter Ads may be better suited for brand campaigns.

Reddit Ads

0.94% CTR, 14030 impressions, 132 clicks, $10.

Screen Shot 2014-06-26 at 2.11.33 PM

 

By far the most successful of my ads. In part because I could target it so specifically to /r/leagueoflegends, a big community. Also Reddit ads are cheap. It’s a pretty interesting ad product really, particularly the way ads become stories that get Reddit votes, comments, etc. I’m surprised it’s not better known. Reddit has a blanket $0.75 CPM rate which seems fairly cheap to me, particularly given the value of Reddit’s audience. The ad tool sure is primitive though. I’m left wondering why Reddit doesn’t pursue an ads business more aggressively.

Conclusion

Small ad campaigns are cheap. OTOH I didn’t set up any way to measure actual conversion. What I want is to get my tool in people’s minds so they remember to try it a month from now, and I’m not about to do the necessary work for such a small side project of mine. I don’t regret the $12.90 I spent though. I’d definitely go back to Reddit ads to get attention for something there, particularly if the organic way of getting Reddit attention doesn’t work out.

 

Directory symlinks (MacOS sucks)

Try this on a Mac

cd /tmp
ln -s ~/Docum <press TAB>
ln -s ~/Documents/ .
ln: ./: File exists

Trollface

 

Yes, MacOS “ln” is too stupid to understand that if something has a trailing slash you probably meant to symlink the directory with that name, not the implicit “Documents/.” name. And bash completion is just helpfully providing slashes because 99% of the time you want them when talking about directories. Of course this works fine on Linux; another legacy of MacOS being based in SysVile.

(To be fair the with/without trailing slash thing has always been ambiguous in Unix. rsync even assigns different semantics to the two names, confusing me every single time.)

 

Steam (MacOS sucks)

The Steam client on MacOS has always been terrible. I mean it’s badly designed as a product, but then also the implementation is terrible. Basically it’s 90% just showing a web page, but that’s always been slow and cranky and broken.

But today takes the cake. Because running Steam has brought my whole system to its knees. Beachball cursors, 10 second delay switching apps, 20 second delay to launch Console.app. Total trash. And as bad as Steam is, the real blame falls on MacOS for freezing because one app is badly behaved. I don’t see anything obviously wrong running top or activity monitor. Is the graphical shell single threaded or something? Steam wasn’t even doing much, just sitting there showing me a web page and downloading an update in the background.

To be fair, I think part of the problem was memory. When I killed Steam and relaunched it a bunch of memory freed up and things are better. So maybe that’s a Steam bug afterall. No Unix kernel schedules memory contention well.

 

 

ToS/DSCP byte in IP packets

Update: be sure to read comment #3 below from Dave Täht. Apparently the Bufferbloat project has made a lot of progress on good router queuing and there’s a lot for me to learn about, including fq_codel and CeroWRT.

Interesting thing in Transmission’s Bittorrent client’s docs

peer-socket-tos: String (default = “default”) Set the ​Type-Of-Service (TOS) parameter for outgoing TCP packets. Possible values are “default”, “lowcost”, “throughput”, “lowdelay” and “reliability”. The value “lowcost” is recommended if you’re using a smart router, and shouldn’t harm in any case.

The Type-of-Service byte is the second byte in an IP header. It is not widely implemented, and has a tangled history. Is it useful?

The bottom six bits are for DSCP, Differentiated Services (aka DiffServ). This allows an IP packet (or the program controlling it) to request a certain level of routing service quality. There’s various things to request; low jitter, best effort delivery, and a couple of means of defining priority classes. I don’t know how well supported these bits are, the Wikipedia entry makes it sound like it’s not entirely unknown. Linux IPTables has rules for setting DSCP classes. The Bufferbloat wiki has some discouraging notes on implementation. Windows 7 claims to support it, but looks wonky. Someone found a Comcast bug in their DSCP data that was harming download speeds.

The top two bits are used for ECN, a way for the router to signal to a TCP stack that it should slow down without actually dropping packets. I think ECN is not practically useful in today’s Internet, too many clients don’t implement it and too many routers don’t use it (or any form of queue management). But I could be wrong. /proc/sys/net/ipv4/tcp_ecn is 0 (not enabled) in my Tomato/Shibby router even though I’ve turned QoS on.

My conclusion on a quick read is these bits are not usefully deployed, too much stuff doesn’t support them. Too bad; it’s exactly what a home network router needs to cooperatively share a network. So much of TCP/IP QoS work was abandoned because it doesn’t work with hostile peering relationships. But I really do trust and control my home router and I wish it could do more to manage bandwidth.

Logs of Lag ready to go

My Logs of Lag site is ready to launch. It works well, a clean and simple way to drop a League of Legends logfile onto a web page and see some statistics.

Not sure how to properly “launch” this yet. Success would be some visibility on the League of Legends Reddit, I’ll probably post it on Monday but it’s a crapshoot of the first 15 minutes whether it gets upvotes or not. I don’t expect an amazing response, this kind of tool is really something more useful to hang around and be available for months or years when people need it.

I’m pretty happy with how the final project came together. I was worried for a long time about the visual style. I still don’t think it’s great, but adding a basic background image texture and switching the fonts from Helvetica/Arial made a big difference in making it feel “real”. And I don’t want to do the over-produced glitzy graphics thing that’s popular with most gaming sites, I find that a useless distraction.

Ideas for future features:

  • Highlight “bad” data. Ie; if the loss/second is greater than some threshold, make that show up in big angry red warning font. I want to collect some logfiles from users to see what is typical before building a classifier.
  • Parse broken logs. In particular the logfile gets wonky if the game disconnects, would be nice to parse that correctly.
  • An analyzer for a whole directory of files. This is the way lolparse.com works, presenting summary statistics for gameplay in many games. It’d be useful to characterize lag for many games as well. Totally feasible given all the work is client-side, it could be fast. A histogram showing the distribution of median ping and median packets/s loss would be a good start.

And ideas for the server:

  • Replace the Python CGI with a real server. I have a Node version but I’m not sure I like Node. Porting the CGI to Gunicorn would suffice for scaling.
  • Or.. Remove the server entirely. Just make the client Javascript upload stuff to S3.
  • Or.. commit to a real server, and add logins and user data management.

D3js mouseover tooltip

It took me three hours, but I added a mouseover tooltip to my LoL netlog graphs. It turns out there’s three ways to do this.

  1. Use svg:title or svg:text and rely on the default browser hover action to show it. Totally ghetto, but it does work.
  2. Catch mouseover events on your actual chart elements. If you bound your data sensibly, the event handler gets the datum that was bound to the element that got the event passed right to it. This works great for bar charts as long as you don’t mind the popups only showing up on the bars, not the whitespace. Not so good for line charts or other things.
  3. Add an overlay to the entire chart area you want to capture events in. Unfortunately no useful data is bound if you do this. So you have to use d3.mouse() to get the relative X,Y in pixels of the mouse position, then shove that through scale.invert() to map that back to data space. Here’s a demo of that technique. It’s a lot more work, but now you have mouse events for the whole chart area, not just the marks.

I went for option #3 and really it looks pretty great. The other tricky part is I was reading the timestamp from the X axis of my time series chart, but then finding the specific row of timeseries data that corresponds to that timestamp is not so easy. I ended up doing a linear search in my data array; not awesome, but will work OK for me.

The other half of the problem is displaying the tooltips. I ended up going with a div element with visiblity toggled by mouseenter/mouseleave. The tooltip is positioned absolutely with CSS, and the mousemove handler positions the tooltip relative to the event pageX and pageY. Important to make sure the tooltip div doesn’t grab the mouse events. I did that with positioning, but probably better to use the pointer-events CSS option.

 

Uncommon ASCII control code delimiters

So much code is worried about using “safe” delimiters, and quoting, and the like. I’m probably getting myself in trouble, but I just used a very old school ASCII delimiters in my code.

In particular I’m using ASCII 28 (File Separator), aka U+001c (Information Separator Four). This is one of the ASCII control codes for separators that’s mostly a forgotten thing. I’ve often wondered why we have CSV and TSV files instead of files delimited by ASCII 30 (Record Separator), too. That character is way, way less likely to occur in source input than a comma or a tab.

I hope I’m not getting myself into trouble somehow. My use case is the LoL netlog files, in particular I want to concatenate a JSON blob and the raw text logfile together to POST to a web server. The source data is very, very unlikely to contain any non-printable characters, including U+001c. If it does I’m screwed.

Javascript code to emit this

    var uploadText = [JSON.stringify(parsedLog),
                      '\n\u001c',
                      rawLog.substring(0, 1000000)].join('');

And Python to parse it (in a CGI)

try:
    jsonText, rawText = postdata.split(u'\u001c')
except:
    jsonText = '{&amp;amp;amp;amp;amp;amp;quot;valid&amp;amp;amp;amp;amp;amp;quot;:false}'
    rawText = postdata

Update: there’s now a draft IETF spec to use RS to separate JSON blobs to make it easier to stream-parse big wads of JSON data.

San Francisco ISP woes

I love my ISP, sonic.net. They have solid no bullshit service, great customer support, and are generally super consumer friendly. Unfortunately they are DSL over AT&T’s copper, so they are pretty hamstrung with what they can do. And I’m stuck at 7Mbps on a single line.

I tried calling them to upgrade to bonded service and it gets very expensive very quickly. Their business service is the bonded option but it’s $90/mo for what will probably be 15Mbps for me (30 if I’m lucky with line quality). And then it comes with two phone lines I don’t want for which I have to pay another $40/mo in taxes, no choice. I assume that bundling is because Sonic is making some money just for providing phone service, but who knows.

In SF we have other technology options. MonkeyBrains offers high speed wireless, which I don’t want. Comcast and Astound offer cable Internet and are promising 50Mbps or even 110Mbps for less than sonic.net wants to charge me. But Comcast is the devil. Maybe Astound is an option. Reports from friends are both have been reliable ISPs.

I called Astound. It’s $90/mo, no taxes, for 100/5 cable Internet. (That’s the price after the first year discount.) They provide service over their own coax, not sharing cable with Comcast.

 

Reconsidering Node

Having done a bit of work deploying a Node server I may not use it afterall. Things I don’t like:

  1. Lack of standard production scripts
  2. Lack of blanket error handling for servers; exceptions kill servers
  3. Difficulty preventing memory leaks in servers. Closures capture memory in complex ways and V8 isn’t always able to GC it.

These are all solvable problems, but I’m not sure I want or need to solve them for my very simple server. The main advantage I get from Node is that I can share some Javascript parsing code between the browser and the server. But I’m not sure I really need that.

Truthfully I don’t need much if any custom server code at all. Just a bucket to post data to and be able to retrieve it again. I wonder if I can do that entirely with client-side Javascript and some basic S3 API.

 

Starting a Node server in Ubuntu

My Node server sort of works and I’m ready to put it into production. I need some sort of start script. What to do? Naturally, the Node world has to reinvent everything and there’s no standard way to do this. But most docs talk about using Upstart (the Ubuntu variant of init scripts), plus monit or forever to keep the Node process running when it inevitably crashes. (Because of course, this is new tech, it’s gonna crash!).

Also some scary notes about catching exceptions globally so your server doesn’t fail simply because of a bug in one user request, but I think Express takes care of that me. Update haha joke’s on me, by default the whole server crashes if you have an unhandled error because “By the very nature of how throw works in JavaScript, there is almost never any way to safely pick up where you left off, without leaking references, or creating some other sort of undefined brittle state.” Apparenly Node domains are the way to deal with this, some notes here.

I ended up just using a trash shell script for /etc/rc.local because it’s too much bother to do it right. I wish that here in 2014 we finally had a basic simple standard way to deploy and run server scripts in production. So many solutions that are either too ad hoc (upstart) or too complex (Puppet and friends)

Some resources:

 

 

My first Node server

I rewrote this Python CGI server in to a Node.js server, or most of one. The main thing it does is accept POST content, writing it to a file and returning a generated filename. (Yes, that’s really a PUT. I know.) The Python CGI is 39 lines, the Node.js is 52 with 12 lines of NPM configuration. But then the Node version is a full server and has fancier message handling. Things I learned:

The Node community and docs are good but nowhere near as mature as Python. Also the Node philosophy is one small stable core, then you download add-on modules. Batteries not included. The core Node API is well documented. Beyond that you’re hunting through npmjs or maybe node.js modules for more.

NPM isn’t so scary. Grab a template, put your dependencies in a packages.json, run “npm install” and it will build a node_modules directory for you with all the dependencies. It’s good that’s a default tool deep in the Node chain. More info on npm.

express is a reasonable webapp framework and has a nice tutorial guide. I like the router style of specifying handlers.

node by default doesn’t do anything with POST body content, you have to install middleware to handle the input bytes. senchalabs / connect seems to be the default choice for doing fancy things like parsing JSON, etc. I just want the plain message text so the raw-body middleware middle is for me. It’s an awful lot of boilerplate to set up.

I’m gonna need a content hash; here’s a pure Javascript implementation of Murmur 128 that’s in npm as “murmurhash3js”. Hard to come by; it’s tricky doing true bit twiddling in Javascript without proper bit types. NPM turns up 10 different Murmur implentations, many of which either require native code or only implement the 32 bit hash.

 

fragments of thoughts on window.history

I’m trying to do an Ajax thing where I’m swapping views of a page based on user clicks and dropping files and stuff, but without any page navigation. A single HTML page webapp. I’ve got it sort of working just using old school manipulation of location.hash, but the back button doesn’t work.

To get the back button working, you need to listen to “popstate” events on the window. One of those fires when the user clicks back or presumably navigates their history in other ways. I’m guessing this event only exists if the browser supports pushState() and popState() functions. Ie: everything but IE 9 and older. But I’m not sure.

Apparently window.history is inconsistent across browsers. History.js is a compatibility library to try to bridge the gap. I’m trying to avoid those, but it may end up being useful.

I’ve got the tools to code up state now, but I’m still tripped up by what my application logic needs to be. Need to sit down and sketch out the control flow. Life sure was easier when the server did all this work :-)

My first Mocha test

OK I’m writing tests in Mocha now! Yay! But what a lot of boilerplate. I want to test a javascript file that works great in a browser. It’s named “lol-netlog-parse.js” and contains a single top level function named parseLolNetlog. Let’s just do a fake test for now.

require('chai').should();
var parse = require("../webapp/lol-netlog-parse")

describe('lol-netlog-parse', function() {
    describe('parseLolNetlog', function() {
        it('Should throw an error', function() {
            "foo".should.equal("bar");
        });
})});

This actually works. But only if I wrap my browser code in some require.js boilerplate to set exports. But then the exports object doesn’t exist in browsers, so I have to do extra work to provide a stub exports object in the browser so that it will still run.

It’s also 7 lines of code for a 1 line test. All test frameworks have their boilerplate, and I understand why this all helps with more complex text harnesses. Still sometimes I think Python doctest had the write idea.. The relative path in the require is a pretty ugly wart too, maybe if I knew more about Node and include paths I wouldn’t have to do that.

I’ve written this in the BDD style, where the function “suite” is named “describe” in some vague attempt at literate programming. I did this because it’s the default style Mocha wants and I don’t want to have to add the “-u” command line flag to use the TDD style. It’s very clever that the code supports 4+ different ways to write unit tests but that’s 3+ more than is necessary. One way to do things; it’s a virtue.

I’m fully embracing the BDD style and using chai’s scary Object prototype manipulation to see if I like it.

Javascript unit testing options

I want to write some Javascript unit tests. I’d hoped Node.js would be mature enough there was one clear answer from that community, but there’s not. This article was useful but two years old. Here’s some options:

  • Mocha: fancy
  • NodeUnit: simple
  • vows: d3js uses this, but I’ve seen some comments it’s not the fresh choice
  • QUnit: been around a long time, browser oriented

I tried looking at most starred modules and nodejsmodules.org to try to figure out what the cool kids were using but it was too much work.

I’ll probably use Mocha unless it seems too hard to do simple things. It seems particularly crazy that there’s not even a consensus assert module. “There’s more than one way to do things” is usually not a virtue.

 

Bad default QoS settings in Tomato/Shibby

I had a problem with the QoS settings in my new router firmware where file downloads weren’t using the full network bandwidth. Even if nothing else was trying to use the network, I was being limited to about 2/3 capacity. Finally figured out the cause: the default Inboumd Rates classified “WWW” and a bunch of other stuff to max out at 60%. I don’t think that’s an appropriate setting for home installations. The QoS should be there to give all TCP flows fair scheduling and, ideally, give important traffic higher priority. Bandwidth reservation is sort of a last resort.

The problem is the Tomato/Shibby QoS settings are very complicated. The key thing are the rate limits in the QoS/Basic Settings page, particularly Inbound for traffic coming into the router from the Internet. Here’s where I ended up:

Screen Shot 2014-05-24 at 7.53.07 AM

That setting says “all traffic classified as Service should use between 5% and 100% of the bandwidth”. The default setting for WWW was “20% to 60%” or something, or maybe that was FileXfer. Anyway, didn’t make sense. Frankly I think all of these could just be 0–100 and it’d work fine, if I understand correctly the router will still give higher classes more priority.

The other half of this is the classification and that’s gotten quite complex with 43 rules! They mostly seem reasonable to me, services like DNS and NTP are given highest “Service” priority. There’s some crazy Layer 7 classifier picking out applications like Youtube, irc, flash video, and a bunch of games. Sadly no L7 classifier for League of Legends, although given that’s UDP I’m not even sure the QoS settings can do that much.

I added some TCP rules to give my Roku device Media classification. Seems to work, I was able to reliably stream high quality video off Twitch using 25% of my bandwidth while 4 other TCP flows were downloading at max possible rate from an NNTP server.

The Tomato “View Graphs” pie charts are really useful, the pie charts for Bandwidth Distribution show current classification and flows. “Zoom graphs” is useful, it shows unused bandwidth as a white wedge.

 

MacOS finder is garbage

I’m looking at a Finder window for the folder /Applications/League of Legends.app/Contents/LOL/Logs/Network Logs. It looks like this

Screen Shot 2014-05-18 at 8.18.07 PM

Then I open a shell in that folder and run ls -l. It looks like this

Screen Shot 2014-05-18 at 8.18.16 PM

Notice how there are files from May 18 that don’t show up in Finder? Yes, the fucking Mac interface can’t even list the files in a local folder correctly. I see this garbage all the time, the Finder window caches some sort of state and doesn’t resync correctly. There’s not even a Refresh option. Perhaps in this case it’s complicated by the fact that some game is writing new files to the directory, maybe it’s using some odd API? But then that’s what the Unix kernel is for; one single creat() system call. And Apple can’t get it right.

Forcing a Finder relaunch fixes it, of course.

Fundamental stuff in MacOS is broken. It’s really awful.

 

Basic HTML5 dropping file demo

Just cooked up this demo HTML file showing how to build a web page that does something to the contents of a file that’s dropped on to it. There’s lots of approaches and tutorials for how to do this, this one is mine.

The challenge is that most of the docs I found dated back to 2010 when drag-and-drop was a bold new idea and was fraught with peril. Now it’s pretty simple and just writing the obvious code works in Chrome, Firefox, and Safari. (I hear there’s another browser but I’m unable to run it, so who cares?)

The most useful document I found while figuring this out was this MDN article. The key concept is that there’s a “drop” event in the DOM. By default that causes the browser to navigate; you override that to provide your own behavior. The FileReader API is also useful, beware that it does not work in IE 9. If I cared I’d probably stop writing my own raw code and use some jQuery plugin or other library to provide compatibility.

 

Another HTML 5 template

Can’t believe I’m doing something this mundane, but here’s a template for a new HTML 5 web document with spots already set up for CSS and Javascript in the body. Way back in 1994 I wrote an emacs mode with one major feature being starting you with a template HTML document. And here I am 20 years later still doing it. At least the doctype string got simpler.

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="utf-8">
<title>TEMPLATE</title>
<style type="text/css">

</style>
</head>

<body>
<script type="text/javascript">

</script>
</body></html>

Haskell notes

Since the Heartbleed bug, I’ve been pondering what language a library OpenSSL should be written in. C is a disaster and C++ is no better. But a component like OpenSSL needs to be buildable into a linkable library, into a .so or .a file that other projects like Apache, Python, etc can then incorporate. And most modern programming languages really don’t work well with the C linker. Javascript, Python, Ruby, Lua, Java, Go ... none of these are suitable langauges for building reusable object code libraries because they either have massive runtime libraries or else toolchains that don’t work with the linker.

Enter Haskell. My friend K.K. recommended looking at it because it’s a modern safe language and is good at linking libraries. I’m not actually going to learn Haskell now, but I did want to collect some of the links and notes he shared with me.

I’m very, very skeptical of bringing new languages into practical software engineering. But the community desperately needs a C replacement, something with safe memory access. Rust is a new effort for this but there’s a lot of work to do. D seems to stand for dead-end.

 

CORS, S3, Origin headers

Learned something new today: Amazon S3 only serves CORS headers if asked to with an Origin: header in the request.

$ curl --silent -i https://s3.amazonaws.com/metro-extracts.mapzen.com/cities.json | head -20
HTTP/1.1 200 OK
x-amz-id-2: d3m01CEUWtx5ZNomSKLJHFihaigT/YZr5B2hY0bpi+KTWvfFWmapxZlEH72yl+v1
x-amz-request-id: 613AC95DCE686F29
Date: Sun, 11 May 2014 23:42:51 GMT
Last-Modified: Sat, 10 May 2014 00:49:14 GMT
ETag: "db184f33f4774a213ff4eb6428ba243c"
Accept-Ranges: bytes
Content-Type:
Content-Length: 56589
Server: AmazonS3

$ curl --silent -H "Origin: http://some.url.com" -i https://s3.amazonaws.com/metro-extracts.mapzen.com/cities.json | head -20
HTTP/1.1 200 OK
x-amz-id-2: 9JqpSl5SOftwRTeIa2b91V+drB1WwM8QySWftj55vSy+cvdQ8RNuRWoceeZW3Gho
x-amz-request-id: 2327BBA990C7F483
Date: Sun, 11 May 2014 23:43:32 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Max-Age: 3000
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
Last-Modified: Sat, 10 May 2014 00:49:14 GMT
ETag: "db184f33f4774a213ff4eb6428ba243c"
Accept-Ranges: bytes
Content-Type:
Content-Length: 56589
Server: AmazonS3

on the idea of reusable D3 chart components

I love D3.js, it’s amazing. But one thing that bugs me is the style it encourages is to write new chart types inline in Javascript. There’s not much in the way for reusable charts, D3’s focus is on making it easier to build your own charts in Javascript. So I find myself painfully rewriting basic histograms and time series and the like. In some sense this is by design; Mike’s style is to parsimonious Javascript and making it easy to actually build charts by hand. And it’s good in that it encourages a diversity of visualizations. But sometimes you just want a simple timeseries, you know?

Of course nothing prevents people from building a chart component suite on top of D3. And lots of people have. Here’s a very quick review of looking at the project web sites for a bunch of efforts. I’m only looking at their ability to produce static visualizations. An API supporting interactions and transitions is significantly more subtle to get right.

The libraries group into two categories. Declarative libraries let you specify a chart simply with a bunch of configuration parameters, no real executable Javascript code. In general, my guess is these are great for doing simple things and hard to customize to go beyond what the library was designed to do. Programmable libraries are more like toolkits on top of D3 that still require some real programming to get results. But then they may give you more access to do complex customizations and interactions.

Declarative libraries

Rickshaw has been around awhile and looks good.

C3.js looks a lot like Rickshaw, see the bar chart example. Seems solid and simple.

Vega is strictly declarative, to the point of emphasizing chart specifications are JSON objects and completely wrapping D3. Has a neat live editor, headless rendering tools, and high-falutin language about “visual grammar”. It’s an impressive package.

Ember Charts by Addepar has some basic chart types. It’s tied to the Ember.js framework and needs Node to develop, also not a lot of activity on GitHub, so I didn’t investigate further.

Tenxer xCharts is declarative but with some programmatic customization. Examples feature using closures inside the chart definitions. Also has notes on customization and extension. Drawbacks are relatively few chart types and that there’s been no code development in eight months.

Programmable libraries

Towards Reusable Charts: Mike’s own opinion on reusability in D3. Advocates encapsulating a chart type in a closure. Doesn’t go much beyond establishing a design pattern. Some of the D3 plugins like Sankey and Horizon are good examples.

NVD3 is a reusable component library that works hard to respect access to underlying D3 design. It’s been around for awhile and seems pretty mature, not many commits in the past few months. The Discrete Bar example is appealingly simple.

Dimple adds chart types on top of D3 that you configure with simple declarative code. But then the advanced examples show you dropping in to the underlying D3 to extend the charts beyond what Dimple provides, which is great.

Bocoup d3.chart is a framework for creating charts, not a chart library itself. Its design is informed by a very thoughtful critique on reusable chart approaches. But it’s pretty early days and it’s aimed more at people writing chart libraries than folks just wanting to draw some charts. Also, I’m bummed the examples aren’t rendering right in JSFiddle. Overall my impression is these guys are pushing on solving the problem I want solved right now.

Summary

I’d use Vega or maybe Rickshaw if I just want some simple graphs. Dimple looks to be the most promising programmable system worth a closer look. I’m stubborn and foolish and like shaving yaks so I’m going to write my own little histogram thing using Mike’s suggested pattern just for the experience. Maybe I’ll end up using Dimple for future projects.

Example

Here’s an example trivial new chart type based on Mike’s proposed format. I’m not very happy with this result.

Update

dc.js is an interesting option. It takes too much programming to really just be reusable chart templates, but it has a nice way of packaging in crossfilter and aiding making basic data charts instead of arbitrary D3 SVG marks.

 

Using Tomato to make a wireless access point

I need a second wireless access point in my house, to deal with crappy wifi signal strength through lathe-and-plaster walls. I’m using an ASUS-RT16N running Tomato/Shibby to do this.

There’s a bunch of ways to string together wireless networks. There’s wifi repeaters (no wires), ethernet bridges, WDS, blah blah. This system is acting as a wireless access point; its whole job is to accept traffic on a wifi network and then share it to a wired ethernet.

In a nutshell, the configuration is to plug the house ethernet into one of the LAN ports on the router (not the WAN!). Then disable the WAN interface entirely in Tomato, and statically configure the router to a specific IP address on your wired network. Then set up the WAN as you’d want.

Here’s some details from Toastman. It looks a little different with the Shibby build, the LAN configuration is now hidden in this complicated bridge thing. But the idea is the same. One hint I picked up from elsewhere is to also go into the Administration thing and change the skin / color of the UI, just so you don’t get it confused with your main router.

League of Legends packet loss

I play LoL half the time on a wired DSL line in San Francisco and it plays just fine. The other half the time I play on a fixed wireless network link in rural California and I get enough lag it’s not much fun to play. I’m trying to figure out if the source of that lag is my ISP’s wireless network or something else.

LoL has net logs which are remarkably helpful. The LoL client reports it’s losing about 300 packets in a 30 minute game, typically 1 or 2 every 10 seconds. And occasionally one bad lag burst, 20 lost packets in a 10 second frame. That’s consistent with what I see in the game, the occasional lag hiccup and then once or twice a game really bad lag. I’ve also poked around a fair amount into the UDP packet stream for the game to measure bandwidth, burst speeds, etc. It’s hard to diagnose without anything like TCP sequence numbers. But FWIW the game never seems to get much faster than 40,000 kbits/sec or so, well below my ISP’s honest speed of 1 mbit/sec.

I was guessing the link layer of the fixed wireless link is causing the packet loss. But my ISP has been great in helping me figure this out. They tell me they measure link packet loss and there isn’t any. Also the network equipment does have various retransmits etc to work around wireless flakiness. Another possibility is my router, or maybe even something in the Internet outside my ISP. Hard to know!

Along the way I’m trying to learn more about ARP caches. This documentation of the Linux ARP cache is helpful. So is the command “ip -s neighbor list” for inspecting the state of the ARP cache, although I don’t fully understand the output.

 

chosen, for Javascript selection

Chosen is neat; it’s a Javascript library that replaces the usual browser form select dropdown with a much more capable version. Check the demo. The only drawback is it requires jQuery or Prototype.

But not anymore! There’s a version that works natively; here’s a pull request for it based on this fork. I’ve built it and it seems to work. 30k JS + 10k CSS after minification. The jQuery version is only 26k JS, but then you also need 80k of jQuery to run it. So big win.

I had a heck of a time building this. Not because it’s complicated, it’s just a few files. But “native” in this case actually means “Coffeescript and Sass with a Grunt build and btw that implies a Ruby dependency”. Bah, kids these days. Here’s a copy of my build, the “public” directory, which contains the minified Javascript, CSS, and a demo that seems to work. I might have built this wrong so better to get it from official sources.

 

go on Mac makes static binaries!

I’ve complained a bunch about how MacOS doesn’t let you compile static binaries; you absolutely must dynamically link libc.

go doesn’t have that problem. go doesn’t use libc. The binaries “go build” creates appear to be truly statically linked, at least according to “otool -L”. Although apparently there’s another compiler “gccgo” that does link with glibc, or else I misunderstand.

Bonus fact: if you strip a Mac go binary, it segfaults when you run it.

Why does Apple hate Unix?

I upgraded an iMac to Mavericks, just so I could share binaries with the other Mac I have. Now I’m undoing the damage the upgrade did.

I have to download and reinstall the compiler. With the mysterious “xcode-select --install”. Because according to Apple, Unix computers don’t come with compilers. And if you have one they go in and delete it on upgrade. At least there’s a standalone command line compiler now, it’s better than having to get the whole Xcode IDE bloat.

I have to download and reinstall the X server. I don’t begrudge Apple not shipping X11 by default, it’s pretty awful and dated. But I have a fully working XQuartz on my system. Why delete it when I upgrade?

I’m starting to flirt with the idea of giving up on MacOS on my desktop. It’s bad at games, and it’s bad at Unix development. It is good at ordinary consumer use though, web browsers. I kind of wish I had a way to run Windows for games, ChromeOS for web browsing, and Linux for development. All on one machine with transparent interaction.

Bandwidth usage in a house

From my place up in Grass Valley, the one with the slow 768kbps link. Recently upgraded to a screamin’ 1024kbps, which makes a bigger difference than you’d think. (800kbps is apparently a sweet spot for online video.)

I’m averaging about 11GB download a month. That’s 33 hours of fully saturated link a month, or about 5% of total capacity. I’m surprised there’s an average of about 2GB upload too. The asymmetric upstream speed is terribly slow, so I work really hard to never rely on it. Then again a TCP ACK packet is about 3% of the size of the data packet it’s acknowledging, so that accounts for 0.3GB of upload just to match the downloads. (Roughly, details vary.)

 

Date Download Upload Total
2014-04 10.47 GB 1.17 GB 11.63 GB
2014-03 17.38 GB 1.55 GB 18.94 GB
2014-02 10.10 GB 1.32 GB 11.42 GB
2014-01 7.57 GB 1.11 GB 8.68 GB
2013-12 10.35 GB 1.71 GB 12.07 GB
2013-11 11.17 GB 1.55 GB 12.72 GB
2013-10 4.15 GB 0.59 GB 4.73 GB
2013-09 10.04 GB 1.41 GB 11.45 GB
2013-08 11.66 GB 1.39 GB 13.05 GB
2013-07 13.97 GB 2.15 GB 16.12 GB
2013-06 14.92 GB 2.49 GB 17.41 GB
2013-05 13.06 GB 1.96 GB 15.02 GB
2013-04 12.97 GB 1.50 GB 14.46 GB
2013-03 10.81 GB 1.21 GB 12.02 GB
2013-02 10.79 GB 1.35 GB 12.14 GB
2013-01 10.93 GB 1.71 GB 12.64 GB
2012-12 15.97 GB 2.01 GB 17.97 GB
2012-11 4.57 GB 0.58 GB 5.15 GB

MacOS binary incompatibility

I keep forgetting this; MacOS binaries are not compatible with earlier MacOS versions. I built a bunch of Homebrew stuff on 10.9 and copied the binaries to a 10.8 machine. And get awesome errors like

dyld: lazy symbol binding failed: Symbol not found: ___strlcpy_chk
Referenced from: /usr/homebrew/bin/rsync
Expected in: /usr/lib/libSystem.B.dylib

Some sort of library / linker design choice, I guess. It’s as baffling as Apple’s decision not to allow static linking, because the kernel API may change so you must dynamically link to libc to mediate.

Homebrew has a way to build with --universal, but I think that’s more for 32 bit compatibility than minor OS revisions.

 

Unison is slow

I like Unison for synchronizing files, but it is slow. I finally have a little insight into why; it’s calculating fingerprints for file contents. rsync seldom cares about file contents, it generally gets by with just metadata like file size and mtime. Unison’s approach seems to be fingerprint every file. At least it caches the fingerprints, it used to not!

The problem is the fingerprint algorithm is slow, slow, slow. Like it takes many seconds to fingerprint a 2 gigabyte file. I can’t find a paper that describes the algorithm and my OCaml is rusty, but the code makes mention of MD5 and the paper references “cryptographic checksum”. Using crypto hashes as generic hashes used to be a fad, I’m guilty of it myself, but unless you’re worried about cryptographic adversaries it’s always better to use a fast CRC or the like instead of a crypto hash. Crypto hashes are slow.

While I’m complaining I can’t help but think being written in OCaml is part of why Unison doesn’t get more attention and development now. Not many folks know ML, you know? It also doesn’t help with the speed. I can’t tell if there’s an ML version of whatever fingerprint hash it’s calculating or if it’s using a native optimized library. Also the whole thing is single threaded, which for an app doing slow CPU work on many independent files is a mess. OCaml apparently doesn’t support concurrency :-(

Tomato on the ASUS RT-AC66U

I thought I had the router thing all figured out and then I decided I wanted 5GHz wifi so I bought an ASUS RT-AC66U. At $180 ASUS still isn’t managing to ship working firmware, although it is better than it used to be. Seems to be based on a reskinned Tomato version that’s not entirely awful. I did have a few problems though; unreasonable sluggishness if I’m running BitTorrent, and the DNS server seemed to simply block occasionally until some unrelated TCP download on my network completed. Stupid.

I thought I’d try something new so I went with the Merlin’s Tower firmware. It’s a lightly patched stock ASUS firmware, fixing a few bugs and adding a few features. It kind of worked, but I still had the sluggishness and DNS problems and it made me sad. For some reason I’ve never liked DD-WRT. So today I’m going back to my favorite, Tomato.

Except Tomato is a mess. The original release is no longer updated, without any notice on the site. Tomato-USB is also abandoned, as is Toastman’s versions. The best bet seems to be Tomato Shibby. Don’t be put off by the Polish language and awful site design, the guy’s serious and is doing a good job on firmware development.

In the end I found this guide to firmware updating helpful, along with these instructions for using tftp instead of ASUS’ proprietary firmware flasher. Once I found the right firmware version it mostly worked. Although man it takes a long time to boot, like 60+ seconds.

Configured more or less like the last one. One bug in the Shibby firmware; first time it boots it doesn’t recognize the 5GHz wireless adapter. You have to reboot it once. Details in this video.

Had to choose yet another DDNS service. I used dyndns for years, sad they finally left the valuable free market. Hover still has no DDNS support either. And couldn’t figure out how to use ASUS’ own service from Tomato. I used this guide (possibly spam) to find my way to freedns.afraid.org which is kind of neat and has thousands of hostnames to choose from. I settled on us.to. There’s a bit of magic where you have to grab the “token” out of freedns’ wget script to configure Tomato.

I should give up on this consumer stuff entirely and buy a serious router. At $180 for the ASUS gear it’s not exactly a bargain. Next project is to add a second access point upstairs, fortunately I have lots of ethernet drops.

d3.js: using CSV for numbers

D3 has two main ways to load data; JSON files or CSV files. JSON is generally better but bloated for long repeated rows of data, for which CSV is better because it only prints the key names once. But CSV has a drawback which is that it’s untyped. So D3 just lamely loads everything as strings. Most of the time Javascript’s automatic string to float conversion lets you ignore that but it fails in some places, like sorting with d3.ascending.

Fortunately D3’s CSV library lets you create an accessor function which manipulates the data as you load it. Here’s a function which will load every row and try to convert things to numbers. I wrote it in very verbose Javascript to make it clear what’s going on. I don’t care about the number of lines, but I do wonder if this is less efficient than possible.

// convert strings to numbers in CSV
function convertNumbers(row) {
  var r = {};
  for (var k in row) {
    r[k] = +row[k];
    if (isNaN(r[k])) {
      r[k] = row[k];
    }
  }
  return r;
}

d3.csv("data.csv", convertNumbers, function(error, inputData) {
  // do work on the data here
}

Note that the accessor function has to create a new object; you can’t just return the one the accessor passes you.

Homebrew observations

You can’t move a Homebrew binary directory. I installed Homebrew in /usr/homebrew2 and then renamed that to /usr/homebrew and a bunch of stuff broke because it had the path /usr/homebrew2 baked into it. bash-completion, also python.

Many Homebrew packages don’t compile cleanly. I ran into three: mg, unison, and ggobi. I filed bugs and got prompt responses (and a patch for ggobi in 12 minutes!), which is pretty great. OTOH it feels to me like Homebrew doesn’t have any sort of automated build-and-test setup for packages, these were all really simple bugs that anyone installing the code would hit. Some basic integration testing would go a long way.

I’m very grateful to Homebrew but the whole project feels pretty ad hoc and brittle to me. No surprise since it started out being such a simple thing. And simple is good! But I think at this point it’s evolved into needing to be a serious package manager, but hasn’t yet evolved all the serious package management. I wish we’d just use dpkg on MacOS instead. Fink is exactly that, but my experiences with it have been bad.

Starting anew with a clean homebrew install. Note I’ve already set PATH and BREW to use /usr/homebrew, the non-standard location

sudo mkdir /usr/homebrew
sudo chown nelson /usr/homebrew
cd /usr/homebrew

git clone https://github.com/Homebrew/homebrew.git
mv homebrew/* homebrew/.git* .
rmdir homebrew

brew tap homebrew/dupes
brew install atk autoconf automake bash-completion cairo clens cloog faac ffmpeg fontconfig freetype freexl gdal gdbm gdk-pixbuf geos gettext gfortran ggobi giflib git glib gmp gobject-introspection gpp graphicsmagick grc gtk+ harfbuzz icu4c iftop isl jpeg jq json-c lame less libffi libgeotiff liblwgeom libmpc libpng libspatialite libtiff libtool libxml2 lzlib makedepend mp4v2 mpfr nmap node objective-caml openssl optipng ossp-uuid p7zip pango pgdbf pixman pkg-config postgis postgresql proj pv python readline rsync sqlite texi2html unrar wget x264 xvid xz yasm

brew install mg
brew install unison

Battlefield 4 graphs

Some quick data views, looking at player statistics from the game Battlefield 4. I’m scraping stats from a site that lets me get a bunch of numbers for players, statistics like “Kill/Death Ratio” and “Score per Minute” and the like. I collected a bucket of stats for the top 1000 players (by rounds completed) for all 5 platforms, then graphed various variables. Honestly I haven’t found a very interesting story in this data yet, the main thing I’ve learned is that time played is not really correlated with any measure of skill. Ie: no one learns to play better. But more to consider.

Scatter plot is for two variables (lableled on axes), histogram below is the x axis.

Kill/Death Ratio vs. Time Played Win/Loss Ratio vs Kill/Death Ratio

Interactive data exploration

I’m exploring a multivariate data set. Battlefield 4 data, to be exact, I have a dataset for thousands of players with such statistics as “time played”, “kill/death ratio”, “win/loss ratio”, etc. Fun stuff. Now I’m exploring it looking for intresting patterns, clusters, etc. And doing it by hand-writing Javascript code with D3.

I wish there were a solid consensus tool for exploring datasets and showing graphics. Excel and R seem to be the two most popular. But Excel is too primitive and R is too much like programming already.

 

Wanted: browser based page scraping

Doing yet another HTML scraping project, contemplating the slowness and desolation that is BeautifulSoup or spend hours learning scrapy or surely there’s something better by now?

There is, my web browser, with DOM CSS queries. Just load the page and do querySelector and you’re done. Most modern HTML is quite nicely scrapable in browser Javascript. The problem is you can’t effectively script a browser to process thousands of pages. I’d hoped node.js would offer a solution but they don’t have some battle-hardened HTML parser like a browser has. There are some options, wonder if any are worth the time to learn about.

 

Chrome extension gripes

Working along on my Chrome extension, generally impressed with how well thought out and thoroughly documented the extension support is. That being said, some wrinkles...

There’s no support for reloading extension code when it’s changed during development. There’s some hacks, I’m using Extensions Reloader which gives me a button to press to reload the Javascript code. But it won’t reload the manifest, so it’s not a complete solution. And even then I have to hit the extension reload the button then refresh the page to debug stuff, it’s awkward.

Chrome has adopted an awkward API for signaling errors in the extension API, the variable chrome.runtime.lastError is set. This makes checking for errors a huge nuisance, but maybe it’s the only way to do this given the weird lifecycle of extensions? Good thing Javascript is single threaded :-P. It’s a shame Javascript’s built in exceptions are not very useful. I like the D3 pattern of setting an error object on the callback function, at least it makes the error variable a bit more explicit.

The Chrome extension storage API is fairly capable, I particularly like that it lets you store data in a place that Chrome synchronizes between the user’s browsers. But the API is just enough different from DOM localStorage to be a bit obnoxious. Also the get() method is incredibly slow, like 500ms to retrieve my 10 bytes of state. That means I can’t just store stuff there and fetch it from my content script, too slow for something whose purpose is to modify a page’s presentation. So I have to create a background page and move the config fetching there, an unwelcome complication. Update: it’s not always so slow. Sometimes it’s only 40ms. Sometimes its 200ms. I’m running a bunch of other extensions, should test it more cleanly.

 

Dog food

I found the perfect way to encourage myself to work on this Chrome extension. Install a version whose UI is so eye-bleedingly awful I can’t help but fix it.

Screen Shot 2014-04-08 at 9.07.47 AM

My first Chrome Extension

I wrote a Chrome Extension today. Or the start of one. Want to modify the content of some pages on Metafilter in order to try out a UI idea. I started with the diediedead userscript, that runs just fine by itself if you manually load it. But I want a proper Chrome extension so I can make it configurable (and easily usable) so I read up on how to build Chrome extensions. It’s easy, at least for this easy thing I’ve done so far, although there’s a lot more complexity for a more complex extension.

The one hassle is Chrome doesn’t auto-reload extensions under development. It does reload userscripts though, weird. Anyway the Chrome Extensions Reloader Extension helps, at least there’s a single button to press.

Automatic software updates considered harmful

Another day, another bandwidth management problem. Being on a slow 1Mbit link really makes you aware of how much crap Apple products downloads, with no user control.

Today’s scenario: trying to watch LoL tournament games on Twitch. That’s an 800kbps stream, so anything else running on my 1000kbps link is instantly notable. Like, say, my laptop. The one I’d like to use for very light web browsing while watching. Only the moment I open it up a bunch of Apple shit decides now’s the time it has to download updates. All invisibly, with no user feedback or control. Right now it’s softwareupdated downloading who knows what or how much, I’m guessing it’s the 120mb command line developer tools. Yesterday storeagent decided it had to download something, I still don’t know what, but that one started downloading with the lid closed and the machine nominally asleep.

Background downloads that happen quietly so your machine is ready to go are great. Background downloads that run in the middle of the day and consume all bandwidth are bad. If only they had some network saturation detection, or if there were a way to specify low priority network usage, or something. But this is TCP/IP and there’s not, so Apple’s a bit stuck. Still it’s awful and annoying.

Oh yeah, you can’t even kill storeagent. Ignores SIGINT. I finally did a SIGKILL. It seems to have recovered intelligently from that.

 

Heatmap of where I’ve been

Moved by Bobby Sudekum’s map and this Ask Metafilter question I drew a quick heatmap of all the places I’ve been in the past two years. Primary data source is OpenPaths, 6348 location points. Results in the gallery.

Doing this right is hard. OpenPaths samples non-uniformly in time, more points when you’re moving. So the honest thing would be to calculate dwell time from the timestamps. Also the heatmap fakery being done in TileMill is not really accurate, more of an alpha blending hack, but it does look nice. The result is not particularly scale-invariant, you need different settings for different zoom levels and different amounts of source data.

Here’s the steps I followed. Full Carto CSS below. These notes below aren’t a full cookbook, but if you sort of know TileMill already it may get you going.

  1. Get the right version of TileMill. This proved challenging; you need a dev build to get the special colorize-alpha image filter, but the absolute latest dev builds are broken. Version TileMill-v0.10.1-243-gafc00a ended up working for me.
  2. Download my data from OpenPaths in CSV format.
  3. Start up a TileMill project and import the OpenPaths data. Happily it detects the CSV and lat/long parameters with no trouble. Style it with simple dots and you have a map!
  4. Add some thematic layers for orientation; I used the Natural Earth data for country boundaries, state boundaries, and the small roads file (which is sadly US only). Put the locations dots as the top layer, then I put roads, admin1, and countries below.
  5. Switch to transparent markers. Grab the Mapnik fuzzy dot and drop it in my project directory, use that as a marker-file.
  6. Switch to the fancy heatmap. The magic there is mostly the image-filters:colorize-alpha. Also want to multiply markers, and allow overlap.
  7. Tweak the heatmap. Unfortunately there’s no scale-invariant way to do this, so I settled on making it look good at zoom=8. Both marker-width and marker-opacity are things you can tweak to make it look good depending on your density of location samples, zoom level, etc.

Here’s the full Carto CSS.

Map {
  background-color: #b8dee6;
}

#countries {
  line-color: black;
  line-width: 2;
  line-join: round;
  polygon-fill: #fff;
}

#10madmin1statesprovi {
  line-width: 0.5;
  line-color: #444;
  line-join: round;
}

#locations {
  marker-file:url(marker.png);
  marker-allow-overlap: true;
  comp-op: multiply;
  marker-width: 20px;
  marker-opacity: 0.5;
  image-filters:colorize-alpha(hsl(240,80%,50%), hsl(180,80%,50%), hsl(120,80%,50%), hsl(60,80%,50%), hsl(0,80%,50%));
}

#10mroads {
  line-width:0.5;
  line-color:#bbb;
  line-opacity: 0.8;
}

Traffic shaping vs. burst speeds

I’m a fan of the QoS controls built into Tomato firmware and other fancy routers. Unfortunately it doesn’t work on my slow Grass Valley link. The problem is the QoS algorithm they use needs to know the max link speed as a parameter; basically it throttles traffic that approaches 90% of that link speed when things get congested.

Except, I don’t have a single link speed. My link is 2500kbps for about 60 seconds, then is 1000kbps. If I set the QoS limit to 1000kbps then the router never allows any single stream to use more than that, basically wasting my burst. So I set it to 2500kbps, but then that screws up the traffic shaping when things get busy.

There’s other QoS algorithms out there that should be possible. I dimly recall back in 1999 when I studied this last that RED didn’t require knowing the link speed, just auto-detected congestion. That may be harder to pull off on a house router since it’s sitting behind the congested link, you really want to shape the link upstream of the bottleneck.

 

what’s using my bandwidth, take 20

Perpetual problem; network is slow, some process is using all the bandwidth, what is it?

On a Mac, the new short answer may be “use Mavericks”. The Activity Monitor includes a Network view and while it’s not perfect, it helps.

On an older Mac or other Unix machine, here’s one way:

Run iftop. It’s a top-like program that shows individual network sockets. Press “p” to turn on port number display. Press “t” to simplify to one line per host. The three columns of numbers on the left are download rates in kilobits/second, averages over 2/10/40 seconds.

Note the port number of the top flow. Then run lsof (as root) and search through the output for that port number. It contains the program name and process ID.

Using this I managed to find it was ocspd taking all my CPU. That program downloads fresh certificate revocation lists. Amazing how much data it had to grab.

iftop and lsof use existing kernel services, doesn’t require installing a kernel module or anything. Should be possible to write a patch to iftop that does the lsof-side of things to show the process ID and name. Or else a separate tool.

Rubbernet is a fine graphical tool to manage and shape Mac bandwidth in this fashion. But it’s €30. Also it requires a kernel module, which feels like dangerous overkill.

 

whois protocol notes

Whois is one of the magical old Internet protocols, going way back to 1982 in the time before TCP was even the standard. It still mostly works. I was curious how it’s scaled, in particular where the database state is held. The Wikipedia article is useful.

Long story short, each top level domain like .com has a whois server. Some of those servers maintain “thick” databases where they have a full copy of the database. Ie, the .ORG whois server has the full .ORG whois database itself. Others are “thin” and delegate queries to the domain registrar of record; for somebits.com, say, the .COM whois server looks up the name and sees TUCOWS is the registrar so sends the request for somebits info off to TUCOWS. It’s all basically a pretty centralized system and seems to work. RWhois is the proposal to replace the centralized system with a hierarchical one.

There’s about 100 million .com domains. Assuming a generous 4 kilobytes of data per record, that’s 400 GB of data. That’s a fair amount of data but not a whole lot, although there sure must be a lot of queries. Whois updates propagate fast, often in seconds, although TUCOWS has a 15 minute delay.

You can see this delegation when making a whois query (testing with the Mac command line client). Asking for somebits.com, the first query goes to a Verisign server who gives back a partial response, including a Whois Server at TUCOWS, the registrar for the domain. Then the whois client makes a second request to TUCOWS. Asking for somebits.org gives you the reply straight from a server at afilias.info, who I guess is running the whois for .org, a thick implementation.

How do you find the whois server for a particular TLD? There’s no standard, but IANA runs a database you can query via whois. Ie: whois -h whois.iana.org com. I don’t know if the whois tools use that online. My Mac client seems to know directly where to send whois queries for weird domains like .museum, .xxx, and .io. (Although it has a bunch of hilarious options to manually choose whois servers, like Russian and Caribbean authorities.)

The most important thing a whois server tells you is the DNS authority for the domain, where to go to look up IP addresses. In retrospect it’s odd that query is not part of the DNS system itself, is instead delegated to this other protocol. Then again the typical DNS client never does the whois requests themselves, they just ask a DNS resolver somewhere. And DNS has a huge amount of caching.

I have a lot of respect for the core old Internet protocols. Many have been in service for 30 years and still work great, despite a zillion-fold increase in Internet size.

ASUS RT-AC66U bug

My fancy new ASUS RT-AC66U has pretty good firmware; it seems based on the Tomato core, even the QoS. And unfortunately the built in DNS server, the one it advertises in DHCP. It has some bug that occasionally causes it to fail to respond to any requests for awhile, I think blocking on some other connection. I just had a failure where I couldn’t resolve names for about 45 seconds and it went away the moment an active HTTP download of a 60 megabyte file completed. The network was up the whole time (downloading the file), as was the router web interface, but DNS requests failed.

I should probably stop using the router DNS. Or else install Merlin’s patches.

Steam’s lousy throttling

Steam does a lousy job of bandwidth throttling. I had it set to limit downloads to 512kbytes/sec. (Why? Because despite using a fancy router with QoS control, QoS still sucks in 2014. Can’t stream video while downloading, derp). Here’s the graph of throughput from my router. X axis scale is 1 pixel = 2 seconds, max throughput is about 900 kbytes/sec. I turned off throttling halfway through.

Screen Shot 2014-03-02 at 8.35.12 AM

 

So looking at the first half of that graph, what Steam is actually doing is running at full capacity for about 10 seconds, then backing off to the requested 512 kbytes/sec for about 10 seconds, then averaging it out by going slow for 10 seconds. Back and forth. That’s just awesome.

I sure wish QoS worked on the modern Internet. The academic research I’m familiar with was all worried about solving the hard problem of fair congestion management through the whole Internet. I don’t care about that; I just want to manage QoS on one link, from my router to my ISP over the slow pipe.

Dogecoin notes

I toyed around with running Dogecoin on my iMac. Some notes.

Wallet

  • The official Dogecoin client starts by downloading the blockchain. That is still very big, gigabytes I think. I didn’t wait for it to finish. Apparently the initial sync can be made faster by download a file separately. Derp. Or use an alternate client that doesn’t require the whole blockchain: maybe MultiBit maybe something from @datamingle.
  • Crashplan will try to back up the Dogecoin state, including gigabytes of blockchain data. Have to exclude both the “blocks” and “chainstate” directories; but then don’t exclude wallet.dat from the backup! That’d be dumb. (Or do: is it encrypted adequately in the backup?)

Mining. Er, digging.

  • The mining pool I picked is fast-coin. It’s the biggest no-fee pool right now.
  • I tried several miners. fast-pool recommends cgminer, which is an awkward command line program and lacks the --scrypt flag they try. cgminer recommends Asteroid, which hung for 1+ minutes with no UI feedback. I finally settled on MacMiner 1.5.18e. It’s basically a GUI wrapper for command line tools, including bfgminer.
  • The CPU miner seems to work well. Each CPU (i7 at 3.4GHz) is giving me about 5.7 khash/second. I have 8 CPUs, so I’m doing about 45 khash/second.
  • The pool as a whole is doing 8.2G Hash/sec with 5891 worker, or an average of 1400 khash/second for a worker. So my worker is about 3% of the average worker. I’m not sure, but I suspect “worker” means “single computer” in the pool, so this is a fair comparison.
  • My Mac is using about 140W running the CPU miner, or about $1 / day at PG&Es outrageously high price for electricity. Temperature isn’t so bad, the fans aren’t making noise.
  • According to this litecoin site my AMD 6970M GPU should get about 210khash / second. That’s about 5x what my CPUs can do; a significant improvement, but not ridiculously so.
  • According to that list very few GPUs push 1000 khash/second. I wonder how the pool average is 1400? Surely no one is building Dogecoin mining rigs.
  • The MacMiner GPU client crashes on my iMac soon after starting to run. There are some flags to tune the GPU usage settings but I have them all set to defaults. It may simply not work, who knows. (it’s an EXC_BAD_ACCESS, KERN_INVALID_ADDRESS, on the main thread).
  • In MacMiner I tried using these command line flags I found on the 6970M stats page and it still crashes.
    -I 13 -g 1 -w 128 --thread-concurrency 5600
  • When the MacMiner GPU client crashes, the whole applications crashes but it manages to leave behind a running bfgminer process that is consuming resources somehow. I had about 4 hanging around before I figured out why my Mac was so slow even though I’d shut off all the doges.
  • I was able to run the MacMiner’s version of bgfminer by hand from the command line. It appears to work, yields about 150khash/second.
    bfgminer -S opencl:auto -o stratum.fast-pool.com:3002 -u workername -p password
    Update:
     see below for the --scrypt flag
  • The GPU miner costs about 100W to run, or about $0.33 cents a day.
  • There’s contention between the GPU and CPU client. No CPU client: 160 khash/sec. With all 8 CPUs pegged: 100 kh/s. Those 8 CPUs are only generating 45 kh/s, so it’s better to run GPU only.
  • Nothing seems to check the worker password I set on bfgminer. The username is checked though.

It may be that GPU miner does not work. bfgminer with just the GPU running never got me any credit in my pool. And the displayed hash/sec values don’t really make sense, or rather the units don’t. The display literally reads “150 MH/s”, which I was interpreting as a sane kH/s.

The fact bfgminer is not checking passwords also makes me suspicious. Maybe it’s just not posting work credit correctly. Update: yeah, bfgminer is not getting my credit with the pool and is reporting weird hash/sec speeds. Something is just wrong. Turns out I wasn’t setting the --scrypt flag; see below.

Profit

  • The pool tells me a rate of 21 khash/sec is worth 74 doge/day.
  • If my best rate is 150 khash/sec, that would be about 530 doge/day.
  • At a rate of 1000 Doge = $1.17, I could make $0.62 / day mining Dogecoin at a cost of $0.33 in electricity.

bfgminer screenshot

No idea what this really means. Like I said, this miner isn’t getting me credit in the pool.

Screen Shot 2014-02-27 at 11.32.55 AM

Update: scrypt

Oops, I was running bfgminer without the “--scrypt” flag. That will still take work and appear to do it, but with the old Bitcoin algorithm and not the new litecoin/dogecoin scrypt algorithm. And nothing ever gets posted. The following command line actually works and posted work to the pool:

bfgminer --scrypt -S auto -o stratum.fast-pool.com:3002 -u worker -p password

With no -I flag (“intensity”, a nice value) I get the desktop default, which yields about 12 kh/s from the GPU and another 12 kh/s from the 8 CPUs together. Ie: much slower than the CPU only miner I was using before. Switching to GPU-only mining doesn’t help. The results seem fairly random .With -I 12 (commonly recommended) I get about 55 kh/s; maybe 60 kh/s if I turn off the CPU miner. “-I 8” is slow again, 8 kh/s. “-I -10” locks up the machine solid, even a remote ssh login and killing the process didn’t recover. “-I 20” also locked up the GUI, maybe that was just bad luck?

Running GPU only results never report to the pool. Maybe the computations aren’t correct.

BTW, all this testing is hard to do because it seems the way the pool works it takes a few minutes before any work shows up. And if your rate is too slow it may never show up, maybe you’re always posting too late?

Lieux-dit

Lieux-dit are little placenames in France, for a farm or field. Les Courtes, La Botte D’Asperges, La Belle Vue, Le Télégraphe... They’re hyper-local placenames, known only to nearby residents. They do show up on road signs though, and occasionally wine labels, and they are lovely and historically evocative.

And of course they exist in Shapefile databases. Here’s some from Nantes. Sorry for the lack of basemap; I tried adding some public raster tile source to QGIS 2 but got defeated.

Screen Shot 2014-02-22 at 9.18.19 AM

 

Update: and here’s something a bit nicer done with TileMill, with Migurski’s OSM extract thrown in as a vector basemap.

Screen Shot 2014-02-23 at 4.35.52 PM

QGIS install on Mac

It takes roughly 60 UI actions to install QGIS on a Mac. And then you only get QGIS 2.0, not the latest 2.2. The problem is the official install is KyngChaos’ packages. They’ve done a great job over the years packaging Python and GIS software for Macs, but it’s seriously old school stuff. 4 different framework libraries have to be installed first by hand, each one individually packaged in a PKG installer script inside a DMG, then you install QGIS itself. Each installer takes many mouse clicks to install and also requires the root password.

In some sense KyngChaos is doing this right; the libraries he installs are useful for other projects, and this way you see all the license and components. But it’s really user unfriendly. It’d be nice if someone built a single self-contained QGIS.app that could just be dragged and run anywhere.

Digital National Geographic schema notes

I bought a digital copy of the National Geographic Magazine archives. Great data collection, horrible Adobe Air interface to access it. Fortunately the archive is basically a bunch of lightly obfuscated image files and SQLite databases. I might take a crack at making a more usable index to all the articles. To that end, some notes on the database schema I found.

There’s individual sqlite files on the DVDs and downloads, but I think they are all merged in a file called Contents/Resources/assets/db/cngcontent.sqlite3.full. I find 7977 article entries in 1416 issues for my set up to 2012, which sounds roughly the right scale. Here’s the tables in it and some notes on schema. Numbers in parentheses are how many rows are in the table.

Tables all have simple primary keys named “id”. “search_time” is a popular field, it stores the date of the issue as an integer. IE “1977 Sep” has a search_time of 19770901.

articles (7977)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
“start_page_offset” integer,
“page_count” integer,
“display_name” varchar(255),
“summary” varchar(255),
“search_time” integer,
“issue_id” integer

issues (1416)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“display_name” varchar(255)
“search_time” integer
“page_count” integer
“numbered_page_offset” integer
“numbered_page_count” integer
“numbered_page_start_value” integer
“page_exceptions” varchar(255));

geolinks (27570)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“location_id” integer
“article_id” integer
“department_id” integer
“map_id” integer

locations (5016)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“display_name” varchar(255)
“lat” float
“lng” float
“bounds_ne_lat” float
“bounds_ne_lng” float
“bounds_sw_lat” float
“bounds_sw_lng” float
“geo_provider” varchar(255)
“kms_per_lng_degree” float

contributors (12400)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“display_name” varchar(255)
“search_time” integer
“article_id” integer
“department_id” integer
“map_id” integer
“start_page_offset” integer

other tables

article_subjects (25774),
ad_subjects, ads,
departments, department_subjects,
maps, map_subjects,
photos (251002), photo_subjects,
links, schema_migrations, trivia_questions, trivia_rankings

 

Looks totally feasible to join through geolinks to find all articles in a specific region.

Sochi ski area maps

This Wired piece on Sochi maps notes that OpenStreetMap has way more map detail for the Olympic ski area than Google maps. It’s not entirely a surprise; Google’s coverage in Russia isn’t great, they’re not really into mapping ski lifts and trails, etc. Still, it’s a big world event, you’d think Google would have put some more effort into getting good data. Anyway, I did a map comparison from more sources than the Wired article. Nothing comes near OSM, but the Yandex maps aren’t bad. I did my best to make maps at the same scale centered on 43.6639, 40.3058.

Images in the gallery on this post. Some of why OSM looks so impressive is they just map a whole lot more kinds of features than other maps. That’s a mixed blessing. From worst to best, Bing and Apple have noticeably worse river and road data and are missing the railroad entirely; must be older data. Google’s maps won’t get you lost, Yandex has more local info still, and then the OSM maps have a generous amount of extra info.

Update: the OSM data in Sochi is years old, contributed by many mappers. Not just an Olympics one-off.

fixing iTunes corruption

iTunes corrupted my MP3 files. Not sure what happened, but I mounted my carefully-groomed 300GB of music via SMB on my Mac, imported the music, and suddenly a bunch of my MP3 files no longer play on the Sonos system. Particularly the music I bought from Amazon. Not sure what the corruption is. The file lengths are the same but the ID3 tags are different, maybe it wrote album art in? That’s worked in the past, but iTunes 11 is such a clusterfuck maybe they finally screwed it up. Or maybe it’s Apple’s broken SMB implementation causing filesystem level corruption. Either way I have to restore from backup. iTunes will no longer have write access to my music library. Screw you, iTunes.

I didn’t want to just rsync everything from a backup; was not positive that wouldn’t do some harm, and at first I had a concern that the 300GB directory might take too long. (Which is dumb; rsync is very smart.) In the end I just did an rsync, trusting the way it doesn’t delete / overwrite stuff it doesn’t need to. But first I did a bunch of verification of the files. The good news is the mtimes on the files at least got set, so it’s relatively easy to find the damage. I have to be a bit careful because the directory names are full of all sorts of messy Unicode, spaces, etc that shell programs don’t like. Also it’s 300 gigs of files, so I don’t want to just rsync the whole thing.

# find all files modified in last 20 days
$ find . -mtime -20 > /tmp/mp3.txt
$ wc -l /tmp/mp3.txt
369 /tmp/mp3.txt

# get just the directory names (ended up not using this)
$ cat /tmp/mp3.txt | while read l; do echo `dirname "$l"`; done | sort | uniq > /tmp/dirnames.txt

# make a list of what's restorable from backup
$ cat /tmp/mp3.txt | while read f; do o=/mnt/sdb1/BACKUPS/rsnapshot/monthly.1/localhost/home/nelson/Music/"$f"; [ -f "$o" ] && echo "$f"; done >| /tmp/restore.txt
$ wc -l /tmp/restore.txt
339 /tmp/restore.txt

# check what rsync would do
$ rsync -avn /mnt/sdb1/BACKUPS/rsnapshot/monthly.1/localhost/home/nelson/Music/ /home/nelson/Music/
# visual inspection
$ rsync -avn /mnt/sdb1/BACKUPS/rsnapshot/monthly.1/localhost/home/nelson/Music/ /home/nelson/Music/  | grep / | wc -l
344
# meh, close enough

# restore from backup
$ rsync -av /mnt/sdb1/BACKUPS/rsnapshot/monthly.1/localhost/home/nelson/Music/ /home/nelson/Music/

Mavericks broke SMB

Apple broke file sharing in MacOS Mavericks. I started finding the problem when I got a new iPhone and was going through the hell of setting up music on it via iTunes. Nothing worked and I finally started over with a new iTunes library, only to find I couldn’t add songs from my SMB network share (an Ubuntu box running Samba). The files showed up fine in Finder, and if I copied them to my desktop I could add them to iTunes. But trying to add them right off the fileshare resulted in nothing happening; no errors, no console logs, nothing.

A lot of research later and I learned that Mavericks has a brand new SMB2 implementation, and apparently it’s broken. In complex and subtle ways, maybe worse using Samba as a server than Windows. Awesome! As usual there’s a lot of cargo cult thinking for bugs like this, but this Apple discussion and this ZDNet article were particularly useful.

The recommended fixes are two ways to fake out MacOS to not use the new broken SMB2 implementation and instead fall back to the slower-but-stable SMB1 implementation. I found I also had to add “log level = 0” to my SMB server configuration to make this work (previously no log level configured). Yeah, there’s no way that makes sense, but it only started working when I had debug logs on (level 2) and then if I removed the line entirely it stopped working, but level 0 works. I’m too angry to spend more time trying to figure out what’s really going on.

It is so, so frustrating when Apple breaks basic Unix services that have been working in the past. Doubly so if there’s absolutely no error logging, and triply if the bug only shows up in some awful piece of client software like iTunes. Just terrible all around.

iTunes repeatable crash

Trying to sync my music to my new iPhone 5S, Track 4 of Autechre’s Quaristice (“plyPhon”) consistently causes iTunes 11 to crash, spinning at 390% CPU. I’m guessing it’s failing trying to transcode the 320kbps MP3 source (from Bleep) down to 128kbps AAC as requested. It’s killed iTunes dead twice now, have to Force Quit. Awesome.