Some Bits: Nelson's log

12 posts in March 2016

NTP surveys

Way back in 1999 I did a survey of NTP. I spidered the whole Internet’s collection of NTP servers and published some statistics. From a desktop Linux box in my office at MIT, without permission, which raised a few eyebrows. But it was the 90s Internet and it was awesome.

These days NTP is much more widely deployed. It’s also been the cause of some security exploits and DDOS traffic, so I fear my kind of survey is much harder to do now. But I get requests about it occasionally, I think mostly from students. Here’s an email of answers I just sent today. Shodan’s view of NTP servers looks like an interesting place to start.

First of all,you use ntpq or ntpdc to do the query,is there any other method to do that now?

I mostly used ntpdc for access to the “monlist” command, which shows clients who are asking for the time (ie: downstream links). Both ntpq and ntpdc support “peers” to show where this particular server is asking for time (ie: upstream links). I also have used ntpdate to just query the time.

Secondly considering the Internet security,most of hosts are behind the firewalls,can the final result actually reflect to the true conditions?

Yes, you are right. It was a concern in 1999 when I did my survey and it’s only gotten much worse. I wonder now whether a survey like I did is even possible. There have been several high-profile security problems with NTP in the past few years, including an exploit in ntpd using monlist. Also NTP queries can be used for DDOS queries. The net result is that most servers are much more secure now and may not answer anything other than a basic “what time is it” query. Also I suspect a survey like mine would set off many alarms.

Finally,can I conduct the survey on a computer running Windows operating system?Can you give me some suggestions?

It should be possible on Windows, but I’m not sure how to do it. You want some way to make ~100 NTP requests simultaneously. It’s pretty easy since it’s just a UDP protocol, but I don’t know the best way to do that on Windows.
Two other things you should look into:
The NTP Pool is where most Internet clients get their time today. There’s about 4000 servers total and I’m sure there are plenty of opportunities to survey and research just those servers. The NTP pool developer community is friendly, you should talk to them before doing any significant survey work.
These days it is relatively easy to query every single IPv4 address in the world, all 4 billion of them. One site that does this regularly is Shodan. For example, here is their search result showing 835,000 NTP servers: https://www.shodan.io/search?query=ntp

Python packaging in March 2016

Hooray! I finally finished porting my lolslacktest code over to be a proper Python module, installable with pip, and with a virtual environment. What a pain! Some notes on what I learned. But first, some reflection.

This project has been one of the least fun things I’ve done in a long time. I can tell by the way I’ve been foot dragging. It’s confusing and hard to debug packages. The docs are inconsistent and suffer from years of accretion. Some things are genuinely confusing, like Python’s surprise lack of support for circular imports. And in the end result is my product works just like it did before. No user visible changes. Behind the scenes things are better; the install is cleaner, I have a virtual environment for proper external dependencies, etc. But nothing fun, just slightly less crappy ops.

The state of the art for Python Packaging

As of March 2016 the Python 3 state of the art for package installation is pip, pyvenv, and setuptools. pyvenv and pip comes with Python 3.4 but setuptools is still extra. (On Ubuntu you have to install python3.4-venv with apt.)

The state of the art for managing Python packages keeps changing. This Stack answer explains the landscape as of September 2014. This packaging user guide is updated as of September 2015 and is mostly very good, but even it references things that don’t work such as “python setup.py bdist_wheel”. I also found this guide useful but it was mostly written in 2012 (although occasionally updated).

The pip installed by python 3.4 (Ubuntu) is version 1.5.4, you want version 8.0 or later if you want to do things like install gevent with a precompiled wheel file. setuptools is old too. So first thing you should do after setting up a pyvenv is “pip install -U pip setuptools”.

The setuptools docs are not very good. They assume you know how distutils works. Also they spend a lot of time talking about easy_install and none at all talking about pip.

Honestly all this Python packaging stuff is a big mess, I feel like you have to understand the history to be able to use the current state of the art. It’s a shame Distutils2 didn’t work out for Python 3.3 and rationalize it all. To be fair, packaging in almost every system sucks: npm, rvm, homebrew, they’re all a mess. All but my beloved apt, and that’s because the Ubuntu package management team works super hard.

Some hacks and code things

I had to do a few hacks and other things to make my project work.

The biggest code change was just wholesale replacing absolute imports like “import lib” with relative imports “from . import lib”. I think that’s actually correct, but I was doing it kind of blind for every single file.

I had to modify my code because Python really doesn’t support circular import dependencies. You don’t really notice until you are using relative imports. The accepted solution for circular imports is to break the circularity, refactor code. Screw that. My workaround was to move some of the import statements inside functions, so they execute at run time and not import time. That’s bad and inefficient but expedient.

There’s two similar-looking ways for a Python package to specify dependencies. You can add an install_requires stanza to your setuptools setup() method, or you can use pip to install a bunch of stuff listed in a requirements.txt file. The setup() dependencies are installed automatically when a package is installed, but nothing installs requirements.txt automatically. OTOH the requirements.txt option is more powerful, for instance pip can install things from github URLs whereas setuptools can’t. (The setuptools docs say you can do this with dependency_links, but I couldn’t make it work.) I’ve ended up using a mix of both, preferring setuptools where I can.

I have some shell scripts named in the “scripts” section of my setup.py, so they are installed in the virtualenv bin directory. But I want them to work even if the virtualenv isn’t activated, so those scripts have to source their own virtualenv. Mostly for execution in cron; getting cron to activate a virtualenv is not easy. The hack I did for this was this shim of code at the top of each script:

VENVDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $VENVDIR/activate

The bash magic in the first line sets VENVDIR to be the directory where the bash script itself is. Conveniently, that’s the same directory that has the activate script.

I have no idea how to put version numbers on my program. It’s a private thing only I’m installing, so for now I’m going with the dbschema version. Part of me wants to just put the git commit nonce there.

My deploy script used to be rsync from dev to prod. Now it’s sshing into prod and having it do a “git pull” followed by “pip install -U”. I took this approach at migurski’s suggestion. It means I’m not using any of the fancy distribution builds and versioning stuff that setuptools/pip enables. But I don’t really need those right now, they make more sense for public code hosted at PyPI

Note to self: you can’t move a pyvenv environment once its created. They have paths hard coded.

 

 

Xiaomi Yi Action Camera notes

I bought a Xiaomi Yi camera. It’s a GoPro-knockoff, a small HD camera that takes amazing high quality video and is only $70. Unfortunately it’s also not really made for the US market and is poorly documented and I can never remember how to use it.

Quick use notes:

  • Press front button to turn it on: it beeps and light in front starts flashing.
  • Wait for beeping / flashing to stop. Front should glow blue (full battery).
  • Press shutter button on top to start recording. Beeps once, lights flash while it records. press shutter button on top again to stop recording. Beeps several times.

Status lights:

  • Front ring: battery indicator goes from red (low) to purple to blue (full)
  • Top/bottom/back: flashing red LED indicates video recording, photo taken
  • Side: blue LED indicates WiFi is on

Sounds:

  • One beep: turning on. Also acknowledging image capture start.
  • Two beeps: still turning on.
  • Three beeps: connected to USB.
  • Four beeps: video recording finished.
  • Seven? beeps: turning off

Buttons and controls:

  • Front button: power. Short press to turn on, long press to turn off.
    Can also be used to swap between photo/video mode.
  • Top button: shutter control / start recording
  • Side button: turn wifi on. This takes awhile, wait for flashing blue.

For more complex control the camera connects to an iPhone app. The camera can be put in WiFi access point mode, at which point your iPhone connects to its private WiFi network and can control it. (Default password: 1234567890). Lots of settings, the main thing I did was be sure the camera defaults to video mode when turned on.

IIRC you can also download video this way but it’s unreliable, I ended up popping the SD card to copy my recordings over. Or maybe I used the device as a USB drive.

The phone is hackable, there’s a world of custom firmware etc. Also lots of stories of people bricking their cameras.

more cron fiddling

Update: this doesn’t work, see below.

I still need a better solution for running lolslackbot. Right now it’s a shell script that runs 7 Python programs that run sequentially and usually complete in about 25 seconds. I run it from cron once a minute. The problem is sometimes one script takes too long, typically because a remote API server is hung. Also it’s better (but maybe not essential?) if the script doesn’t run twice at once.

So I set up lockrun in the cron job so that only one instance of the job can run at once. This works pretty well, but lockrun has no solution for timing out a dead job. Despite my best efforts, twice now the script hung for hours (forever?) and my system stopped working.

(I can’t even figure out how to monitor lockrun’s lockfile. It creates the file once and then never touches or updates it ever again, so the file time never changes. I could monitor my underlying program’s logfile or something I guess.)

So now I’m wrapping some bailing wire around the duct tape and using timeout to add a timeout.

timeout 3 lockrun --lockfile=/tmp/lf1 -- sleep 10

Yeah, I know. But it seems to work. What could possibly go wrong?

I think the right solution is ensure my scripts are safe to run twice at once. I don’t think this is too hard semantically, and I do have a database with transactions to help mediate things. The trick is the occasional faux distributed transaction for stuff like “if I find a new row in the database, update some remote service and then mark the row as processed”. I guess I could add three phase locking for that? Ugh. While I’m at it I should make it so the 7 Python programs can run independently, at different frequencies. The very first one is the important one, the slow one, asking “is there any activity for any of these N users?” It’d be nice to run that script in parallel and somewhat out of lockstep sync.

While I’m here I wanted to give a shout-out to cronic, yet another wrapper for cron jobs that improves error reporting. cron mails you if there’s any stdout or stderr, but ignores exit status. cronic fixes it so it mails you if there’s stderr or if the exit code indicates an error. But it ignores stdout. Seems particularly useful in concert with timeout; if timeout kills a job the only way you know is exit status, which cron without cronic ignores.

Update: this timeout + lockrun thing doesn’t work. If the timeout fires then timeout kills the child process, lockrun in this instance. But that kill signal doesn’t propagate to the children. A potential solution would be to kill the whole process group but I don’t see an easy way to do that. I’m also wary of adding hacks on hacks because of the warning in the lockrun docs about how there’s no kill option in lockrun because killing things correctly is hard.

Update 2: after 9 months I think my current solution is stable. I use lockrun to be sure only one version of the cron job is running. It runs a Python program, not a shell script, that runs all my separate Python subprograms (by invoking the main() function on each.) It uses faulthandler.dump_traceback_later to implement a last resort global timeout on the whole Python program. It all feels wrong, but in practice it’s been quite robust.

Python modules frustration

I’m trying to turn my lolslackbot code into a proper set of Python modules, so I can manage the code with pip and venv. That means turning my moduleless code into a bunch of packaged modules. And writing setuptools.

And oh god it’s awful. Python’s handling of module namespaces and imports is confusing, particularly when circular dependencies are involved and/or command line scripts as opposed to Python libraries. I can’t even tell if this caveat applies to me or not

Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.

The other problem is years of cruft that’s accumulated in Python packaging tools. setuptools, disttools, easy_install, pip, wheel, egg, virtualenv, pyvenv.. To some extent this has been rationalized in modern Python: use pip and setuptools and call it a day. But the docs that are out there are hard to follow because they tend to describe the history, not the current practice.

The two best documents I’ve found so far:

Right now I’m hung up on some code where “from . import lib” works in some contexts but not others. I think it may be related to circular dependencies but am not sure.

Update: turns out Python doesn’t actually support circular imports, despite looking like it does in many circumstances. So now I’m having to refactor all my code that worked just fine to not have module A import module B which imports module A. I feel like I’m programming in C again, only without #ifndef macros. One partial solution is to only do the imports inside the running function code. That avoids the circular imports at import time, at the expense of deferring the import code machinery running in your actual execution path all the time. Maybe I’m misunderstanding how to really make this work. (There’s a bunch of arrogant advice which says “if your code has circular imports you should refactor it.” No, imports are how you manage namespaces in Python, and Python shouldn’t have this limitation.)

Unit testing in bash

I wrote a really simple unit test framework for bash. Like 10 minutes, 2 functions, totally half-baked. But it seems to work.

testErrors=""
function assertEqual {
    expected="$1"
    actual="$2"
    message="${3:-Not Equal}"
    if [ "$expected" == "$actual" ]; then
        echo -n "."
    else
        echo -n "E"
        testErrors="$testErrors\n$message: Got $actual, expected $expected"
    fi
}
function assertSql {
    expected="$1"
    sql="$2"
    actual=$(echo "$sql" | sqlite3 $db | sed -e 's/ *$//')
    assertEqual "$expected" "$actual"
}

function testReport {
    if [ -z "$testErrors" ]; then
        echo "Tests OK!"
    else
        echo -e "Tests failed$testErrors"
    fi

DNS glue records

Had a bit of DNS I didn’t understand today. The whois records for google.com say the name server is ns1.google.com. So how do you look up the address for ns1.google.com? That’s a circular dependency!

Turns out the answer is glue records; there’s a good explanation in the first two answers on Stack Exchange, or enjoy this comic strip. Long story short, the same TLD server that tells you that the name server for google.com is ns1.google.com also provides an “additional” non-authoritative A record for ns1.google.com. That short-circuits the circular dependency. You can see this reply yourself with dig +additional. Here’s a (heavily shortened) transcript where I only show the lines along the actual resolution chain:

$ dig +trace +additional google.com SOA

.			13529	IN	NS	g.root-servers.net.
;; Received 397 bytes from 192.168.0.1#53(192.168.0.1) in 31 ms

com.			172800	IN	NS	k.gtld-servers.net.
h.gtld-servers.net.	172800	IN	A	192.54.112.30
;; Received 734 bytes from 192.112.36.4#53(g.root-servers.net) in 279 ms

google.com.		172800	IN	NS	ns4.google.com.
ns4.google.com.		172800	IN	A	216.239.38.10
;; Received 660 bytes from 192.54.112.30#53(h.gtld-servers.net) in 361 ms

google.com.		60	IN	SOA	ns3.google.com. dns-admin.google.com. 117627770 900 900 1800 60
;; Received 210 bytes from 216.239.38.10#53(ns4.google.com) in 36 ms

The key thing there is the third segment. My computer asked h.gtld-servers.net who the name server for google.com was, and it gave me an NS record naming ns4.google.com. But then it also volunteered a non-authoritative A record for that name, 216.239.38.10. That’s the “additional” response that serves the glue record.

The other question is how glue records are administered; who told gtld-servers.net the address for ns4.google.com? How do we keep that IP address updated? I’m not sure. My registrar Hover just lets you fill in a glue record but doesn’t explain how that gets sent to the TLD servers. Gandi’s docs have a good explanation too. My guess is it’s part of the protocol that registrars use to communicate with the companies that maintain the TLDs. You don’t just give them NS records for each domain, but you can give them an A record too. I wonder if they auto-update? I’m guessing not.

Glue records are old: they are explained in RFC 1033, complete with an example at SRI.com. This DNS book notes that glue records can also be an optimization; it’s basically providing the answer to the next question the resolver is about to ask. At the cost of being non-authoritative.

(Reading this whole chain I realize I’m still a bit confused about how DNS works. My computer asks my name server 192.168.0.1 who the name server is for “.”, the root, and is told g.root-servers.net. Note it gets no additional A record. But then my computer already knows that g.root-servers.net is 192.112.36.4, how did it know that? Maybe a cache? Then it asks that root server for the name server for .com and is told k.gtld-servers.net, along with an additional A record. From there it can ask about Google.)

Hat Tip to Andy Fowler for giving me the magic keyword “glue records”.

sqlite3 test suite

I felt guilty complaining about sqlite3’s source distribution, so I went to look at the real source, what the authors work with. It’s not managed by git but rather in Fossil (an SCM written by the sqlite3 author). Happily the web view is quite good.

One of the miraculous things about sqlite3 is its incredible test suite. There are 683,932 lines of test code. Compare to 273,000 lines of C code for the library and all its extensions. sqlite3 has a reputation for being solid and correct. It’s not an accident.

The test size is overcounted a bit because there’s a lot of test data. For instance the test for the Porter Stemmer is 24k lines of code, but almost all of that is a giant list of words and their correct stemming. Still very useful tests! But not quite as much human effort as it looks on first blush.

The tests are written in Tcl! For all I know it is the oldest large large Tcl program still in active development. But other than the string quoting problem Tcl is a pretty good way to script a test. See for example the tests for the JSON module

do_execsql_test json101-1.1.00 {
  SELECT json_array(1,2.5,null,'hello');
} {[1,2.5,null,"hello"]}
do_execsql_test json101-1.1.01 {
  SELECT json_array(1,'{"abc":2.5,"def":null,"ghi":hello}',99);
  -- the second term goes in as a string:
} {[1,"{\\"abc\\":2.5,\\"def\\":null,\\"ghi\\":hello}",99]}
do_execsql_test json101-1.1.02 {
  SELECT json_array(1,json('{"abc":2.5,"def":null,"ghi":"hello"}'),99);
  -- the second term goes in as JSON
} {[1,{"abc":2.5,"def":null,"ghi":"hello"},99]}

Very readable and compact.

As a software project sqlite3 makes a lot of idiosyncratic choices. Tests written in Tcl. Fossil instead of git. Source code distributed as “the amalgamation”. But sqlite3 is a masterwork of code. It’s fast, it’s reliable, it’s simple, and it works well in embedded systems while also providing a lot of very sophisticated database capabilities. I have nothing but respect for it.

Upgrading sqlite3 within Python 3

Python 3 has sqlite3 baked in. That’s great! But it has an old version of sqlite3; my Ubuntu 14.04 system with Python 3.4 has sqlite 3.8.2. I want sqlite 3.9, for the new JSON hotness.

There’s a pip-installable package called “pysqlite” that should be installable in a virtualenv. But it only supports python 2 and explicitly says “use the built-in sqlite3 for python 3”. Thanks but no thanks!

This Stack Exchange thread has details on recompiling python3 with your own sqlite3, but that’s more work than I want to do. Also it appears that python3 is just loading libsqlite3.so.0 from my Ubuntu install, so I should be able to upgrade it by either upgrading libsqlite in Ubuntu or building my own shared library. But the Ubuntu upgrade looks impossible without upgrading all of Ubuntu 14.04. (I couldn’t find a PPA from a quick search).

Compiling sqlite3 into a shared library is an exercise. The source is distributed in an idiosyncratic format and the version with a Makefile doesn’t build shared libraries. I ended up making something work by following the official docs and this note about the shared library.

gcc -c -fPIC -O2 -I. -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS4    -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_JSON1    -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_EXPLAIN_COMMENTS    -DHAVE_USLEEP -DHAVE_READLINE    shell.c sqlite3.c
gcc -shared -o libsqlite3.so -fPIC sqlite3.o -ldl -lpthread
ln -s libsqlite3.so libsqlite3.so.0
./sqlite3 -version
LD_LIBRARY_PATH=. /usr/bin/python3 -c 'import sqlite3; print(sqlite3.sqlite_version)'

It works! But now I’m nervous. Compiling sqlite3 correctly takes more research than I conducted. It has a whole lot of options! Also I get a bit worried about relying on LD_LIBRARY_PATH to override libraries. It’s totally fine to do of course, but it just seems too easy to forget to do it in some environment and suddenly things aren’t working consistently. If I were serious about doing this I think I’d build my own Ubuntu package for real, using Ubuntu’s Makefile as a starting point.

Python / sqlite3 query logging

When debugging database code it’s really handy to have a text log of the actual SQL being executed by the database. This output is remarkably difficult to get in many database drivers. Happily, starting with Python3.3 there is a way

connection.set_trace_callback(print)

The argument is any function, or None to disable the tracing. I think this has no access to the results, nor can you use it to time how long the query took. That requires some more ambitious thing.

letsencrypt renewal

I set up letsencrypt SSL for http://www.somebits.com awhile ago. When I installed it in early January, there was no way to renew the certs and they expired in 3 months. Happily they’ve added a simple renewal command which mostly worked. The first time I ran it I got an error “DNS problem: query timed out looking up CAA” but I just ran it a second time and it worked.

Happily the certificate renewal didn’t touch my Apache config at all, just updated the certificate.

I took the opportunity to fix some redirects in the SSL version of my site config so they redirected to https://, not http://. I’m further regretting the way I have two versions of my Apache config, some 90 lines of complicated redirects and crap now duplicated. And now edited a tiny bit, to preserve SSL. I should refactor all that but IIRC it’s complicated.

I’m a little scared to have enabled SSL without fully committing to it. I suspect Google will start preferentially serving the SSL links, so what happens if I forget to update the letsencrypt certs? So far Google isn’t serving the SSL links though, I wonder if my siteindex URLs (no https) overrides their preference for SSL.

I hate installing Python libraries

(Caution: intemperate angry rant follows.)

I’m wasting more than an hour figuring out the fuckup of building GDAL to run in a virtualenv on Ubuntu 14.04 LTS. This hasn’t worked well in the year+ I’ve been trying, and it’s not working well now.

  1. set up a new virtualenv and activate it
    virtualenv -p /usr/bin/python2.7 venv
    source venv/bin/activate
  2. Install the openaddresses repo I have
    cd ~/src/oa/machine/
    pip install -e .
  3. Manually install cairo cffi (shouldn’t pip have done this?)
    sudo apt-get install libffi-dev python-cffi
    pip install cairocffi
  4. Give up trying to install GDAL with pip. Even after you work through the include path packaging problems, the C compiler starts throwing errors about variable scoping.
  5. Start over with a virtualenv that also uses system packages, which somehow seem to be working.
    virtualenv --system-site-packages -p /usr/bin/python2.7 venv

I shouldn’t publish my angry rant. GDAL is great software, and I appreciate all the volunteer open source effort. But something about dealing with packages and software installation is just so maddening. I think it’s because hiding behind “pip install gdal” is about 200,000 lines of complex code in multiple languages from multiple distributers. When it works its awesome. When it fails all you can do is try searching the error message and cargo culting a solution, which only works 1/3 of the time.

grawr.