Showing posts with label shell. Show all posts
Showing posts with label shell. Show all posts

Saturday, March 31, 2012

Running a Command Whenever a File Changes

Edit: I actually had to republish this as I didn't understand the Blogger interface. Because of this, I added a new section where I combine this into a script that you can actually use. Enjoy.

Every once in a while you probably would like to have a command run every time a particular file changes. I know I did when I was writing some Latex based presentations with Beamer and was using the latex to dvips to gs chain of commands to compile the document into a PDF file. I came up with a way to ease these steps by detecting changes in the document's DVI file that Emacs writes for me. I later thought of a couple of other methods and figured I would put them up here in case anybody ever needed something similar. I included all of them as you never know when you need to put together a hack on some old or limited system, or just a system that you don't control and thus cannot install new software.

I decided that the interface of my little script should be to specify a file to watch, the watch file, and a command to run when it changes, the on change command. The on change command should take one argument, the watch file.

Watch File Modification Times

In this version we look at the watch file modification time and compare it to a reference time that is updated every time the watch file changes. This is definitely a cheap way to find these updates. The easiest way I could find to check the modification time of a file was to create a temporary file which acts as a time stamp. We just check which file is newer and touch the temporary file any time we want to update the time stamp.

#!/bin/bash

watched_file=$1
command=$2

# First we need a temporary file to test against
marker=$(mktemp /tmp/on-change-XXXXXX)

# We have to trap the EXIT signal as we want to clean up our tmp file
trap "rm -f $marker" EXIT

# Loop until killed
while true
do
    # If the watched_file is newer than the marker...
    if [ $watched_file -nt $marker ]
    then
        # Wait for a bit to make sure that the file is done being modified
        sleep 1
        # ... run the command ...
        $command $watched_file
        # ... and reset the marker
        touch $marker
    fi
    sleep 2
done

One thing to note is that this script, like many scripts, has a race condition in it. If it happens to detect a modification of the watch file but the modification is not yet complete, it will trigger the on change command and then probably get an error from it, then detect another modification the next iteration. This will continue until the program modifying the watched file has completed its work. This is bound to happen for short polling times (here we use two seconds) or long running programs that modify the watch file. This is the reason I added one second delays after the modification time based test. The delay is to try and give time for anything that is currently underway to complete. It helps, but of course fails to help other times.

A possible problem here is that it is easy to trick this into doing more work than it should. The watch file might be repeatedly touched but never actually modified, which would lead to unnecessary execution of the on change command. The key is to note that the newer modification time is a necessary but not sufficient condition for the file to have changed. It leads to false positives, but is very cheap.

It should be noted that, in the case of compiling Latex documents, while this can happen, it is a pretty rare event. But, if we are building a general purpose tool, it is something we should worry about.

Watch File Hash

How can we eliminate the reprocessing of identical files? File hashes.

The next technique is to poll the file for actual file changes. We don't need to keep an old copy of the file, or anything like that, we just keep track of the file's old hash value. Every two seconds (plus the time it takes to hash the file) we compute files hash and compare it to the old file's hash. If they differ, we run the specified on change command and update the stored hash value.

#!/bin/bash

watched_file=$1
command=$2

# Compute the reference hash value
hash=`md5sum $watched_file | cut -f 1 -d\ `
while true
do
    # Grab the files hash
    newhash=`md5sum $watched_file | cut -f 1 -d\ `
    # If it has changed...
    if [ $newhash != $hash ]
    then
        # ...run the command...
        $command $watched_file
        # ...and record the new hash
        hash=$newhash
    fi
    sleep 2
done

This has the advantage that it never needs to run the on change command unless there is an actual change in the file. This means that for an expensive on change command the method works very well. However, for very large watch files the hashing becomes unnecessarily expensive.

However, the race condition is still there and this time it is worse. Whereas in the modification time test method we could try to give the modifying process extra time to complete, this time we don't have that option. We just have to blindly try again until we get it right.

Use INotify

As is often the case, you find something that is a better solution than what you have hacked together after you have long since found a good enough solution to your problem. This is the case with the me and INotify.

The INotify kernel facility was designed for just the problem I was attacking. It provides, via a kernel interface, a way to hook into the file system and receive notifications on events such as reading from, writing to, opening, and closing files. If you are on one of the mainstream distros and have been keeping things even remotely up to date, you probably have an INotify ready kernel, but might not have the shell tools installed. We will be using inotifywait, which blocks until a specified file system event is triggered. In this case, we are interested in file modification events, so we will pass the option -e modify to the program. Just a note, this is taken almost verbatim from the inotifywait man page.

#!/bin/bash

watched_file=$1
command=$2

while inotifywait -e modify $watched_file; do
    # Wait a bit, in case the modifier is still working
    sleep 1
    # Then run the command
    $command $watched_file
done

This is much simpler than the other methods. A real strength here is that this is short enough that it really doesn't need to be a script at all. You can just memorize this. This is definitely a pretty good version, but it still has that race condition. So, one last version, where we will wait for the file to not be modified for a few seconds before we run the command on it. We can do this because inotifywait provides a timeout which exits with a 2 if it did timeout.

#!/bin/bash

watched_file=$1
command=$2

while inotifywait -e modify $watched_file;
do
    while [ 2 != $(inotifywait -e modify -t 1 $watched_file \
                    1> /dev/null 2> /dev/null; echo $?) ]
    do
        echo waiting...
    done
    $command $watched_file
done

This catches most of the race condition issues, I think, but the price you pay is that you have to wait at least one second after the file has been modified before the file can be processed by your script.

Of course, without a proper synchronization mechanism, which needs to be agreed upon by both programs and thus is largely incompatible with the shell idea of small self contained programs, you will never get rid of this race condition. It is firmly up to the user to ensure that two different programs are not accessing the same file at the same time (actually, I think we can go a long way towards solving this by using lsof and checking if the watched file is still open. I don't have time to explore this but lsof $watched_file seems to be promissing).

Combine The Methods

We can have the best of all of these methods by combining them into one monster script that checks for changes using INotify (with a modification time check fall back) and then confirms that the file has actually changed by comparing the file hashes. But I wont bother because this is already too long, both in words and time spent typing and editing.

Update: here it is. I changed the interface, now you specify a file and the complete command you want to run on change.

#!/bin/bash

watched_file=$1
command="${@:2}"

# We start with a bogus hash
hash=null

if which inotifywait
then
    function wait_till_unchanging()
    {
        while \
            [ $(inotifywait -e modify -t 1 $watched_file \
            1> /dev/null 2> /dev/null; echo $?) != 2 ];
        do
            echo waiting...
            sleep 1
        done
    }
else
    function wait_till_unchanging()
    {
        # Wait until there isn't a change for delay seconds
        touch $marker
        cont=1
        while [ 1 == $cont ]
        do
            cont=0
            sleep 1
            # If the watched_file is newer than the marker...
            if [ $watched_file -nt $marker ]
            then
                # reset the marker
                touch $marker
                cont=1
            fi
        done
    }
fi

if which md5sum
then
    function if_changed_run ()
    {
        # Grab the files hash
        newhash=`md5sum $watched_file | cut -f 1 -d\ `
        
        # If it has changed (this is always run the first time as $hash is null)...
        if [ $newhash != $hash ]
        then
            # ...run the command...
            $command

            # ...and record the new hash
            hash=$newhash
        fi
    }
else
    function if_changed_run ()
    {
        # ...run the command...
        $command
    }
fi

if which inotifywait
then
    while inotifywait -e modify $watched_file;
    do
        wait_till_unchanging
        if_changed_run
    done
else
    # First we need a temporary file to test against
    marker=$(mktemp /tmp/on-change-XXXXXX)

    # We have to trap the EXIT signal as we want to clean up our tmp file
    trap "rm -f $marker" EXIT

    while true
    do
        # If the watched_file is newer than the marker...
        if [ $watched_file -nt $marker ]
        then
            wait_till_unchanging
            if_changed_run
        fi
        sleep 1
    done
fi

Using It To Automate Latex Builds

I said I wanted this to make compiling Latex documents easier. In order to do that you just use something like:

on-file-change presentation.dvi dvipdf

Update: with the new interface, it looks like this:

on-file-change presentation.dvi dvipdf presentation.dvi

Of course the best method would be to figure out how to make Emacs run this post processing for me. However, I have so far failed to figure that out and this little tool is applicable to more than just this scenario anyway.

Update: I did find out how to do this the right way in Emacs. Turns out there are a lot of different ways and not all of them work. For instance, the first answer on that page doesn't work for me. I use AuCTeX, which means that you can temporarily change the Latex compilation mode to use pdflatex by using "C-c C-t C-p" in the buffer or permanently set it by adding (setq TeX-PDF-mode t) in your .emacs file.

Friday, December 10, 2010

Problems with cooling the MacBook Pro (1,2)



I have a first generation MacBook Pro which, after living in shame with OS X for several years, I finally bit the bullet and installed Ubuntu on it. And it was certainly biting a bullet; Apple computers are some of the least supported computers on the market when it comes to Ubuntu and the Linux kernel in general. I imagine this is strongly linked with the closed nature of their design. Despite this, the gains I have seen in capability of the machine far outweigh the annoyances of the setup, the reduced battery life, and when using 9.04, the many graphics errors that made compiz and anything with OpenGL unusable (the new ATI drivers are much better, at least for me).

One of the most annoying problems, however, is that (at least) the first generation MacBook Pros run very hot with Ubuntu. Largely this seems to be due to a bug in the fan speed control. It does increase the fan speed with temperature, but it seems that the temperature of the CPU needs to reach upwards of 100 degrees C before you will notice the fans kicking in. At 100 degrees C the outside case (aluminum and often in contact with your skin) may reach an uncomfortable temperature. I suspect that this might be the result of the fan control module reading its temperature data from the wrong sensor, i.e. scaling the fan based on the case temperature instead of the CPU, but let's ignore the root of the problem and consider how to fix it.

Several people have come up with methods of controlling the temperature, like this. I wrote my own because I thought this was too complicated, but mine has grown in complexity with time. I just have this running in the background as root.

#!/bin/bash

let 'speed=1000'

while true
do
    temp=`cat /sys/devices/platform/applesmc.768/temp3_input`
    let 'new_speed=(1000 + (5000*((temp-35000)/(100*(60-30))))/10)'
    if [ $new_speed -lt $speed ]
    then
        # Go down in speed quickly
        let 'speed=new_speed'
    fi
    # Average to provide some damping
    let 'speed=(speed+new_speed)/2'
    if [ $speed -gt 6000 ]; then speed=6000; fi
    if [ $speed -lt 1000 ]; then speed=1000; fi
    echo $speed > /sys/devices/platform/applesmc.768/fan1_min
    echo $speed > /sys/devices/platform/applesmc.768/fan2_min
    sleep 2
done 

But even this wasn't enough to keep the temperature under control. I have read in many places that the maximum fan speed for the MacBook Pro (1,2) is 6000 RPM (although it seems to go up to 7000 RPM). Even when the fan speed is pegged at 6000 RPM, one process at 100% CPU will raise the temperature up to 100 degrees C (already too hot for laptop work), and anything running on the other core will often times raise the temperature enough to cause the system to shutdown from overheating. This is a big problem: it seems that the fans on the MacBook Pro (1,2) are not able to cool the CPU appropriately at maximum load.

Today I finally found a way to keep the temperature under control: by changing the CPU scaling behavior to powersave mode. This basically locks each core to its minimal clock frequency, or 1 GHz for me. Interestingly, this doesn't seem to extend my battery life at all. What it does do is hold the CPU temperature at below 60 degrees C when the above script is despite the system load. Of course, CPU bound programs run at half the speed.

Never mind the matter of why Ubuntu's built in thermal throttling isn't kicking in, setting the powersave governor will allow us to script our own thermal throttling. I plan, in the near future, to hack together a solution using cpufreq-selector that will switch the CPU scaling governor when the system gets too hot or if the system is running on battery power (as stated earlier, this isn't for extended battery life. It's just that when I am on battery power it is more likely that the computer is sitting on my lap or I'm in a meeting and a noisy fan would bother others). This sort of thing makes me wonder if Apple used thermal throttling when they configured OS X for the first gen MBPros. The computer certainly ran hot in OS X, but it never crashed due to overheating. The current CPU frequency was not readily apparent from with OS X (or at least I didn't see it). I wonder if all those times I was running at maximum CPU, I was actually running at 1 GHz or 1.33 GHz so that the system wouldn't shutdown. Makes me pretty happy that my place of work went with my suggestion to buy the lowest clock speed computer. I could probably test this by booting into OS X and running a benchmark and comparing to the result under Ubuntu.

I did a little research and it seems that the Core2 Duos dropped support for ACPI Thermal Zone, which is responsible for thermal throttling. The first gen MBP has a Core Duo, so maybe it is similar. Turns out you can switch between thermal throttling CPU states by writing the desired state (say T1) to /proc/acpi/processor/CPU0/throttling. Even at the most limiting throttle states, the CPU still runs hotter than running with the powersave governor at T0. That doesn't make a lot of sense.

Sunday, October 3, 2010

scp and symlinks



Many would be surprised to hear that several common GNU/Linux programs don't handle symlinks properly.  By that, of course I mean that they don't handle them the way I would want them to, but close enough.  For instance, if you want to copy a directory from one server to another, the command scp -r source-dir target-dir looks very attractive. Unfortunately scp follows symlinks, meaning instead of copying a link to some other part of the file system, it instead copies that other part of the file system.  For a heavily symlinked directory this can be disastrous.

The correct and fool proof way to grab a portion of a file system from a server is to use tar.  Don't worry, this doesn't mean you have to actually create a tar file, you can use tar to pipe the output over ssh and untar it on the other side.

tar -c some-files some-dirs \
  | ssh -C my-server "tar -C path/to/extract/root -x"

If you want to download from a server…

ssh -C my-server \
  "tar -C path/to/archive/root -c some-files some-dirs" | tar -x

The -C switch to tar tells it to change directories prior to performing the operation.  The -C switch to ssh tells it to compress the traffic with gzip like compression.  You can even use a better compression if you have a slower connection to the server or a pay by the bit plan, by including lzma or p7zip in the pipe, or just passing a -j switch to both tar commands.  By the way, p7zip also treats symlinks badly and you need to protect any hierarchy with a tar archive.

In case you are wondering why scp defaults to bad behavior, well all file systems aren't created equal.  Since you are copying to a server and who knows what file system they have (for instance, it could be FAT), you might not be able to create symlinks there.  So it is an alright decision to only copy files and not links to files.  If you only deal with, hmmm, how to put it, modern file systems, this sure seems like incorrect behavior.  Maybe someday this will change, but in the mean time, the tar method works great and has been the method of choice since tar, pipes, and networks existed.

But wait, there's more.  Even if you don't have symlinks, piping a tar archive over ssh might be a good idea.  Since scp operates on individual files, it incurs an overhead on each one.  If you have many small files you want to transfer, small enough that the actual transfer time is almost insignificant, this overhead can become quite costly.  In these cases the tar method will be faster.

smithzv@ciabatta:~$ ssh scandal "ls -R kappa-slices-3d | wc"
   3993    3958  117715

smithzv@ciabatta:~$ ssh scandal "du -sh kappa-slices-3d"
36M     kappa-slices-3d

smithzv@ciabatta:~$ time scp -qr scandal:./kappa-slices-3d dat/

real    0m8.004s
user    0m1.152s
sys     0m1.184s

smithzv@ciabatta:~$ time ssh scandal "tar -c kappa-slices-3d" \
                      | tar -x -C ~/dat/

real    0m2.442s
user    0m0.824s
sys     0m0.728s

This directory on our scandal cluster has 4000 small files in it which total up to 36 MB.  Performing the piped tar method takes about a third the time of the recursive scp copy.  Also, I should point out that the scp process will, as far as I know, at best be as fast as the taring procedure.  Of course, note that we didn't use compression here as this is a transfer of already compressed files over a fast connection and compression just slows both commands down.  If you ever need to backup your computer over a your home LAN so you can reinstall an OS or something, this is a lifesaver (or at least a time saver).

So, piping a tar archive over ssh is a great tool.  That being said, there is a program that does so much more and might be a better choice as long as it is installed on both systems; it's called rsync. rsync follows symlinks just like scp by default (for the same reasons), but it has a switch, -a for archive mode, that allows it to perform the symlink preserving behavior as seen above.  rsync has other benefits over just an ssh or scp copy (like incremental updates: i.e. only transmitting data that has changed) and really should be preferred in most cases if it is an option, but you have to read the man page first or it will bite you, especially if you have heavily internalized the way cp and scp work.