Skip to content

Instantly share code, notes, and snippets.

@wernerb
Last active August 29, 2015 14:03
Show Gist options
  • Save wernerb/6c367e463678a676945f to your computer and use it in GitHub Desktop.
Save wernerb/6c367e463678a676945f to your computer and use it in GitHub Desktop.
This is a POSIX compatible init script for jclouds
#!/bin/sh
export INSTANCE_NAME="test"
export INSTANCE_HOME="/tmp/test"
export LOG_DIR="$INSTANCE_HOME"
forget () {
mkdir -p "$LOG_DIR"
if test ! -f "$LOG_DIR/pid" ; then
nohup "$INSTANCE_HOME/$INSTANCE_NAME.sh" > "$LOG_DIR/stdout.log" 2> "$LOG_DIR/stderr.log" &
echo $! > "$LOG_DIR/pid"
else
echo "$INSTANCE_NAME" already running pid $(cat "$LOG_DIR/pid")
return 1
fi
}
stream () {
offset=$(du -b "$1" | cut -f1)
head -q -c "$offset" "$1"
offset=$(expr "$offset" + 1 )
while kill -0 $(cat "$LOG_DIR/pid") >/dev/null 2>&1
do
sleep 0.1
cursize=$(du -b "$1" | cut -f1)
tail -q -c "+$offset" "$1" | head -q -c $(expr "$cursize" + 1 - "$offset")
offset=$(expr "$cursize" + 1 )
done
tail -q -c "+$offset" "$1"
exit $(cat "$LOG_DIR/rc")
}
case $1 in
init)
mkdir -p $INSTANCE_HOME
# create runscript header
cat > "$INSTANCE_HOME/test.sh" <<- "END_OF_JCLOUDS_SCRIPT"
#!/bin/sh
export PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin
export INSTANCE_NAME="test"
export INSTANCE_HOME="/tmp/test"
export LOG_DIR="$INSTANCE_HOME"
END_OF_JCLOUDS_SCRIPT
# add desired commands from the user
cat >> "$INSTANCE_HOME/test.sh" <<- "END_OF_JCLOUDS_SCRIPT"
cd $INSTANCE_HOME
rm -f $INSTANCE_HOME/rc
trap 'echo $?>$INSTANCE_HOME/rc && rm -f "$LOG_DIR/pid"' 0 1 2 3 15
##### Start of my little test script
i=0
max=500
while [ $i -lt $max ]
do
sleep 0.1
echo $i
true $((i=i+1))
done
exit 0
##### End of my little test script
END_OF_JCLOUDS_SCRIPT
# add runscript footer
cat >> $INSTANCE_HOME/test.sh <<- "END_OF_JCLOUDS_SCRIPT"
exit $?
END_OF_JCLOUDS_SCRIPT
chmod u+x "$INSTANCE_HOME/test.sh"
;;
status)
pid=$(cat "$LOG_DIR/pid") || exit 1
kill -0 $pid || exit 1
echo $pid
;;
stop)
FOUND_PID=$(cat "$LOG_DIR/pid") || exit 1
kill -0 $FOUND_PID || exit 1
echo stopping $FOUND_PID
kill -9 $FOUND_PID && rm -f "$LOG_DIR/pid"
;;
start)
forget || exit 1
;;
stdout)
cat "$LOG_DIR/stdout.log"
;;
stderr)
cat "$LOG_DIR/stderr.log"
;;
exitstatus)
test -f "$LOG_DIR/rc" && cat "$LOG_DIR/rc"
;;
tail)
tail "$LOG_DIR/stdout.log"
;;
tailerr)
tail "$LOG_DIR/stderr.log"
;;
stream)
stream "$LOG_DIR/stdout.log"
;;
streamerr)
stream "$LOG_DIR/stderr.log"
;;
run)
mkdir -p "$LOG_DIR"
echo $$ > "$LOG_DIR/pid"
"$INSTANCE_HOME/$INSTANCE_NAME.sh"
;;
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment