summaryrefslogtreecommitdiff
path: root/templates/check-puppetd.sh.erb
blob: ee2fc7a7d10044e47df4680b138418bb53a5389a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash
#
# check if puppet is running
#

PATH="$PATH:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
PID="/var/run/puppet/<%= agent_name %>.pid"
INIT="/etc/init.d/puppet"
LOCKFILE="/var/run/puppet/check-puppetd.pid"

function puppet_start {

  sleep `echo $RANDOM/2000*60 | bc`
  $INIT start

}

function puppet_restart {

  $INIT stop
  puppet_start

}

function set_lockfile {

  if [ ! -z "$LOCKFILE" ]; then
    mkdir -p `dirname $LOCKFILE`
    if ( set -o noclobber; echo "$$" > "$LOCKFILE" ) &> /dev/null; then
      trap 'unset_lockfile' INT TERM EXIT
    else
      echo "Could not create lockfile $LOCKFILE, exiting"
      exit 1
    fi
  fi

}

function unset_lockfile {

  if [ ! -z "$LOCKFILE" ]; then
    rm -f $LOCKFILE || echo "Could not remove lockfile $LOCKFILE"
  fi

}

function check_lockfile {

  local pid process

  if [ ! -z "$LOCKFILE" ] && [ -f "$LOCKFILE" ]; then
    pid="`cat $LOCKFILE 2> /dev/null`"
    process="`ps --no-headers -o comm $pid`"

    # Check lockfile again
    if [ -f "$LOCKFILE" ]; then
      if [ "$?" == "0" ] && [ "`ps --no-headers -o comm $$`" == "$process" ]; then
        echo "Another backup is running for $LOCKFILE, skipping run"
        exit
      else
        echo "Found old lockfile $LOCKFILE, removing it"
        unset_lockfile  
      fi
    fi
  fi

}

check_lockfile
set_lockfile

if [ "$1" == "restart" ]; then
  puppet_restart
elif [ ! -f "$PID" ]; then
  puppet_start
else
  running="$(ps $(cat $PID) &> /dev/null)"
  if [ "$?" != "0" ]; then
    puppet_start
  fi
fi

unset_lockfile