Mosh automatic cleanup of dead sessions

I love mosh, using it to connect to a long-lived screen session from multiple computers (laptop, chromebook, $DAY_JOB, and phone).

One problem with it is that a mosh-server process that has no living client will linger for a very long time (forever?). This can happen for various reasons, such as letting a device's battery run down.

With some brainstorming help from the participants from #mosh, I came up with a way to automatically kill old mosh-server processes that probably represented defunct clients without killing ones that may represent working clients.

For a long time, my basic setup has been to run a command equivalent to: mosh myserver -- bin/cs where cs is a script which sets some environment variables and ends with exec screen, so I already had an excellent location to put cleanup code.

I also felt that the cleanup rule I wanted was: kill all mosh-server processes started from the same client. $SSH_CLIENT was suggested for this, but it's not useful since my portable devices naturally connect from different networks with different IP addresses (that's the point of mosh after all!) So I jumped to the conclusion that I needed a unique identifier. Why not involve a UUID?

As soon as I realized I needed to pass the UUID on the commandline or environment of cs, I realized that meant it would show up in the mosh-server commandline. So that led to the following snippet: ($i is already identified as being the UUID= argument):

    ps h --sort start_time -o pid,command -C mosh-server |
        grep "$i" |
        head --lines=-1 |
        awk '{print $1}' |
        xargs --no-run-if-empty -n 1 --verbose kill

That seems to work! One final wrinkle, though: In mosh irssi connectbot, there's no way to specify the mosh commandline directly. Hoever, there is "Requested mosh server". I created a wrapper script reading:

#!/bin/sh
exec mosh-server "$@" -- bin/cs UUID=...
and used that script (with full path, in my case) as the configuration value.

Now I shouldn't have to worry about mosh-server processes piling up on my main linux box anymore.

Entry first conceived on 31 January 2014, 18:05 UTC, last modified on 31 January 2014, 18:19 UTC
Website Copyright © 2004-2014 Jeff Epler