From a6d1e32948863e3f91a4c129b870988b8941e777 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?marc=20Ren=C3=A9=20Sch=C3=A4dler?= Date: Wed, 13 Nov 2013 11:59:52 +0100 Subject: [PATCH] Add "cache.sh", a script that caches a programs output --- bsp/default/root_file_system/etc/cache.sh | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100755 bsp/default/root_file_system/etc/cache.sh diff --git a/bsp/default/root_file_system/etc/cache.sh b/bsp/default/root_file_system/etc/cache.sh new file mode 100755 index 0000000..47e29df --- /dev/null +++ b/bsp/default/root_file_system/etc/cache.sh @@ -0,0 +1,38 @@ +#!/bin/ash + +[ $# -ge 2 ] || exit 1 + +CACHEDIR='/tmp/cache' + +MAXAGE="$1" +shift 1 +COMMAND="$@" + +# generate an ID based on the command to be executed +ID=$(echo "$COMMAND" | md5sum | cut -d" " -f1) || exit 1 + +CACHED=false + +# create directory for cached output +[ -d "$CACHEDIR" ] || mkdir -p "$CACHEDIR" +[ -d "$CACHEDIR" ] || exit 1 + +# if there is an entry for the command to be executed... +if [ -f "$CACHEDIR/$ID/timestamp" ]; then + TIMESTAMP=$(cat "$CACHEDIR/$ID/timestamp") + CURRENTTIME=$(date +%s) + # ...check the timestamp and determine if it is sufficiently recent + if [ -n "$TIMESTAMP" ] && [ $(($CURRENTTIME-$TIMESTAMP)) -lt $MAXAGE ] && [ -f "$CACHEDIR/$ID/output" ]; then + CACHED=true + fi +fi + +# if there is cached output data just put it out... +if $CACHED; then + cat "$CACHEDIR/$ID/output" +else +# ...if not execute the command and save the output and a timestamp + [ -d "$CACHEDIR/$ID" ] || mkdir -p "$CACHEDIR/$ID" + $COMMAND | tee "$CACHEDIR/$ID/output" + date +%s > "$CACHEDIR/$ID/timestamp" +fi