Some Bits: Nelson's log

11 posts in June 2012

Javascript Date sadness

There are many things to dislike about the Javascript Date library, but this one keeps tripping me up so I better write it down:

typeof(Date(1341070612432))
"string"

typeof(new Date(1341070612432))
"object"

The confusing thing is that Date is both a Javascript class that returns Date objects and a convenience function that returns strings. Most of my Javascript programming is in D3’s style which never uses constructors or the “new” keyword; instead its “classes” are functions that return objects. But a lot of core Javascript isn’t like that. Neither is Leaflet; I keep forgetting to say “new” there too.

Lasercutting foray

I’m playing with doing some lasercutting, using Ponoko and their Inkscape starter kit to do the cutting. I gave myself just a few hours to prepare a single test file to send off for fabrication, just to get my feet wet. First time using Inkscape, and first time in over 10 years to try to drive a laser cutter.

Inkscape is sadness on a Mac. It runs in X11 which is mostly intolerable. It’s unaware of the Mac file system. But the worst thing is the rendering is just really ugly. It’s a shame there’s no Cocoa native port of Inkscape, although realistically that’d be a lot of work to do right. BTW is it just me or if you copy a path from one Inkscape window and paste it to another, does it get converted to a bitmap?! I had to save the thing to a file and then import it to preserve the vector data.

Ponoko’s use of Inkscape is quite simple. Basically just make a bunch of blue lines 0.01mm wide for cuts. Some extra options for engraving, fills, etc. I made some circles and an outline of my name in Futura as test objects. But on to the more interesting things.

First, my walks tracks. Converting my complex walk shape to a cuttable SVG was not easy. The GPS tracks themselves are not sensibly cuttable, of course, you’d end up with confetti in the middle. What I want is to cut the concave hull of my shape, plus do something clever to depict some internal structure. Not sure how to do that. Even concave hull isn’t easy; ST_ConcaveHull isn’t available until PostGIS 2.0 which I’m not yet using. So what I did was use a combination of QGIS and Inkscape to make a filled shape of all my walks, a raster blob, then use Inkscape’s bitmap tracer to turn that into an outline path. Even then I got kind of a mess, had to go in and remove a lot of points. I’ve still got a disjoint lobe in my object which is going to screw up the cut, but I left it in there because I was curious what would happen and I don’t know how to easily fix it anyway.

Second the San Francisco Bravo airspace. This was pretty straightforward; load up the shapefile from FADDS in QGIS, print it to SVG, done! Well almost; that results in a bunch of lines being double-drawn, which causes the laser to cut twice. Ponoko doesn’t want you to do that and has instructions on how to manually break up shapes so duplicate lines don’t print. I did my best but I probably missed some spots.

OK, my SVG file is done, ready to cut! Now then, what material? Ponoko has a fun variety of options. Cardboard would be the natural cheap material for testing, but it’s kind of flimsy for some of the fine angles and they recommend not using the raster engraving option, which I’d already done as test images. I went with cardstock on the theory it’d be most forgiving to any materials / delicacy problems.

Some sample prices for my relatively simple object, 7.1″ square material sheet. Prices are “making”, which I take to be laser time, and then the material.

  • Cardstock: $7.13 + $2.36.
  • Thin cardboard: $7.93 + $0.23.
  • Cherry veneer MDF: $14.83 + $4.34.
  • Fluorescent orange acrylic: $8.27 + $3.72.
  • Bamboo: $8.27 + $2.82.

$10 for the item and another $10 for shipping and the order is in! They say it takes “typically 1-2 weeks”, but I see there’s a design review first which will presumably take some time on their end and maybe mine.

 

CrashPlan on Linux

It’s taken me six months since my last server failure, but I’m finally implementing an offsite backup for my home Linux server. I use rsnapshot for local backups which is great for recovering from mistakes. But it does no good if your server box dies in a fire, need offsite backups for that. I like CrashPlan on my Mac, so I thought I’d try it on Linux.

The first hurdle is installation. The default install location is /usr/local/crashplan. The supplied shell script is quite nice and they even gave thought to letting you run the backups as some user other than root! I think if you don’t install it as root the /etc/init scripts don’t get linked in. Worse, those scripts don’t seem to have any provision for non-root users.

The second hurdle is setting it up. CrashPlan is only configurable via a GUI tool that assumes it’s running on the computer that’s being backed up. Weak! Fortunately there’s a workaround; the GUI client really just talks over a socket to the backup daemon and you can fake it out with to talk to a remote host via an ssh tunnel. The Mac client stores the port number in an awkward place, but then I found that instead of editing the .app config file I could edit /Users/nelson/Library/Application Support/CrashPlan/ui.properties and add the line servicePort=4200. Still, shame the GUI client doesn’t allow this setting.

One extra Linux challenge is that the real time backups feature uses the inotify kernel module which by default only allows watching 8192 files. The docs cheerfully suggest just upping this number, but then I read this post that suggests it costs 200 bytes per file monitored (or maybe it’s only 40). Either way I don’t want to bump this up to 100,000+ or whatever it’d take (one per directory?) so I simply disabled real time backups in the Advanced settings. I’d actually prefer it just ran a nightly backup anyway, to manage bandwidth.

The backup daemon is reasonably well behaved. It’s a java process (!) that’s using less than 5% of one CPU. The bandwidth throttle actually works.

I’m annoyed CrashPlan is listening on port 4243 on the LAN port, not just localhost. You can’t actually use this for remote administration, at least setting serverHost instead of serverPort in the client didn’t work out for me. I wonder how secure the daemon really is; the security FAQ only addresses file encryption. Update: if you disable listening for remote backups, then it only listens on localhost:4243, much more secure.

Checking out msgpack

msgpack sounds like it could be useful: a binary format alternative to JSON that promises to be “like JSON but it’s faster and smaller”. Is it really? Not significantly; on a sample of 175 JSON files I had lying around the msgpack files were on average 75% the size of the JSON files. Better, but not significantly so. And if you’re a bit careful with JSON formatting and float precision, it’s not clear msgpack has anything to offer.

The big winner (ukiah.json, msgpack is 12% the original) is a GeoJSON file with a few thousand lat/lon coordinates in it, all pretty-printed with spaces. Some files actually get bigger with msgpack; a quick look suggests those are files with short floats in them like “32.17”, and it may be the Python encoder is giving those a full 8 bytes for an IEEE double.

For a file I actually care about, my WindHistory stations-md.json database, the 1 meg JSON files goes to 500k. That’s a big win for me in a deployed webapp, I think msgpack may do a particularly good job with the arrays of small numbers that file contains, e.g. [0,5,6,4,4,15,18,14,9,5,7,7,6]. I’d considered doing a custom format for that, dropping in msgpack would sure be easier.

Update: I did a quick extra comparison, passing the data through zlib.compress() after encoding, before comparing lengths. Compressed msgpack is worse than compressed json! For my sample, the msgpack/gzip data was on average 106% the size of the json/gzip data. For the WindHistory database the msgpack was still smaller, but only a little; 90%. gzip must be good at removing the text redundancy in json files full of numbers. OTOH I don’t understand why msgpack would ever be worse.

I took a quick look at the format spec: I think all msgpack is doing is storing numbers in binary instead of ASCII. That’s an improvement, particularly for codec speed, but it doesn’t seem to make all that big a difference in size. Here’s the msgpack author’s own opinion on comparison to other formats. The most useful link is the StackExchange answer.

What I’m really hoping for is an encoding that divines the structure of the stored data and builds compressed representations based on an ad hoc schema. It’s not crazy, folks were doing this with XML in Java webapps 10 years ago. But it’s not easy either. First step; a lookup dictionary for key names in object maps.

import json, sys, msgpack, os

pcts = []
for fn in sys.argv[1:]:
    try:
        jsonData = file(fn).read()
        data = json.loads(jsonData)
    except: continue

    msgData = msgpack.packb(data)
    pct = 100.0*len(msgData)/len(jsonData)
    print "%d%% %s json %d msgpack %d" % (pct, os.path.basename(fn), len(jsonData), len(msgData))
    pcts.append(pct)

print "%d%% average size" % (sum(pcts) / len(pcts))
12% ukiah.json json 2025795 msgpack 251349
24% faithful.json json 1103 msgpack 275
37% multiple-child-classes.json json 1645 msgpack 609
40% pets.json json 319 msgpack 128
41% sample_flatpages.json json 762 msgpack 318
42% m2m_through.json json 682 msgpack 292
42% mypeople.json json 142 msgpack 61
42% nk-inheritance.json json 344 msgpack 146
42% non_natural_1.json json 481 msgpack 206
43% big-fixture.json json 1749 msgpack 756
43% fixture6.json json 777 msgpack 341
44% forward_ref_lookup.json json 645 msgpack 286
44% initial_data.json json 5758 msgpack 2558
44% sequence.json json 231 msgpack 102
44% thingy.json json 147 msgpack 66
45% fixture8.json json 651 msgpack 295
46% initial_data.json json 6220 msgpack 2882
46% multidb.default.json json 546 msgpack 253
46% multidb.other.json json 543 msgpack 251
46% testdata.json json 1849 msgpack 860
47% fixture1.json json 744 msgpack 357
47% raw_query_books.json json 2602 msgpack 1240
48% absolute.json json 158 msgpack 76
49% db_fixture_3.nosuchdb.json json 193 msgpack 95
50% authtestdata.json json 1785 msgpack 895
50% empty.json json 2 msgpack 1
50% fixture2.json json 408 msgpack 206
50% multidb-common.json json 196 msgpack 99
50% stations-md.json json 10835 msgpack 5523
50% testdata.json json 1783 msgpack 894
50% testdata.json json 1783 msgpack 894
51% comment_tests.json json 968 msgpack 502
53% db_fixture_1.default.json json 208 msgpack 112
53% fixture1.json json 434 msgpack 231
53% fixture2.json json 437 msgpack 234
53% initial_data.json json 211 msgpack 112
54% flare.json json 11413 msgpack 6220
54% zeppelin.json json 318590 msgpack 174435
55% feeddata.json json 725 msgpack 403
55% initial_data.json json 226 msgpack 126
56% direct_message-destroy.json json 397 msgpack 225
56% direct_messages-new.json json 397 msgpack 225
58% skyrim.json json 22577 msgpack 13124
59% us-borders.json json 1421 msgpack 843
61% show-89512102.json json 656 msgpack 405
61% update.json json 656 msgpack 405
61% user_timeline-kesuke.json json 658 msgpack 406
62% manifest.json json 307 msgpack 193
64% CellLocation-geo.json json 936985 msgpack 608302
64% WifiLocation-geo.json json 5026275 msgpack 3249817
64% sample.json json 34 msgpack 22
66% model-inheritance.json json 161 msgpack 107
66% test-region.json json 104 msgpack 69
67% package.json json 732 msgpack 494
68% miserables.json json 11535 msgpack 7877
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% test-country.json json 23138 msgpack 16046
71% mkassawara-aprs.json json 5644 msgpack 4036
72% cells.json json 2186447 msgpack 1583116
72% steps.json json 98475 msgpack 71556
73% mkassawara-first-solo-xc.json json 2368 msgpack 1730
73% walks.json json 269914 msgpack 199435
74% marimekko.json json 1139 msgpack 847
75% ohio.json json 244951 msgpack 184823
75% stations.json json 2185 msgpack 1648
75% test-location.json json 31890 msgpack 23957
76% average size
76% bullets.json json 543 msgpack 417
76% status-destroy.json json 473 msgpack 364
76% us-state-centroids.json json 7849 msgpack 6009
79% track.json json 2570 msgpack 2048
79% us-counties.json json 901283 msgpack 718329
80% direct_messages.json json 240 msgpack 192
80% public_timeline.json json 9488 msgpack 7670
81% us-states.json json 88430 msgpack 71888
81% user_timeline.json json 356 msgpack 291
82% initial_data.json json 4563 msgpack 3748
82% turkers.json json 1866 msgpack 1533
83% friends_timeline-kesuke.json json 9045 msgpack 7585
84% KMER-df30.json json 321 msgpack 272
85% friends.json json 17796 msgpack 15233
85% world-countries.json json 252515 msgpack 216432
86% KLVK-df30.json json 322 msgpack 278
86% KRHV-df30.json json 319 msgpack 276
86% followers.json json 29176 msgpack 25124
86% trip.json json 25665 msgpack 22184
87% flare-imports.json json 34321 msgpack 30201
87% friendship-create.json json 468 msgpack 408
87% friendship-destroy.json json 468 msgpack 408
87% replies.json json 3298 msgpack 2895
87% show-dewitt.json json 722 msgpack 630
88% KAPC-df30.json json 322 msgpack 286
88% featured.json json 10056 msgpack 8854
89% KCCR-df30.json json 324 msgpack 289
89% KMRY-df30.json json 327 msgpack 293
89% KPAO-df30.json json 317 msgpack 283
89% KSTS-df30.json json 324 msgpack 291
89% KWVI-df30.json json 330 msgpack 296
90% KOAK-df30.json json 344 msgpack 313
91% KMAE-df30.json json 326 msgpack 299
91% KNUQ-df30.json json 317 msgpack 290
91% KVCB-df30.json json 328 msgpack 301
92% KHWD-df30.json json 327 msgpack 303
92% KMHR-df30.json json 332 msgpack 306
92% KSFO-df30.json json 348 msgpack 321
92% KSJC-df30.json json 334 msgpack 308
92% KSMF-df30.json json 339 msgpack 312
92% KSNS-df30.json json 326 msgpack 300
92% KSQL-df30.json json 317 msgpack 293
93% KMCE-df30.json json 328 msgpack 307
93% KMHR.json json 7656 msgpack 7182
93% KMOD-df30.json json 327 msgpack 307
93% KPAO.json json 7372 msgpack 6891
93% KSAC-df30.json json 333 msgpack 313
93% KSAC.json json 7485 msgpack 7035
93% KSCK-df30.json json 336 msgpack 314
93% KSUU-df30.json json 341 msgpack 320
94% KCCR.json json 7465 msgpack 7034
94% KMOD.json json 7388 msgpack 6953
94% KRHV.json json 7106 msgpack 6714
94% KSFO.json json 7710 msgpack 7269
94% KSQL.json json 7615 msgpack 7199
94% KSUU.json json 7555 msgpack 7160
94% district.json json 53585 msgpack 50817
94% district.json json 53585 msgpack 50817
94% district.json json 53585 msgpack 50817
95% KAPC.json json 7541 msgpack 7220
95% KDVO.json json 7826 msgpack 7467
95% KHWD.json json 7646 msgpack 7329
95% KLVK.json json 7442 msgpack 7100
95% KMAE.json json 7582 msgpack 7231
95% KMCE.json json 7278 msgpack 6959
95% KMER.json json 7258 msgpack 6909
95% KOAK.json json 7662 msgpack 7332
95% KSCK.json json 7591 msgpack 7263
95% KSTS.json json 7548 msgpack 7210
95% KWVI.json json 7711 msgpack 7375
96% KMRY.json json 7760 msgpack 7454
96% KNUQ.json json 7701 msgpack 7433
96% KSMF.json json 7777 msgpack 7512
96% KSNS.json json 7700 msgpack 7426
96% KVCB.json json 7726 msgpack 7417
97% KSJC.json json 7758 msgpack 7567
99% test-usstates.json json 152305 msgpack 152245
99% test-worldborders.json json 911213 msgpack 911121
107% flowers.json json 14123 msgpack 15152
110% unemployment.json json 1383 msgpack 1532
120% world.json json 142051 msgpack 170748
121% unemployment.json json 39718 msgpack 48273
76% average size

Python: showing time in another timezone

Python’s date and time APIs are awful. Actually they’re awful in most languages, Java’s were sure terrible. But Python is worse because it has several ways to do things and none of them are really correct. The newish datetime module is better than the old time module and its bizarre “tuple that may or may not be timezone aware” type. But even datetime is stupid about time zones, only supporting UTC or the local computer’s time. You need the add-on pytz to bring in the Olson timezone database to start doing real work, and even then it’s complex.

I have some timestamps, seconds-since-Unix-epoch, which is intrinsically UTC. Unambiguous integers. Now I want to print them in Florida’s timezone, no matter what my computer’s time zone is. Here’s one way:

florida = pytz.timezone('US/Eastern')
floridaDatetime = datetime.datetime.fromtimestamp(ts, florida)
print floridaDatetime.strftime("%b %d %H:%M")

This seems to work, but the pytz docs admonish “Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. It is safe for timezones without daylight savings trasitions though, such as UTC” The docs recommend this instead:

florida = pytz.timezone('US/Eastern')
utcDatetime = datetime.datetime.fromtimestamp(ts, pytz.utc)
floridaDatetime = utcDatetime.astimezone(florida)
print floridaDatetime.strftime("%b %d %H:%M")

I’m not positive, but I think my simpler code actually will work as long as I don’t try to do anything fancy with floridaDatetime like arithmetic. The problem is described in detail in the pytz docs: it’s some combination of datetime being limited and that certain timestamps are ambiguous because of DST. So really pytz is encouraging us to always always always only ever do math with UTC time and defer conversion to local timezone to the last possible moment before string output. Which is imminently sensible, if frustratingly verbose.

I think the right library would be a datetime type whose internal representation is always only ever seconds-since-epoch plus desired timezone. That way all the library code can do arithmetic without worrying about DST. I wonder if any other languages do it that way. Python’s got some unfortunate legacy hanging around and I don’t think Python3k tried to fix up the mess.

interactive fsck on Ubuntu

My headless server in Kansas didn’t reboot properly. The nice guys at the datacenter plugged in a console and found fsck waiting for them to press “Y”, which they did, and the system came back. Interactive fsck is pretty much always a terrible idea, particularly for a headless server, why was it waiting?

I can’t find good docs on this for Ubuntu. I’ve asked a question on StackExchange and started digging through code. I think the important setting is FSCKFIX /etc/default/rcS:

When the root and all other file systems are checked, fsck is invoked with the -a option which means “autorepair”. If there are major inconsistencies then the fsck process will bail out. The system will print a message asking the administrator to repair the file system manually and will present a root shell prompt (actually a sulogin prompt) on the console. Setting this option to yes causes the fsck commands to be run with the -y option instead of the -a option. This will tell fsck always to repair the file systems without asking for permission.

So Ubuntu already partially runs fsck in non-interactive mode; the -a flag (aka -p) “This option will cause e2fsck to automatically fix any filesystem problems that can be safely fixed without human intervention.” I guess something was wrong enough with the filesystem on reboot that -p was afraid to fix it. But in my case I don’t care; I have a backup, I need the server up under any circumstance, and I never knew how to answer fsck’s questions anyway.

I found this by reading through code. Ubuntu mounts filesystems via a program called mountall. Init invokes mountall and uses a shell script to set options. Here’s relevant bits of code:

/etc/init/mountall.conf:

[ "$FSCKFIX" = "yes" ] && fsck_fix="--fsck-fix"

mountall.c:

if (fsck_fix || mnt->fsck_fix) {
  NIH_MUST (nih_str_array_add (&args, NULL, &args_len, "-y"));
} else {
  NIH_MUST (nih_str_array_add (&args, NULL, &args_len, "-a"));
}

So there we have it, I think setting FSCKFIX=yes in /etc/default/rcS is my solution. And I’m glad to see even with that not set Ubuntu mostly runs fsck non-interactively.

Ubuntu 12.04 power savings

This is kind of neat; Ubuntu 12.04 is saving me 10-15 watts or about 25% of my server’s power consumption. I upgraded from Ubuntu 11.10 and my UPS is telling me my server uses 45W now instead of 58W, or thereabouts. The system is a few degrees cooler, too.

I suspect the important change is from the 3.0 Linux kernel to the 3.2 kernel, and the subsequent Power Saving Tweak where the Intel chipset is told to shut down the built in GPU. That’s a win for a lot of folks; headless servers (without weird code using the GPU) and desktop computers with “real” graphics cards. I’m surprised it’s so much an improvement though.

A second possibility is CPU affinity; there’s been some work on multicore systems trying to keep some cores shut down more often if the workload is light. Details on Less Watts tips. I enabled sched_smt_power_savings a few hours after upgrading Ubuntu, but I didn’t see any difference, so maybe not. The CPU frequency scaling graph suggests that maybe something’s changed.

The one alarming thing is that the IO Service Time went way up, from .00001s to .05s. Huh? I’m not doing much IO, so maybe this is a bogus measurement, and I can’t really understand what Munin is measuring anyway. This may be an artifact of the disks being put to sleep more often, or maybe the measurement changed scale, or who knows what. Simple disk benchmarks suggest nothing’s really wrong.

Update: turns out this was a change in the Munin scripts, a fix for an eight year old bug. The Ubuntu 11.10 version was reporting bogus numbers that were backwards and too small. Supposedly the new numbers are correct, and also report no data correctly now. Just reading the numbers off the graph, my system now says writes take about 20ms when before it was saying 0.1ms. Disk seeks are roughly 10ms, so I’m inclined to believe the new numbers are more correct. The bug comments also note that the various disk stats graphs contain similar information but are better.

www.ʬʬʬ.com

Someone on Metafilter mentioned they registered the IDN http://www.ʬʬʬ.com (aka http://www.xn--5paaa.com). I thought that was cool, so I posted it to my usual social media thing. And it worked, correctly rendering everywhere! Here’s the flow of where that worked

  • Pasted the name into the Pinboard Chrome extension
  • Had it show up on Pinboard
  • Had dlvr.it pick it up from an RSS feed and post it to Twitter
  • Saw the IDN in my Twitter client
  • Clicked on the link, redirecting through t.co and dlvr.it

In retrospect, I think why this works is IDNs aren’t really Unicode, they’re Punycode (that xn-5paaa thing). So most of the tools are treating that thing as ASCII but the browser happens to do the interpretation so it displays correctly. I confirmed that a bit by tweeting “this is a test http://www.ʬʬʬ.com”, which shows up on Twitter as “this is a test http://www.xn--5paaa.com” on both Twitter.com and the MacOS client. The link still works, but it looks wrong; Twitter should probably translate.

Fixing a slow Samba server on Ubuntu 12.04

I recently upgraded my Ubuntu from 11.10 to 12.04. Mostly worked fine, the usual little config mishaps. But then one really bad problem: my SMB server on the Ubuntu box was terribly slow with my Mac client. Like reading a file would get 100kbytes/second. This on a gigabit ethernet where I used to be able to do SMB at the disk speed of 30Mbytes/second.

I ruled out some basic stuff: local disk access was fine, and copying the file via nc was super fast so it wasn’t the network. I started at guessing things. The final fix was to remove this line I’d previously put in my smb.conf

socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

Not sure why those settings would be harmful, nor which specific setting is the problem. The smb.conf man page suggests TCP_NODELAY is the default so I’m guessing it’s the buffers. Anyway, SMB is fast again.

Kartograph

Kartograph is looking promising. It’s a new Javascript map library that is fully vector based, drawing maps in SVG. First time I’ve seen a complete break with the slippy map raster tiles that Google made so popular. The nice thing about a vector map is you can easily use your own projection. Of course you can do raster tiles in many projections too, but most of the existing raster libraries have Google Mercator baked pretty deeply into them. Also vector rendering is beautiful and somewhat scale invariant.

The code’s on GitHub. And if you dig into the demo pages you can find the source code hidden inside the <div> element that contains the map itself. It looks pretty straightforward, a nice API. I’m a bit alarmed to see methods like “chloropleth” and “dotgrid” right on the map object; that suggests the author has in mind a set of hardcoded visualization types. I hope he’s left room for other developers to easily add their own visualization types. Also none of the examples have any navigation, none of the usual pan/zoom controls we expect. That’s totally fine for many visualizations, but may distinguish the uses of this library compared to Leaflet and friends.