Some Bits: Nelson's log

13 posts in April 2016

Things I learned about systemd

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

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

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

References

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

Stuff I learned

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

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

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

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

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

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

Opinions

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

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

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

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

 

freedns annoyance

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

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

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

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

Machine Learning study

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

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

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

wordpress.com code bug

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

The code I want to post is the Python code

int(“1”) & 2

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

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

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

Visual mode

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

HTML Mode

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

Notes

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

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

Sending SMTP email: a decade approach

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

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

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

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

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

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

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

MacOS 10.9 to 10.11 upgrade

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

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

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

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

Packages to install this time:

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

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

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

TinyDB: is this sqlite for JSON?

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

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

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

 

champion.gg and BSON data

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

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

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

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

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

2016 Python webapps

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

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

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

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

Full Stack Python has some useful advice.

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

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

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

Simple app metrics: stathat

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

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

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

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

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

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

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

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

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

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

Python3: no len() for iterators

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

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

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

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

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

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

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

A library of trained machine learning models?

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

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

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

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

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

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

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

youtube-dl for music playlists

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

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

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

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

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