Watchfolders - Part 2

1 minute read

The watcher script

Creating a script that will leverage INOTIFY tools to kick off a process is actually quite simple. The hardest part is making it as generic as possible so that it can be easily modified for multiple processes. I decided to break the process into two parts, one that monitors the folder or file and then one that moves the files. This way I could maintain one single script to move the files and then define variables in the watcher process that make it unique. Of course, you dont have to fire off a file move script for every watcher. You can add your own script that gets called by each watcher process.

The most annoying part of implementing this is that when I started to move the files people kept added in requests to upgrade the process. The features that I added in addition to the original source / destination directory are a notify list and an alternate filename. I will explain the alternate filename in the next post.

I originally intended the script to run as an init.d script, but the target system was RHEL7 and I decided to make it as a systemd service. Here is the systemd template that I created for the watcher process:

This script is put into /usr/lib/systemd/scripts/


#!/bin/bash
#VARIABLES - change these as they are passed to the file move script
     
monitor="MONITORFOLDERNAME"
     
watchdir=/watchfolders/FOLDER/NAME/
outdir=/output/FOLDER/NAME/
notify="distribution.group@email.address"
filename="outputfilename.ext"
     
RETVAL=0
     
start() {
    printf "Starting inotify monitor:  $monitor \n"
    RETVAL=1
    inotifywait -m -q -r -e close_write $watchdir | while read path action file; do
        /scripts/filemove.sh $watchdir $outdir $notify $filename $monitor
    done >> /var/log/watchlog_$monitor 2>&1 &
    RETVAL=$?
    return $RETVAL
}
     
stop() {
    printf "Stopping inotify monitor:  $monitor \n"
    pkill -f $watchdir
    RETVAL=$?
    return $RETVAL;
}
     
restart() {
    stop
    start
}
     
case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        restart
    ;;
    *)
        printf "Usage: %s {start|stop|restart}\n" "$0"
    exit 1
esac
     
exit $?

« Watchfolders Part 1 » Watchfolders Part 3