Browse Source

Write background job script

Samuel W. Flint 9 months ago
parent
commit
2c4888b77a
1 changed files with 77 additions and 6 deletions
  1. 77 6
      in-progress/background-job

+ 77 - 6
in-progress/background-job

@@ -4,16 +4,15 @@ NAME=""
 COMMAND_FILE=""
 ENV_FILE=""
 MAIL_NOTIFICATION=""
-NOTIFICATION_SCRIPT=""
 PID=$$
 
-USAGE="Usage: `basename $0` [-h] [-n name] [-e env-file] [-m mail-address] [-N notifier]"
+USAGE="Usage: `basename $0` [-h] [-n name] [-e env-file] [-m mail-address] COMMAND+"
 
 while getopts hn:e:m:N: OPT; do
     case "$OPT" in
         h)
             echo $USAGE
-            exit 0
+            exit 1
             ;;
         n)
             NAME=$OPTARG
@@ -24,12 +23,84 @@ while getopts hn:e:m:N: OPT; do
         m)
             MAIL_NOTIFICATION=$OPTARG
             ;;
-        N)
-            NOTIFICATION_SCRIPT=$OPTARG
-            ;;
         \?)
             echo $USAGE >&2
             exit 1
             ;;
     esac
 done
+
+shift $((OPTIND - 1))
+
+if [ -z "${NAME}" ] ; then
+    echo "A job name is required." >&2
+    exit 1
+fi
+
+RUN_SCRIPT=$(mktemp)
+
+cat <<EOF > "${RUN_SCRIPT}"
+#!/bin/sh
+
+FN="${RUN_SCRIPT}"
+JOB_NAME="${NAME}"
+MAIL_NOTIFICATION="${MAIL_NOTIFICATION}"
+
+OUTPUT_FILE=\$(mktemp)
+TIME_FILE=\$(mktemp)
+START_TIME=\$(date)
+EOF
+
+if [ -e "${ENV_FILE}" ] ; then
+    cat "${ENV_FILE}" >> "${RUN_SCRIPT}"
+fi
+
+cat <<EOF >> "${RUN_SCRIPT}"
+
+env time -o \${TIME_FILE} $@ 2>&1 | tee \${OUTPUT_FILE}
+
+cat \${TIME_FILE}
+
+END_TIME=\$(date)
+
+EOF
+
+if [ ! -z "${MAIL_NOTIFICATION}" ] ; then
+    cat <<EOF >> "${RUN_SCRIPT}"
+
+MESSAGE_FILE=\$(mktemp)
+
+cat <<EOM > "\${MESSAGE_FILE}"
+Job \${JOB_NAME} has completed.  The output is attached.
+
+Start time: \${START_TIME}
+End time  : \${END_TIME}
+
+Process Time/Usage Statistics:
+EOM
+
+cat "\${TIME_FILE}" >> "\${MESSAGE_FILE}"
+
+cat <<EOM >> "\${MESSAGE_FILE}"
+
+FN="${RUN_SCRIPT}"
+JOB_NAME="${NAME}"
+MAIL_NOTIFICATION="${MAIL_NOTIFICATION}"
+ENV_FILE="${ENV_FILE}"
+EOM
+
+mail -s "Job \${JOB_NAME} complete" -a "\${OUTPUT_FILE}" "\${MAIL_NOTIFICATION}" < "\${MESSAGE_FILE}"
+
+rm "\${MESSAGE_FILE}"
+EOF
+fi
+
+cat <<EOF >> "${RUN_SCRIPT}"
+rm "\${OUTPUT_FILE}"
+rm "\${TIME_FILE}"
+rm "\${FN}"
+
+EOF
+
+screen -d -S ${NAME} -m ${RUN_SCRIPT}
+