- only source configuration if it exists to avoid bootstrap warning
[myplc.git] / plc.d / functions
1 # -*-Shell-script-*-
2 #
3 # Common functions for PLC startup/shutdown scripts
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # $Id: functions,v 1.2 2006/04/07 04:27:56 mlhuang Exp $
9 #
10
11 export PATH=/sbin:/bin:/usr/bin:/usr/sbin
12
13 # Source function library
14 . /etc/init.d/functions
15
16 # Source configuration if it exists
17 if [ -f /etc/planetlab/plc_config ] ; then
18     . /etc/planetlab/plc_config
19 fi
20
21 # Total number of errors
22 ERRORS=0
23
24 # Count the exit status of the last command
25 check ()
26 {
27     ERRORS=$(($ERRORS+$?))
28 }
29
30 # Print status header
31 dialog ()
32 {
33     echo -n "PLC: $*: " >&3
34 }
35
36 # Print result
37 result ()
38 {
39     if [ $ERRORS -eq 0 ] ; then
40         success "$*" >&3
41     else
42         failure "$*" >&3
43     fi
44     echo >&3
45 }
46
47 # Start up a program with a plc_ prefix
48 plc_daemon ()
49 {
50     base=${1##*/}
51
52     # See if it's already running. Look *only* at the pid file.
53     if [ -f /var/run/plc_${base}.pid ]; then
54         local line p
55         read line < /var/run/plc_${base}.pid
56         for p in $line ; do
57                 [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
58         done
59     fi
60
61     [ -n "${pid:-}" -a -z "${force:-}" ] && return
62
63     # And start it up.
64     (exec -a plc_${base} $*)
65     ret=$?
66
67     if [ -f /var/run/${base}.pid ] ; then
68         mv /var/run/${base}.pid /var/run/plc_${base}.pid
69     fi
70
71     return $ret
72 }
73
74 # Print IP address of hostname if resolvable
75 gethostbyname ()
76 {
77     perl -MSocket -e '($a,$b,$c,$d,@addrs) = gethostbyname($ARGV[0]); print inet_ntoa($addrs[0]) . "\n";' $1 2>/dev/null
78 }
79
80 # Print the CNAME of an SSL certificate
81 ssl_cname ()
82 {
83     openssl x509 -noout -in $1 -subject | \
84         sed -n -e 's@.*/CN=\([^/]*\).*@\1@p'
85 }
86
87 # Forcefully make a symlink
88 symlink ()
89 {
90     mkdir -p $(dirname $2)
91     rm -f $2
92     ln -s $1 $2
93 }
94
95 # Make copies of stdout and stderr. The plc initscript redirects
96 # stdout and stderr to a logfile if -v is not specified.
97 [ ! -e /dev/fd/3 ] && exec 3>&1
98 [ ! -e /dev/fd/4 ] && exec 4>&2