Thursday, July 25, 2013

Stuipd shell trick (or: who's been up-chucking all over my /tmp?)

This isn't actually something going mental on my own machine, though it could very well have been, I suppose.  I'm doing a lot of work with bitbake these days for work.  One of the features I've been spending time with is the PR Service, which, in the absence of any other configuration changes, starts up a process that queries and feeds an sqlite3 database with hashes and revision numbers.  The intent is to get around problems that arise when you don't properly update the PR value in your recipe.

And if that's all gibberish to you, don't worry, that's just setting the stage.

Here's the thing.  If the server doesn't shut down cleanly -- for whatever reason -- it leaves a pidfile in /tmp.
Aside: I briefly considered providing a patch to bitbake that would move the pidfile out of /tmp mostly on religious grounds. I'm offended by anything that leaves plain files in /tmp as a matter of course, but I opted to not bother since I didn't think most people would care or would welcome the change if I did submit it and really, so long as you're not having problems with your build, bitbake actually does clean up after itself and removes the pidfile. The problem is, of course, the only reason I get dragged into this stuff is when builds don't go well. So, observer's bias, I guess.
So then I log in to a particularly ill machine and discover this:
% ls -l /tmp/PRServer_127.0.0.1_* | wc -l599
... yeah.  We do not have 599 active PR Servers running on this machine.  But it's also, let's say, challenging to find anything I actually happen to care about in /tmp now, thanks to this heap of detritus.

Ah.  At last we're getting near the point.

The pidfile has, encoded in the name, the PID of the server.  So for starters, let's collect up a list of potential PIDs.  I figure that's a good first step, then I can look to see if those PIDs are still active and, if they are, if they happen to be a PR Service (since given the length of time this has obviously been running amok, there's no reason to assume that an active PID is actually the same one that was given to the PR Server in question).

First step is easy.  Of course I typed this all on the command line, I don't actually create scripts ... well, much of ever, honestly.  I create shell functions more often than that by far, but I don't even bother enshrining most of these quick hacks in functions.  If they age out of my shell history, I recreate them from scratch.  There's no magic here, anyway.  But for the sake of readability, let's look at this as if it were a script or function:
for i in /tmp/PRServer_127.0.0.1_*
do
    cat $i
done
Why not just 'cat /tmp/PRServer_127.0.0.1_*' you ask?  Because that destroys any ability I have to operate on individual files.  Bear with me.

Right.  Got a list of PIDs now.  Conveniently, 599 of 'em.  Now what?

My first thought was send something relatively benign like SIGCONT to each, check the return value and hopefully harvest some info from each of them at the same time about their command line so I could tell which of the active ones were still the processes I was interested in.  That would look something like this:
for i in /tmp/PRServer_127.0.0.1_*
do
    for j in $(cat $i)
    do
        if [[ kill -SIGCONT $j ]]
        then
            # appears to be an active process, check it
            if [ -n "$(ps aux | grep $j | grep -v grep | grep prserv)" ]
            then
                # active and a PR server, probably the right one.
            else
                # remove the dead pidfile
                rm /tmp/PRServer_127.0.0.1_$j.pid
            fi
        fi
    done
done
Don't use that.  It almost certainly won't work.  I never even typed it into the shell.

I got thinking a bit more about this.  Considered using -p rather than SIGCONT, googled a bit for some tool to help, then thought:  this is dumb, I have the info I need in the shell.  So here's what I ended up with:
for i in /tmp/PRServer_127.0.0.1_*
do
    for j in $(cat $i)
    do
        if [ -d /proc/$j ]
        then
            if grep -q bitbake /proc/$j/cmdline
            then
                continue
            fi
        fi
        rm $i
    done
done
So how'd that work out?
% ls -l /tmp/PRServer_127.0.0.1_* | wc -l9
Still a suspiciously large number, but one I can live with.
Turns out, though, there's another (in this case better) way to do it.  The pidfile contains a port number where the server is listening.  If there's nothing still listening on that port, it's safe to assume the server is dead.
for i in /tmp/PRServer_127.0.0.1_*
do
    for j in $(basename $i | awk -F_ '{ print $3 }' | cut -f1 -d.)
    do
        if netstat -l | grep -q localhost:$j
        then
            continue
        else
            rm $i
        fi
    done
done
This relies on behaviour of the PR Service, though, whereas my first attempt works for any ridiculously large list of processes.  I think I like it better, though, because I like anything that lets me bring awk into the equation.

Tuesday, March 12, 2013

find sucks

There are certainly times when find is useful, but nearly every time I end up doing something like this:
# find . -type f -name foo
That's my age showing, probably. Regardless, one of the old 2¢ Tips I remember from back in the day that I hardly ever used until recently was using locatedb to find stuff on your disk.

Yes, there's absolutely a lot of options in "modern" distributions for finding files, often going as far as indexing contents and letting you search a single interface to find them all. That's great for a lot of people, I'm sure. But I'm a software developer most of the time, meaning I would rather have my machine sit idle most of the time than be busy doing something else when I want it to be compiling. Similarly, I need my disk space because I'm going to have a lot of intermediate files. They don't live long, sure, but if I run out of disk space in the middle of a build, that's kinda bad. So I don't want all-singing-all-dancing indexers running in the background (or worse still, on boot) and leaving databases lying around full of stuff I'll never be searching for anyway.

But back to the point.  The old tip that I've only recently started adapting for my own purposes.  The essence of it is this:
Create a custom locatedb containing only the stuff you want to search, update it on demand, then search that.
That's it.  So the simplest possible implementation of the idea is this:
# cd $HOME
# updatedb -o $HOME/.homedir.db -l 0 -U .
That's it.  After that, all subsequent searches are of the form:
# locate -d $HOME/.homedir.db --regex ".*foo$"
Simpler?  Maybe not.  Faster?  Actually, not greatly on a local disk with a small hierarchy.  Consider that by small I mean something like this: 
# locate -S -d $HOME/.homedir.db
Database /home/joe/.homedir.db:
        24,135 directories
        196,394 files
        16,616,477 bytes in file names
        6,598,887 bytes used to store database
For example, my search for all mp3s in my home directory results in this:
skynet ~ time locate -d $HOME/.homedir.db --regex ".*mp3$"
[output deleted]
    1.83s real     1.73s user     0.00s system

skynet ~ time find . -type f -name  "*.mp3"

[output deleted]

    0.55s real     0.23s user     0.28s system
Not really a win.  But let's look at something more "real world".  In my case this is a project source tree.  Any mp3s in there?
turd src time locate -d ./.src-list.db --regex ".*mp3$"
    0.65s real     0.65s user     0.00s system
turd src time find . -type f -name  "*.mp3"
   83.28s real     1.40s user     4.15s system
Nope.  Didn't expect any, but there's the speed-up we were looking for.  FWIW, the database is significantly different than my home directory one:

turd src locate -S -d ./.src-list.db 
Database ./.src-list.db:
40,534 directories
412,043 files
51,894,579 bytes in file names
11,188,602 bytes used to store database
turd src time locate -d ./.wrlinux-list.db --regex ".*layer.conf$"
[output deleted]
    0.56s real     0.56s user     0.00s system
turd src time find . -type f -name "layer.conf"
[output deleted]
    1.25s real     0.60s user     0.65s system

So there, again, we see considerable speed-up.  If you're unfortunate enough to be doing anything over shared filesystems, you're going to see improvements in the range of a couple of orders of magnitude.

Beware:  I'd been using this trick for a while before I realized just how fragmented the *locate world has become.  What I have here works for mlocate but not necessarily for any other version.

Also, note that this isn't quite the same as the old tip that first enlightened me about locate.  That was for indexing CDs (or, more likely, floppies) where you wanted to be able to search a library of them without manually popping each into the drive.  That still works, though I'm hard pressed to think of a practical use for it now that we live in the age of the cloud.  But for the sake for conversation and completeness, here's how that worked.


  1. Mount your CD to a custom location (eg. /mnt/cd-label-1)
  2. updatedb -d $HOME/cd-database.db -l 0 -U /mnt/cd-label-1
  3. search at your leisure as above
Now you need only search the database that the path name will actually tell you what CD your files are on.  Except who backs stuff up to CD anymore in the age of cheap, effectively infinite cloud storage?  Hmm.

Sunday, September 23, 2012

Automatically pgp-sign outgoing email with mutt

There's very little I miss about Evolution. But, yeah, I have my weak moments. Occasionally I'll try to start it up, get frustrated and lose a few hours to the mental trap of "Aw, c'mon, it can't suck this much!". It does. When you're using it purely to interact with an Exchange server, in particular E2003 and E2010 (the two I've been compelled to interact with at work), it does. When you'd really rather be using an email client that positively revels in the simplicity of its interface, it does. On the other hand, everyone knows mutt sucks. It just happens to suck less. Except in two and a half ways (I'll get into that later) it sucks just a little bit more than Evolution.
  • Automatically signing outgoing email with your pgp key
  • Interacting with calendars
  • Interacting with calendars (yeah, this is two things, I'll post on it someday, too)
Okay, so the thing is, mutt can do what I want in terms of signing email, it just takes a little bit of doing. First, though, the problem statement.
I want to be able to have a single pgp key selected by default that will be used to sign all outgoing email from me and I only want to enter that key's passphrase when I start mutt.
Yes, yes, I know. That last part is a bad idea, I should have it time out or I should just use the built-in features in mutt to cache that information and be done with it. I'm aware of the risks I'm opening myself up to here, it's just the way I roll. Livin' on the edge, baybee. So we'll start with getting the preliminary bits out of the way. You need a key for starters. Odds are if you're using a modern Linux at all you've already got some of the required GNU Privacy Guard (gpg) tools installed. I'm not walking you through creating keys (maybe some other time), but you'll want to do something like this:

skynet ~ gpg --gen-key

And answer the questions then enter a reasonably good passphrase. Let's not even start down the "what makes a good passphrase" road. Firmly out of scope. If you've already got a key you want to use, then you'll do something like this:

skynet ~ gpg --list-keys

And find the one you're interested in using as your default from the output. In my case, I want to use my personal one: 5A20D17C. That's nothing private, you can get that info from here, for example. Now that you've got a key you want to use, time to the basic part of the mutt setup. A quick look here shows you already have options available. So turn them on. For reasons I may get into later, I keep them in a file named .user-mutt-config, but the go just fine in your .muttrc

# specify the uid to use when encrypting/signing
set pgp_sign_as=0x5A20D17C
# automatically sign all outcoming messages
set crypt_autosign


Phase one, complete. There's a lot more options available on the UseGPG page I linked above, but you don't need any of them if all you want to do is sign email and verify other signatures. Now every time you compose an email, mutt will have your selected key queued up and when you hit 'send' it'll attempt to use that key to sign your message. If you're well-behaved it'll now ask you for your pgp passphrase, which is the very thing I'm trying to avoid doing. There is one other option listed on the UseGPG page above, a timeout. You can use that to set the number of seconds mutt will consider your passphrase good, and really that's probably what you should use, but for me, it's just not what I want. I can't seem set it to value I like and I also have a few other places I use my gpg key (specifically when I build a new Ubuntu package) so I don't just need my email client to use my gpg key. So now what? GPG Agent. This is where things may get distro-specific. I use Xubuntu exclusively these days, but most of what I know about this comes from Debian pages. If you're in a non-Debian-ish world, I can't really help you except to suggest you should be able to find a package in your distro named somewhat close to gnupg-agent. Install gnupg-agent:

skynet ~sudo aptitude install gnupg-agent
[sudo] password for joe:
The following NEW packages will be installed:
gnupg-agent libassuan0{a} pinentry-gtk2{a}
0 packages upgraded, 3 newly installed, 11 to remove and 13 not upgraded.
Need to get 379 kB of archives. After unpacking 0 kB will be freed.
Do you want to continue? [Y/n/?] Y


And wait. Next we need to configure gnupg-agent. Not complicated, but it wasn't terribly obvious to me at first, despite the pretty straightforward pages I found describing it. The important things to remember here are that installing the package on Ubuntu will update the default X configuration to start up gpg-agent when X starts. This is important because gpg-agent works pretty much the same way ssh-agent works, to really be useful, you have to export an environment variable to any shell where intend to use it, telling that shell how to communicate with it. If you let it start when X starts, all shells in your X session will already know about it and you don't have to set up anything. This means, though, that it's probably best to just suck it up and log out and log back in again after you install gpg-agent. It sucks, but trust me, it's easier this way. And the next time you log in, you won't have to worry about it anymore anyway. Let's assume you ignore my advice and plan to start gpg-agent by hand (at least for this first run). Don't do that yet. We need to configure it first. The minimal useful gpg-agent configuration file (for me, at least) appears to be:

skynet ~cat ~/.gnupg/gpg-agent.conf
pinentry-program /usr/bin/pinentry-gtk-2 default-cache-ttl 86400
max-cache-ttl 86400


Which says, gpg-agent use pinentry-gtk-2 to prompt me whenever it need to prompt me for a passphrase, it should cache my passphrase for one day by default and it should never cache a passphrase for more than one day. Create yourself a ~/.gnupg/gpg-agent.conf file now. Put in whatever you like, you'll want at least a pinentry binary and select whatever cache times seem reasonable to you. Right, next, start up gpg-agent:

skynet ~eval $(gpg-agent --daemon)


You won't see any output due to the eval. It doesn't matter, all you would see would be something like this: GPG_AGENT_INFO=/tmp/gpg-7cigjL/S.gpg-agent:7425:1; export GPG_AGENT_INFO; And you'd have to paste that into any shell where you intended to use gpg-agent. If you want that information, something like this will do it for you:

skynet ~env | grep GPG_AGENT_INFO
GPG_AGENT_INFO=/tmp/gpg-7cigjL/S.gpg-agent:7425:1


Almost there. The last bit is to go back to mutt and tell it that it should use gpg-agent for passphrases if at all possible:

# consult a gpg-agent, if running, for pgp credentials set pgp_use_gpg_agent=yes


That's it. Start up mutt, compose an email and try it out.

Oh, one last caveat.  I have reliable reports that email sent out this way (presumably any RFC-compliant, PGP-signed email) breaks some versions of Good.  It certainly breaks the one being used at my work.  So, if you like explaining to folks how it's not your fault they cannot read your mail -- and not just because you have a proclivity for using ten-dollar-words -- this turns out to be a twofer.

Saturday, August 18, 2012

Never copy with just 'cp'

Something from way back on openbsd-misc@ from Otto Moerbeek. I've long ago lost the reference, unfortunately:
On Mon, 6 Dec 2004, Dave Feustel wrote:
    My original /usr partition is not big enough to hold OpenBSD source, so I have added another disk to which I have copied (cp -Rp /usr /mnt) and then have untarred source gz files from the 3.6 cdrom to /mnt. My plan is to mount this disk at /usr, replacing the partition which contains the original /usr. I noticed that the copied /usr partition is somewhat larger than the original. Is there anything else I need to do before I change the /usr entry in /etc/fstab?
Never copy just with cp -Rp , use:
       cd /usr
       pax -rw -pe . /mnt
cp will mangle hard links, soft links, device nodes and what more.
The (possibly surprising) thing to remember here is Otto's example assumes you are following his steps as outlined. Yes, both of them. pax will recreate paths all relative to . (read: here) in /mnt so if for some reason you need to be in different directories, you'll need to remember the same rules you have to remember for, say, rsync which has a similar habit of confusing me with path interpretation and giving me more nested levels than I intended.

Wednesday, August 15, 2012

Day Zero

The Linux Gazette used to have a feature in the Back Page section called 2 Cent Tips. They were small, fun little tricks, usually shell or command related, that made life easier for me. LG is largely defunct now, it seems, but I'm still finding lots of neat little tidbits of information I want to keep around for future reference. So here they are. My own 2 Cent Tips section, culled from the web, with direct references where possible. Satisfaction guaranteed or you can go do your own googling.