Various tweaks for myplc-native (not thoroughly tested yet) :
[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$
9 #
10
11 export PATH=/sbin:/bin:/usr/bin:/usr/sbin
12
13 # Source function library
14 . /etc/init.d/functions
15
16 # Total number of errors
17 ERRORS=0
18
19 # Count the exit status of the last command
20 check ()
21 {
22     ERRORS=$(($ERRORS+$?))
23 }
24
25 # Print status header
26 dialog ()
27 {
28     echo -n "PLC: $*: " >&3
29 }
30
31 # Print result
32 result ()
33 {
34     if [ $ERRORS -eq 0 ] ; then
35         success "$*" >&3
36     else
37         failure "$*" >&3
38     fi
39     echo >&3
40 }
41
42 # Start up a program with a plc_ prefix
43 plc_daemon ()
44 {
45     base=${1##*/}
46
47     # See if it's already running. Look *only* at the pid file.
48     if [ -f /var/run/plc_${base}.pid ]; then
49         local line p
50         read line < /var/run/plc_${base}.pid
51         for p in $line ; do
52                 [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
53         done
54     fi
55
56     [ -n "${pid:-}" -a -z "${force:-}" ] && return
57
58     # And start it up.
59     # Thierry -- June 18 2007
60     # when invoking, e.g. service plc start httpd from an ssh connection
61     # ssh stupidly hangs when everything is done
62     # it turns out the forked ssh daemon exhibits the following stack at that point
63     # (gdb) where
64     # #0  0x001d6402 in __kernel_vsyscall ()
65     # #1  0x003c2e7d in ___newselect_nocancel () from /lib/libc.so.6
66     # #2  0x004387b4 in main () from /usr/sbin/sshd
67     # So I figured the various file descriptors used were not properly closed
68     (exec 3>&- 4>&- ; exec -a plc_${base} $*)
69     ret=$?
70
71     if [ -f /var/run/${base}.pid ] ; then
72         mv /var/run/${base}.pid /var/run/plc_${base}.pid
73     fi
74
75     return $ret
76 }
77
78 # Print IP address of hostname if resolvable
79 gethostbyname ()
80 {
81     python -c 'import socket; import sys; print socket.gethostbyname(sys.argv[1])' $1 2>/dev/null
82 }
83
84 # Forcefully make a symlink
85 symlink ()
86 {
87     mkdir -p $(dirname $2)
88     rm -f $2
89     ln -s $1 $2
90 }
91
92 # Argument(s) or stdin to lowercase stdout
93 lower ()
94 {
95     if [ ${#*} -ge 1 ] ; then
96         tr A-Z a-z <<<$*
97     else
98         tr A-Z a-z
99     fi
100 }
101
102 # Argument(s) or stdin to uppercase stdout
103 upper ()
104 {
105     if [ ${#*} -ge 1 ] ; then
106         tr a-z A-Z <<<$*
107     else
108         tr a-z A-Z
109     fi
110 }
111
112 # Make copies of stdout and stderr. The plc initscript redirects
113 # stdout and stderr to a logfile if -v is not specified.
114 [ ! -e /proc/self/fd/3 ] && exec 3>&1
115 [ ! -e /proc/self/fd/4 ] && exec 4>&2