runcached.sh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/bin/bash
  2. # Run an expensive command as frequently as you want through this.
  3. # Command output will be kept for $cacheperiod and replayed for subsequent calls
  4. # Possible usage: query multiple EMC parameters with zabbix in random order,
  5. # by running the EMC interfacing command just once, transparrently to zabbix.
  6. # sivann 2012
  7. # Thu Jun 14 13:11:28 EEST 2012
  8. ####################################################33
  9. cacheperiod=60 #seconds
  10. savedir="/tmp"
  11. ####################################################33
  12. for arg in "$@"
  13. do
  14. cmd=( "${cmd[@]}" "$arg" )
  15. let "i+=1"
  16. done
  17. cmdmd5=`echo -n "${cmd[@]}" |md5sum|awk '{print $1}'`
  18. #random sleep to avoid racing condition of creating the pid on the same time
  19. sleep .$[ ( $RANDOM % 10 ) + 1 ]s
  20. #don't run the same command in parallel, wait for it to finish the 1st time
  21. count=15
  22. while [ -f /tmp/${cmdmd5}-runcached.pid ]; do
  23. sleep 2
  24. count=`expr $count -1`
  25. if [ $count -eq 0 ]; then
  26. echo "timeout waiting for runcached.pid to be removed"
  27. exit -1
  28. fi
  29. done
  30. echo $$ >/tmp/${cmdmd5}-runcached.pid
  31. cachedir="/tmp"
  32. cmddatafile="${cachedir}/${cmdmd5}.data"
  33. cmdexitcode="${cachedir}/${cmdmd5}.exitcode"
  34. cmdfile="${cachedir}/${cmdmd5}.cmd"
  35. ##########
  36. function runit {
  37. "${cmd[@]}" 2>&1 | tee $cmddatafile 1>/dev/null 2>&1
  38. exitcode=${PIPESTATUS[0]}
  39. echo $exitcode > $cmdexitcode
  40. echo "${cmd[@]}" > $cmdfile
  41. }
  42. if [ ! -f "$cmddatafile" ] ; then runit ; fi
  43. lastrun=`stat -c %Y $cmddatafile`
  44. currtime=`date +%s`
  45. diffsec=$(( (currtime - lastrun) ))
  46. if [ "$diffsec" -ge "$cacheperiod" ] ; then
  47. runit
  48. fi
  49. cat $cmddatafile
  50. /bin/rm /tmp/${cmdmd5}-runcached.pid
  51. exit `cat $cmdexitcode`