]> git.pld-linux.org Git - projects/rc-scripts.git/blob - lib/functions
move also functions to /lib/rc-scripts (symlink preserved)
[projects/rc-scripts.git] / lib / functions
1 #!/bin/sh - keep it for file(1) to get bourne shell script result
2 # functions     This file contains functions to be used by most or all
3 #               shell scripts in the /etc/rc.d/init.d directory.
4 #
5 # $Id$
6 #
7 # Author:       Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
8 # Hacked by:    Greg Galloway and Marc Ewing
9 # Modified for PLD Linux by:
10 #               Marek Obuchowicz <elephant@pld-linux.org>
11 #               Arkadiusz Miśkiewicz <misiek@pld-linux.org>
12 #               Michał Kochanowicz <mkochano@pld-linux.org>
13 #               Łukasz Pawelczyk <havner@pld-linux.org>
14
15 # First set up a default search path.
16 export PATH="/sbin:/usr/sbin:/bin:/usr/bin"
17
18 # Set defaults
19 if [ -z "$COLUMNS" -o -z "$LINES" ]; then
20         _setterm() {
21                 set -- $(stty size 2>/dev/null)
22                 LINES=${LINES:-$1}
23                 COLUMNS=${COLUMNS:-$2}
24         }
25         _setterm
26         unset _setterm
27 fi
28 [ -z "$LINES" ] || [ "$LINES" -le 0 ] && LINES=40
29 [ -z "$COLUMNS" ] || [ "$COLUMNS" -le 0 ] && COLUMNS=80
30 export LINES COLUMNS
31 INIT_COL=$((COLUMNS - 13))
32
33 # Set colors
34 RED=1
35 GREEN=2
36 YELLOW=3
37 BLUE=4
38 MAGENTA=5
39 CYAN=6
40 WHITE=7
41 NORMAL=15
42 # Bold definition (second parameter to termput setaf)
43 BOLD=1
44 NOBOLD=0
45 # Default colors
46 CBRACKETS="$CYAN"       # brackets [ ] color
47 CDONE="$GREEN"          # DONE and WORK color
48 CBUSY="$MAGENTA"        # BUSY color
49 CFAIL="$RED"            # FAIL and DIED color
50 CPOWEREDBY="$CYAN"      # "Powered by" color
51 CPLD="$GREEN"           # "PLD Linux Distribution" color
52 CI="$RED"               # Capital I color (press I to enter interactive startup)
53 CRESMAN="$GREEN"        # "Resource Manager" color
54 CHARS=""                # Characters displayed on the beginning of show line
55 CCHARS="$NORMAL"        # Color of these characters (look at /etc/sysconfig/init-colors.gentoo example)
56
57 # save from env, set by /sbin/service
58 env_upstart=$USE_UPSTART
59
60 # Source configuration if available - may override default values
61 [ -r /etc/sysconfig/init-colors ] && . /etc/sysconfig/init-colors
62 [ -r /etc/sysconfig/system ] && . /etc/sysconfig/system
63 [ -r /etc/sysconfig/bootsplash ] && . /etc/sysconfig/bootsplash
64
65 [ "$env_upstart" ] && USE_UPSTART=$env_upstart
66
67 if [ -z "$VSERVER" -o "$VSERVER" = "detect" ]; then
68         {
69                 while read _f _ctx; do
70                         [ "$_f" = "VxID:" -o "$_f" = "s_context:" ] && break
71                 done </proc/self/status
72         } 2>/dev/null
73         if [ -z "$_ctx" -o "$_ctx" = "0" ]; then
74                 VSERVER=no
75         else
76                 VSERVER=yes
77         fi
78         unset _f _ctx
79 fi
80
81 # VSERVER_ISOLATION_NET = isolation only inside of vserver guests
82 if [ -z "$VSERVER_ISOLATION_NET" -o "$VSERVER_ISOLATION_NET" = "detect" ]; then
83         VSERVER_ISOLATION_NET=no
84         if [ "$VSERVER" = "yes" ]; then
85                 if [ -f /proc/self/nsproxy ]; then
86                         {
87                                 while read _t _data; do
88                                         [ "$_t" = "net:" ] && break
89                                 done < /proc/self/nsproxy
90                         } 2> /dev/null
91                 else
92                         # assume old kernel mode
93                         VSERVER_ISOLATION_NET=yes
94                 fi
95                 if [ "${_data##*\(}" = "I)" ]; then
96                         VSERVER_ISOLATION_NET=yes
97                 fi
98                 unset _f _data
99         fi
100 fi
101
102 # we need to know in functions if we were called from a terminal
103 if [ -z "$ISATTY" ]; then
104         [ -t ] && ISATTY=yes || ISATTY=no
105         export ISATTY
106 fi
107
108 is_yes() {
109         # Test syntax
110         if [ $# = 0 ]; then
111                 msg_usage " is_yes {value}"
112                 return 2
113         fi
114
115         # Check value
116         case "$1" in
117         yes|Yes|YES|true|True|TRUE|on|On|ON|Y|y|1)
118                 # true returns zero
119                 return 0
120                 ;;
121         *)
122                 # false returns one
123                 return 1
124                 ;;
125         esac
126 }
127
128 is_no() {
129         # Test syntax
130         if [ $# = 0 ]; then
131                 msg_usage " is_no {value}"
132                 return 2
133         fi
134
135         case "$1" in
136         no|No|NO|false|False|FALSE|off|Off|OFF|N|n|0)
137                 # true returns zero
138                 return 0
139                 ;;
140         *)
141                 # false returns one
142                 return 1
143                 ;;
144         esac
145 }
146
147 # checks if file is empty
148 # empty lines and lines beginning with hash are ignored
149 is_empty_file() {
150         [ -s "$1" ] || return 0
151         grep -vqE "^(#|[[:blank:]]*$)" "$1" && return 1 || return 0
152 }
153
154 # returns OK if $1 contains $2
155 strstr() {
156         local a=$2
157         [ "${1#*$a*}" = "$1" ] && return 1
158         return 0
159 }
160
161 if is_yes "$FASTRC" || is_yes "$IN_SHUTDOWN"; then
162         RC_LOGGING=no
163 fi
164
165 if is_no "$RC_LOGGING"; then
166         initlog() {
167                 RESULT=0
168                 while [ "$1" != "${1##-}" ]; do
169                         case $1 in
170                         -c)
171                                 shift
172                                 $1
173                                 RESULT=$?
174                                 break
175                                 ;;
176                         *)
177                                 shift
178                                 ;;
179                         esac
180                 done
181                 return $RESULT
182         }
183 fi
184
185 kernelver() {
186         local _x _y _z v v1 old_IFS ver
187         {
188                 read _x _y v _z
189                 old_IFS=$IFS
190                 # strip _* or -* from versions like: "2.6.25_vanilla-1", "2.6.25-1"
191                 IFS='_-'
192                 set -- $v
193                 v1=${1}
194                 IFS='.'
195                 set -- $v1
196                 IFS=$old_IFS
197
198                 ver=${3}
199                 while [ ${#ver} -lt 3 ]; do ver="0$ver"; done
200                 ver="$2$ver"
201                 while [ ${#ver} -lt 6 ]; do ver="0$ver"; done
202                 ver="$1$ver"
203                 while [ ${#ver} -lt 9 ]; do ver="0$ver"; done
204                 echo $ver
205         } < /proc/version
206 }
207
208 kernelverser() {
209         local _x _y _z v v1 old_IFS ver
210         {
211                 read _x _y v _z
212                 old_IFS=$IFS
213                 # strip _* or -* from versions like: "2.6.25_vanilla-1", "2.6.25-1"
214                 IFS='_-'
215                 set -- $v
216                 v1=${1}
217                 IFS='.'
218                 set -- $v1
219                 IFS=$old_IFS
220                 ver=$2
221                 while [ ${#ver} -lt 3 ]; do ver="0$ver"; done
222                 ver="$1$ver"
223                 while [ ${#ver} -lt 6 ]; do ver="0$ver"; done
224                 echo $ver
225         } </proc/version
226 }
227
228 kernelvermser() {
229         local _x _y _z v v1 old_IFS ver
230         {
231                 read _x _y v _z
232                 old_IFS=$IFS
233                 # strip _* or -* from versions like: "2.6.25_vanilla-1", "2.6.25-1"
234                 IFS='_-'
235                 set -- $v
236                 v1=${1}
237                 IFS='.'
238                 set -- $v1
239                 IFS=$old_IFS
240                 ver="$1"
241                 while [ ${#ver} -lt 3 ]; do ver="0$ver"; done
242                 echo $ver
243         } </proc/version
244 }
245
246 # Colors workaround
247 termput() {
248         is_yes "$ISATTY" || return
249
250         if is_yes "$FASTRC" || is_no "$TPUT"; then
251                 case "$1" in
252                 hpa)
253                         echo -ne "\033[$(($2+1))G"
254                         ;;
255                 cuu*)
256                         echo -ne "\033[${2}A"
257                         ;;
258                 el)
259                         echo -ne "\033[0K"
260                         ;;
261                 setaf)
262                         local ISBOLD
263                         if [ -n "$3" ]; then
264                                 ISBOLD="$3"
265                         else
266                                 ISBOLD="$NOBOLD";
267                         fi
268                         is_yes "$COLOR_INIT" && echo -ne "\033[${ISBOLD};3${2}m"
269                         ;;
270                 op)
271                         termput setaf $NORMAL
272                         ;;
273                 esac
274         else
275                 case "$1" in
276                 hpa | cuu* | el)
277                         tput "$@"
278                         ;;
279                 setaf)
280                         if [ "$3" = "1" ]; then tput bold; else tput sgr0; fi
281                         is_yes "$COLOR_INIT" && tput setaf "$2"
282                         ;;
283                 op)
284                         termput setaf $NORMAL
285                         ;;
286                 esac
287         fi
288 }
289
290 if [ ! -x /bin/printf ]; then
291         # printf equivalent
292         # FIXME: buggy when single or double quotes in message!
293         printf() {
294                 local text m
295                 text="$1"
296                 shift
297                 if [ $# -gt 0 ]; then
298                         m="$1"
299                         shift
300                         while [ $# -gt 0 ]; do
301                                 m="$m\",\"$1"
302                                 shift
303                         done
304                 fi
305                 awk "BEGIN {printf \"$text\", \"$m\"; }"
306         }
307 fi
308
309 # National language support function
310 nls() {
311         local msg_echo nls_domain text message
312         msg_echo='\n'
313         nls_domain="$NLS_DOMAIN"
314         while [ "$1" != "${1##-}" ]; do
315                 case "$1" in
316                 --nls-domain)
317                         shift
318                         nls_domain="$1"
319                         shift
320                         ;;
321                 -n)
322                         msg_echo=''
323                         shift
324                         ;;
325                 esac
326         done
327         message="$1"
328         shift
329
330         # empty message, so we return --misiek
331         if [ -z "$message" ]; then
332                 echo -en "$msg_echo"
333                 return
334         fi
335
336         if is_yes "$GETTEXT"; then
337                 message=$(TEXTDOMAINDIR="/etc/sysconfig/locale" gettext -e --domain="${nls_domain:-rc-scripts}" "$message")
338         fi
339
340         printf "$message" "$@"
341         echo -en "$msg_echo"
342 }
343
344 rc_splash() {
345         local action="$1"
346
347         if ! is_no "$BOOT_SPLASH" && ! is_yes "$VSERVER"; then
348                 [ -x /bin/splash ] && /bin/splash "$action"
349         fi
350
351         : $((progress++))
352 }
353
354 msg_network_down() {
355         nls "ERROR: Networking is down. %s can't be run." "$1" >&2
356 }
357
358 msg_starting() {
359         show "Starting %s service" "$1"
360 }
361
362 msg_already_running() {
363         nls "%s service is already running." "$1"
364 }
365
366 msg_stopping() {
367         show "Stopping %s service" "$1"
368 }
369
370 msg_not_running() {
371         nls "%s service is not running." "$1"
372 }
373
374 msg_reloading() {
375         show "Reloading %s service" "$1"
376 }
377
378 msg_usage() {
379         nls "Usage: %s" "$*"
380 }
381
382 # Some functions to handle PLD Linux-style messages
383 show() {
384         local text len
385
386         if is_no "$FASTRC" && is_yes "$GETTEXT"; then
387                 text=$(nls -n "$@")
388         else
389                 text=$(printf "$@")
390         fi
391         len=${#text}
392         while [ $((len++)) -lt $INIT_COL ]; do
393                 text="$text."
394         done
395         if [ -n "$CHARS" ]; then
396                 termput setaf $CCHARS
397                 echo -n "$CHARS"
398                 termput op
399         fi
400         echo -n "$text"
401 }
402
403 deltext() {
404         termput hpa $INIT_COL
405 }
406
407 # Displays message in square brackests ("[ DONE ]"). Takes two arguments.
408 # First is the text to display, second is color number to use (argument to
409 # tput setaf). If second argument is not given, default (2, green) will be
410 # used).
411 progress() {
412         local COLOR
413         if [ -n "$2" ]; then
414                 COLOR="$2"
415         else
416                 COLOR="$CDONE"
417         fi
418         deltext
419         echo -n "$(termput setaf $CBRACKETS)[$(termput setaf $COLOR) $(nls --nls-domain rc-scripts "$1") $(termput setaf $CBRACKETS)]$(termput op)"
420 }
421
422 busy() {
423         echo -n "$_busy"
424 }
425
426 ok() {
427         echo "$_ok"
428 }
429
430 started() {
431         echo "$_started"
432 }
433
434 fail() {
435         echo "$_fail"
436         return 1
437 }
438
439 died() {
440         echo "$_died"
441         return 1
442 }
443
444 # Check if $pid (could be plural) are running
445 checkpid() {
446         while [ "$1" ]; do
447                 [ -d "/proc/$1" ] && return 0
448                 shift
449         done
450         return 1
451 }
452
453 # - outside chroot get only those processes, which are outside chroot.
454 # - inside chroot get only those processes, which are inside chroot.
455 # - don't filter out pids which do not have corresponding running processes (process died etc)
456 # (note: some processes like named are chrooted but run outside chroot)
457 # - do nothing inside vserver
458 filter_chroot() {
459         if is_yes "$VSERVER"; then
460                 echo $@
461                 return
462         fi
463         if [ $# -lt 1 -o ! -d /proc/1 ]; then
464                 echo $@
465                 return
466         fi
467         local root_dir good_pids="" good_add_pid
468         for root_pid in $@; do
469                 root_dir=$(resolvesymlink /proc/${root_pid}/root)
470                 if [ -n "$root_dir" ]; then
471                         good_add_pid=1
472                         if [ -n "${SYSTEM_CHROOTS}" ]; then
473                                 for r_dir in ${SYSTEM_CHROOTS}; do
474                                         echo "$root_dir" | grep -q "^${r_dir}" && good_add_pid=0
475                                 done
476                         fi
477                         [ "$good_add_pid" -eq 1 ] && good_pids="$good_pids $root_pid"
478                 elif [ ! -d "/proc/$root_pid" ]; then
479                         good_pids="$good_pids $root_pid"
480                 fi
481         done
482         echo $good_pids
483 }
484
485 # Usage:
486 # run_cmd Message command_to_run
487 # run_cmd -a Message command_to_run
488 # run_cmd --user "username" "Message" command_to_run
489 run_cmd() {
490         local force_err=0 exit_code=0 errors user
491         while [ $# -gt 0 ]; do
492                 case "$1" in
493                 -a)
494                         force_err=1
495                         ;;
496                 --user)
497                         shift
498                         user=$1
499                         ;;
500                 *)
501                         break
502                 esac
503                 shift
504         done
505
506         local message=$1; shift
507         show "$message"; busy
508
509         if errors=$(
510                 cd /
511                 export HOME=/tmp TMPDIR=/tmp
512                 if is_no "$RC_LOGGING"; then
513                         ${user:+setuidgid -s $user} "$@" 2>&1
514                 else
515                         ${user:+setuidgid -s $user} initlog -c "$*" 2>&1
516                 fi
517                 ); then
518                 ok
519                 log_success "$1 $message"
520         else
521                 fail
522                 log_failed "$1 $message"
523                 exit_code=1
524         fi
525         [ -n "$errors" ] && [ $exit_code -eq 1 -o $force_err -eq 1 ] && echo "$errors"
526         return $exit_code
527 }
528
529 _daemon_set_ulimits() {
530         local opt val ksh=${KSH_VERSION:+1}
531         set -- ${SERVICE_LIMITS:-$DEFAULT_SERVICE_LIMITS}
532         while [ $# -gt 0 ]; do
533                 opt=$1
534                 val=$2
535                 if [ "$ksh" ]; then
536                         case "$opt" in
537                         -Hu)
538                                 opt=-Hp
539                         ;;
540                         -Su)
541                                 opt=-Sp
542                         ;;
543                         -u)
544                                 opt=-p
545                         ;;
546                         esac
547                 fi
548                 ulimit $opt $val
549                 shift 2
550         done
551 }
552
553 # A function to start a program (now it's useful on read-only filesystem too)
554 daemon() {
555         local errors="" prog="" end="" waitname="" waittime=""
556         local exit_code=0
557         local nice=$SERVICE_RUN_NICE_LEVEL
558         local fork user closefds redirfds pidfile makepid chdir=/
559
560         # NOTE: if you wonder how the shellish (by syntax) $prog works in ssd mode,
561         # then the answer is: it totally ignores $prog and uses "$@" itself.
562
563         while [ $# -gt 0 ]; do
564                 case $1 in
565                 '')
566                 msg_usage " daemon [--check] [--user user] [--fork] [--chdir directory] [--closefds] [--redirfds] [--waitforname procname] [--waitfortime seconds] [--pidfile file] [--makepid] [+/-nicelevel] {program} <program args>"
567                         return 2
568                         ;;
569                 --check)
570                         # for compatibility with redhat/mandrake
571                         nls "warning: --check option is ignored!"
572                         shift
573                         ;;
574                 --user)
575                         shift
576                         [ "$1" != "root" ] && prog="/bin/su $1 -s /bin/sh -c \""
577                         user=$1
578                         ;;
579                 --fork)
580                         fork=1
581                         prog="/usr/bin/setsid sh -c \""
582                         end='&'
583                         ;;
584                 --chdir)
585                         shift
586                         chdir=$1
587                         ;;
588                 --closefds)
589                         closefds=1
590                         ;;
591                 --redirfds)
592                         redirfds=1
593                         ;;
594                 --waitforname)
595                         shift
596                         waitname="$1"
597                         ;;
598                 --waitfortime)
599                         shift
600                         waittime="$1"
601                         ;;
602                 --pidfile)
603                         shift
604                         pidfile="$1"
605                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
606                         ;;
607                 --makepid)
608                         makepid=1
609                         ;;
610                 -*|+*)
611                         nice=$1
612                         shift
613                         break
614                         ;;
615                 *)
616                         break
617                         ;;
618                 esac
619                 shift
620         done
621         # If command to execute ends with quotation mark, add remaining
622         # arguments and close quotation.
623         if [ "$prog" != "${prog%\"}" ]; then
624                 prog="$prog $*$end\""
625         else
626                 prog="$prog $*$end"
627         fi
628
629         _daemon_set_ulimits
630
631         [ -z "$DEFAULT_SERVICE_UMASK" ] && DEFAULT_SERVICE_UMASK=022
632         [ -z "$DEFAULT_SERVICE_RUN_NICE_LEVEL" ] && DEFAULT_SERVICE_RUN_NICE_LEVEL=0
633
634         # And start it up.
635         busy
636         cd $chdir
637         [ -n "$SERVICE_CPUSET" ] && is_yes "$CPUSETS" && echo $$ > "/dev/cpuset/${SERVICE_CPUSET}/tasks"
638         if errors=$(
639                 umask ${SERVICE_UMASK:-$DEFAULT_SERVICE_UMASK};
640                 export USER=root HOME=/tmp TMPDIR=/tmp
641                 nice=${nice:-$DEFAULT_SERVICE_RUN_NICE_LEVEL}
642                 nice=${nice:-0}
643
644                 if [ "$closefds" = 1 ]; then
645                         exec 1>&-
646                         exec 2>&-
647                         exec 0>&-
648                 elif [ "$redirfds" = 1 ]; then
649                         exec 1>/dev/null
650                         exec 2>/dev/null
651                         exec 0>/dev/null
652                 else
653                         exec 2>&1
654                 fi
655
656                 if is_no "$RC_LOGGING"; then
657                         prog=$1; shift
658                         if [ ! -x $prog ]; then
659                                 logger -t rc-scripts -p daemon.debug "daemon: Searching PATH for $prog, consider using full path in initscript"
660                                 local a o=$IFS
661                                 IFS=:
662                                 for a in $PATH; do
663                                         if [ -x $a/$prog ]; then
664                                                 prog=$a/$prog
665                                                 break
666                                         fi
667                                 done
668                                 IFS=$o
669                         fi
670                         /sbin/start-stop-daemon -q --start \
671                                 --nicelevel $nice \
672                                 ${pidfile:+--pidfile $pidfile} \
673                                 ${makepid:+--make-pidfile} \
674                                 ${user:+--chuid $user} \
675                                 ${chdir:+--chdir "$chdir"} \
676                                 ${fork:+--background} \
677                                 ${waitname:+--name $waitname} \
678                                 ${SERVICE_DROPCAPS:+--dropcap $SERVICE_DROPCAPS} \
679                                 --exec "$prog" \
680                                 -- ${1:+"$@"}
681                 else
682                         nice -n $nice initlog -c "$prog" 2>&1
683                 fi
684                 ); then
685
686                 if [ -n "$waitname" -a -n "$waittime" ]; then
687                         # Save basename.
688                         base=${waitname##*/}
689                         # Find pid.
690                         pid=$(pidofproc "$waitname" "$pidfile")
691                         [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
692                         i=0
693                         while [ "$i" -lt "$waittime" ]; do
694                                 i=$((i + 1))
695                                 checkpid $pid && sleep 1 || break
696                         done
697                 fi
698                 log_success "$1 startup"
699                 ok
700         else
701                 exit_code=1
702                 fail
703                 log_failed "$1 startup"
704                 [ -n "$errors" ] && echo >&2 "$errors"
705         fi
706         return $exit_code
707 }
708
709 # A function to stop a program.
710 killproc() {
711         local notset killlevel base pid pidfile result
712         # Test syntax.
713         if [ $# = 0 ]; then
714                 msg_usage " killproc [--pidfile PIDFILE] {program} [-SIGNAME]"
715                 return 2
716         fi
717
718         while [ "$1" != "${1##-}" ]; do
719                 case $1 in
720                 --pidfile|-p)
721                         pidfile="$2"
722                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
723                         shift 2
724                         ;;
725                 --waitforname)
726                         waitname="$2"
727                         shift 2
728                         ;;
729                 --waitfortime)
730                         waittime="$2"
731                         shift 2
732                         ;;
733                 esac
734         done
735
736         busy
737
738         local notset=0
739         # check for second arg to be kill level
740         if [ -n "$2" ]; then
741                 killlevel=$2
742         else
743                 notset=1
744         fi
745
746         # experimental start-stop-daemon based killing.
747         # works only with pidfile
748         if is_no "$RC_LOGGING" && [ "$pidfile" ]; then
749                 local sig=${killlevel:--TERM}
750                 /sbin/start-stop-daemon -q --stop \
751                         --retry ${sig#-}/10/${sig#-}/60/KILL/10 \
752                         -s ${sig#-} \
753                         ${pidfile:+--pidfile $pidfile}
754                 result=$?
755                 if [ "$result" -eq 0 ]; then
756                         ok
757                 else
758                         fail
759                 fi
760                 return $result
761         fi
762
763
764         # Save basename.
765         base=${1##*/}
766
767         # Find pid.
768         pid=$(pidofproc "$1" "$pidfile")
769         [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
770
771         # Kill it.
772         if [ -n "$pid" -a "$pid" != "$$" ] && checkpid $pid 2>&1; then
773                 if [ "$notset" = "1" ]; then
774                         if checkpid $pid 2>&1; then
775                                 # TERM first, then KILL if not dead
776                                 kill -TERM $pid
777                                 usleep 100000
778                                 if checkpid $pid && sleep 1 &&
779                                         checkpid $pid && sleep 3 &&
780                                         checkpid $pid; then
781                                         # XXX: SIGKILL is sent already on 4th second!
782                                         # HARMFUL for example to mysqld (which is already workarounded)
783                                         kill -KILL $pid
784                                         usleep 100000
785                                 fi
786                         fi
787                         checkpid $pid
788                         result=$?
789                         if [ "$result" -eq 0 ]; then
790                                 fail
791                                 log_failed "$1 shutdown"
792                         else
793                                 ok
794                                 log_success "$1 shutdown"
795                         fi
796                         result=$(( ! $result ))
797                 else
798                         # use specified level only
799                         if checkpid $pid > /dev/null 2>&1; then
800                                 kill $killlevel $pid
801                                 result=$?
802                                 if [ "$result" -eq 0 ]; then
803                                         ok
804                                         log_success "$1 got $killlevel"
805                                 else
806                                         result=7
807                                         fail
808                                         log_failed "$1 didn't get $killlevel"
809                                 fi
810                         else
811                                 result=7
812                                 died
813                                 log_failed "$1 shutdown"
814                         fi
815                 fi
816         else
817                 died
818                 log_failed "$1 shutdown"
819                 result=7
820         fi
821
822         if [ -n "$waitname" -a -n "$waittime" ]; then
823                 # Save basename.
824                 base=${waitname##*/}
825                 # Find pid.
826                 pid=$(pidofproc "$waitname" "$pidfile")
827                 [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
828                 i=0
829                 while [ "$i" -lt "$waittime" ]; do
830                         i=$(( i + 1 ))
831                         checkpid $pid && sleep 1 || break
832                 done
833         fi
834
835         # Remove pid file if any.
836         if [ "$notset" = "1" ]; then
837                 rm -f /var/run/${base}.pid
838         fi
839
840         return $result
841 }
842
843 # A function to find the pid of a program.
844 pidofproc() {
845         local pid pidfile base=${1##*/}
846         pidfile="$base.pid"
847         [ -n "$2" ] && pidfile="$2"
848
849         # Test syntax.
850         if [ $# = 0 ]; then
851                 msg_usage " pidofproc {program}"
852                 return 2
853         fi
854
855         # First try pidfile or "/var/run/*.pid"
856         case "$pidfile" in
857                 /*)pidfile="${pidfile}";;
858                 *) pidfile="/var/run/$pidfile";;
859         esac
860         if [ -f "${pidfile}" ]; then
861                 local p pid=""
862                 for p in $(< "${pidfile}"); do
863                         [ -z "$(echo "$p" | awk '{gsub(/[0-9]/,"");print;}')" ] && pid="$pid $p"
864                 done
865         fi
866
867         # Next try "pidof"
868         [ -z "$pid" ] && pidof -o $$ -o $PPID -o %PPID -x "$1"
869         pid=$(filter_chroot "$pid")
870         echo $pid
871 }
872
873 # status [--pidfile PIDFILE] {subsys} [{daemon}]"
874 status() {
875         local pid subsys daemon cpuset_msg pidfile
876         if [ "$1" = "--pidfile" -o "$1" = "-p" ]; then
877                 pidfile=$2
878                 case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
879                 shift 2
880         fi
881
882         subsys=$1
883         daemon=${2:-$subsys}
884
885         # Test syntax.
886         if [ $# = 0 ]; then
887                 msg_usage " status [--pidfile PIDFILE] {subsys} [{daemon}]"
888                 return 2
889         fi
890
891         # if pidfile specified, pid must be there
892         if [ "$pidfile" ]; then
893                 [ -f "$pidfile" ] && read pid < $pidfile
894                 # filter_chroot does not filter out dead pids, so this extra check, see t/status-pidfile.sh
895                 if [ ! -d "/proc/$pid" ]; then
896                         pid=
897                 fi
898         else
899                 pid=$(pidof -o $$ -o $PPID -o %PPID -x $daemon)
900         fi
901         pid=$(filter_chroot "$pid")
902
903         if [ "$pid" ]; then
904                 cpuset_msg="..."
905                 if [ -n "$SERVICE_CPUSET" ] && is_yes "$CPUSETS"; then
906                         if grep -q "$pid" "/dev/cpuset/${SERVICE_CPUSET}/tasks"; then
907                                 cpuset_msg=$(nls " in cpuset %s..." "$SERVICE_CPUSET")
908                         else
909                                 cpuset_msg=$(nls " outside of configured cpuset %s..." "$SERVICE_CPUSET")
910                         fi
911                 fi
912                 nls "%s (pid %s) is running%s" "$daemon" "$pid" "$cpuset_msg"
913                 return 0
914         fi
915
916         # Next try "/var/run/*.pid" files; if pidfile is not set
917         local base=${daemon##*/}
918         if [ -z "$pidfile" -a -f /var/run/${base}.pid ]; then
919                 read pid < /var/run/${base}.pid
920                 pid=$(filter_chroot "$pid")
921                 if [ "$pid" ]; then
922                         nls "%s dead but pid file (%s) exists" "$subsys" /var/run/${base}.pid
923                         return 1
924                 fi
925         fi
926
927         # See if /var/lock/subsys/$subsys exists
928         if [ -f /var/lock/subsys/$subsys ]; then
929                 nls "daemon %s dead but subsys (%s) locked" "$daemon" "$subsys"
930                 return 2
931         fi
932         nls "%s is stopped" "$subsys"
933         return 3
934 }
935
936 # Confirm whether we really want to run this service
937 confirm() {
938         local answer
939         nls -n "Start service %s (Y)es/(N)o/(C)ontinue? [Y] " "$1"
940         read answer
941         case $answer in
942         y|Y|t|T|j|J|"")
943                 return 0
944                 ;;
945         c|C|k|K|w|W)
946                 return 2
947                 ;;
948         n|N)
949                 return 1
950                 ;;
951         *)
952                 confirm $1
953                 return $?
954                 ;;
955         esac
956 }
957
958 # module is needed (ie. is requested, is available and isn't loaded already)
959 is_module() {
960         # module name without .o at end
961         if ! lsmod | grep -q "$1"; then
962                 if ls -1R /lib/modules/$(uname -r)/ 2> /dev/null | grep -q "^${1}.\(\|k\)o\(\|.gz\)"; then
963                         # true
964                         return 0
965                 fi
966         fi
967         # false
968         return 1
969 }
970
971 _modprobe() {
972         local parsed single die args foo result
973         parsed=no
974         while is_no "$parsed"; do
975                 case "$1" in
976                 "single")
977                         single=yes
978                         shift
979                         ;;
980                 "die")
981                         die=yes
982                         shift
983                         ;;
984                 -*)
985                         args="$args $1"
986                         shift
987                         ;;
988                 *)
989                         parsed=yes
990                         ;;
991                 esac
992         done
993         if is_yes "${single}"; then
994                 foo="$@"
995                 show "Loading %s kernel module(s)" "$foo"
996                 busy
997         fi
998         if [ -x /sbin/modprobe ]; then
999                 /sbin/modprobe -s $args "$@"
1000                 result=$?
1001         else
1002                 deltext; fail
1003                 result=1
1004         fi
1005         if is_yes "${single}"; then
1006                 deltext
1007                 if [ $result = "0" ]; then
1008                         is_yes "$single" && ok
1009                 else
1010                         fail
1011                         if is_yes "$die"; then
1012                                 nls "Could not load %s kernel module(s)" "$@"
1013                                 exit 1
1014                         fi
1015                 fi
1016         fi
1017 }
1018
1019 if is_no "$RC_LOGGING"; then
1020         log_success() {
1021                 :
1022         }
1023
1024         log_failed() {
1025                 :
1026         }
1027 else
1028         log_success() {
1029                 initlog -n $0 -s "$1 $2" -e 1
1030         }
1031
1032         log_failed() {
1033                 initlog -n $0 -s "$1 $2" -e 2
1034         }
1035 fi
1036
1037 # Check if any flavor of portmapper is running
1038 check_portmapper() {
1039         if [ -x /usr/sbin/rpcinfo ]; then
1040                 if /usr/sbin/rpcinfo -p localhost >/dev/null 2>/dev/null; then
1041                         return 0
1042                 else
1043                         return 1
1044                 fi
1045         elif [ -z "$(pidof portmap)" -a -z "$(pidof rpcbind)" ]; then
1046                 return 1
1047         fi
1048         return 0
1049 }
1050
1051 # is_fsmounted fstype mntpoint
1052 # Check if filesystem fstype is mounted on mntpoint
1053 is_fsmounted() {
1054         local fstype=$1
1055         local mntpoint=$2
1056
1057         [ -n "$fstype" -a -n "$mntpoint" ] || return 1
1058
1059         if [ -r /proc/mounts ]; then
1060                 grep -qE "[[:blank:]]$mntpoint[[:blank:]]+$fstype[[:blank:]]" /proc/mounts
1061                 return $?
1062         else
1063                 if [ "$(stat -L -f -c %T $mntpoint 2>/dev/null)" = "$fstype" ]; then
1064                         return 0
1065                 else
1066                         return 1
1067                 fi
1068         fi
1069 }
1070
1071 # __umount_loop awk_program fstab_file first_msg retry_msg umount_args
1072 # awk_program should process fstab_file and return a list of fstab-encoded
1073 # paths; it doesn't have to handle comments in fstab_file.
1074 __umount_loop() {
1075         local remaining sig=
1076         local retry=3 count
1077
1078         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1079         while [ -n "$remaining" -a "$retry" -gt 0 ]; do
1080                 if [ "$retry" -eq 3 ]; then
1081                         run_cmd "$3" fstab-decode umount $5 $remaining
1082                 else
1083                         run_cmd "$4" fstab-decode umount $5 $remaining
1084                 fi
1085                 count=4
1086                 remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1087                 while [ "$count" -gt 0 ]; do
1088                         [ -z "$remaining" ] && break
1089                         count=$(($count-1))
1090                         usleep 500000
1091                         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1092                 done
1093                 [ -z "$remaining" ] && break
1094                 fstab-decode /bin/fuser -k -m $sig $remaining >/dev/null
1095                 sleep 3
1096                 retry=$(($retry -1))
1097                 sig=-9
1098         done
1099 }
1100
1101 # Similar to __umount loop above, specialized for loopback devices
1102 __umount_loopback_loop() {
1103         local remaining devremaining sig=
1104         local retry=3
1105
1106         remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
1107         devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
1108         while [ -n "$remaining" -a "$retry" -gt 0 ]; do
1109                 if [ "$retry" -eq 3 ]; then
1110                         run_cmd "Unmounting loopback filesystems: " \
1111                                 fstab-decode umount $remaining
1112                 else
1113                         run_cmd "Unmounting loopback filesystems (retry):" \
1114                                 fstab-decode umount $remaining
1115                 fi
1116                 for dev in $devremaining ; do
1117                         losetup $dev > /dev/null 2>&1 && \
1118                                 run_cmd "Detaching loopback device $dev: " \
1119                                 losetup -d $dev
1120                 done
1121                 remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
1122                 devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
1123                 [ -z "$remaining" ] && break
1124                 fstab-decode /bin/fuser -k -m $sig $remaining >/dev/null
1125                 sleep 3
1126                 retry=$(($retry -1))
1127                 sig=-9
1128         done
1129 }
1130
1131 rc_cache_init() {
1132         # If we have cachefile, use it.
1133         # If we don't, create memory variables and try to save silently,
1134         local cachefile='/var/cache/rc-scripts/msg.cache'
1135
1136         local term
1137         if is_yes "$ISATTY"; then
1138                 term=$TERM
1139         else
1140                 term=dumb
1141         fi
1142
1143         # We create $check variable which is used to invalidate the cache.
1144         # The $check contains user locale and terminal.
1145         local check="$term.$LC_MESSAGES.$INIT_COL"
1146
1147         if [ -f "$cachefile" -a "$cachefile" -nt /etc/sysconfig/system -a "$cachefile" -nt /etc/sysconfig/init-colors ]; then
1148                 if . "$cachefile" 2>/dev/null; then
1149                         if [ "$check" = "$_check" ]; then
1150                                 return
1151                         fi
1152                 fi
1153         fi
1154
1155         # primitive caching
1156         _busy=$(progress "BUSY" "$CBUSY")
1157         _ok=$(progress "DONE")
1158         _started=$(progress "WORK")
1159         _fail=$(progress "FAIL" "$CFAIL")
1160         _died=$(progress "DIED" "$CFAIL")
1161
1162         # we don't use heredoc, as ksh attempts to create tempfile then
1163         (> "$cachefile" ) 2>/dev/null || return
1164         echo "_busy='$_busy';" >> "$cachefile"
1165         echo "_ok='$_ok';" >> "$cachefile"
1166         echo "_started='$_started';" >> "$cachefile"
1167         echo "_fail='$_fail';" >> "$cachefile"
1168         echo "_died='$_died';" >> "$cachefile"
1169         echo "_check='$check';" >> "$cachefile"
1170 }
1171
1172 rc_gettext_init() {
1173         if [ -z "$GETTEXT" ]; then
1174                 if [ -x /bin/gettext -o -x /usr/bin/gettext ]; then
1175                         GETTEXT=yes
1176                 else
1177                         GETTEXT=no
1178                 fi
1179         fi
1180
1181         if [ -z "$TPUT" ]; then
1182                 if [ -d /usr/share/terminfo ] && [ -x /usr/bin/tput -o -x /bin/tput ]; then
1183                         TPUT=yes
1184                         # check if we are on proper terminal
1185                         tput longname >/dev/null 2>&1 || TPUT=no
1186                 else
1187                         TPUT=no
1188                 fi
1189         fi
1190 }
1191
1192 use_upstart () {
1193         # True when upstart-event-based boot should be used
1194         is_yes "$USE_UPSTART" && return 0
1195         is_no "$USE_UPSTART" && return 1
1196         if [ ! -x /sbin/initctl ] ; then
1197                 USE_UPSTART="no"
1198                 return 1
1199         fi
1200         local cmdline=$(cat /proc/cmdline 2>/dev/null)
1201         if strstr "$cmdline" "pld.no-upstart" ; then
1202                 USE_UPSTART="no"
1203                 return 1
1204         else
1205                 USE_UPSTART="yes"
1206                 return 0
1207         fi
1208 }
1209
1210 emit () {
1211         # emit upstart signal
1212         # only when 'upstart' boot is enabled
1213         use_upstart || return 0
1214         /sbin/initctl emit "$@"
1215 }
1216
1217 is_upstart_task() {
1218         # Return 0 if the given service is an upstart task.
1219         grep -q '^task' "/etc/init/$1.conf"
1220 }
1221 is_upstart_running() {
1222         # Return 0 if the given service is running via upstart
1223         initctl status "$1" 2>/dev/null | grep -q running
1224 }
1225 upstart_start() {
1226         local service=$1
1227         is_upstart_running "${service}" && return 0
1228         msg_starting "${service}"
1229         if errors=$(/sbin/initctl start ${service} 2>&1) ; then
1230                 ok
1231                 return 0
1232         else
1233                 fail
1234                 echo "$errors" >&2
1235                 return 1
1236         fi
1237 }
1238 upstart_stop() {
1239         local service=$1
1240         if ! is_upstart_running "${service}" && ! is_upstart_task "${service}" ; then
1241                 return 0
1242         fi
1243         msg_stopping "${service}"
1244         if errors=$(/sbin/initctl stop ${service}) ; then
1245                 ok
1246                 return 0
1247         else
1248                 fail
1249                 echo "$errors" >&2
1250                 return 1
1251         fi
1252 }
1253 upstart_reload() {
1254         local service=$1
1255         if ! is_upstart_running "${service}" && ! is_upstart_task "${service}" ; then
1256                 return 0
1257         fi
1258         msg_reloading "${service}"
1259         if errors=$(/sbin/initctl reload ${service}) ; then
1260                 ok
1261                 return 0
1262         else
1263                 fail
1264                 echo "$errors" >&2
1265                 return 1
1266         fi
1267 }
1268 upstart_status() {
1269         # get service status
1270         # should be compliant with
1271         # http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1272         local service=$1
1273         local status
1274         if is_upstart_task "${service}" ; then
1275                 # we probably should have a way to handle task status
1276                 return 0
1277         fi
1278         if ! status=$(/sbin/initctl status "${service}") ; then
1279                 # program or service status is not known
1280                 return 4
1281         fi
1282         if strstr "$status" "running" ; then
1283                 # program is running or service is OK
1284                 echo "$status"
1285                 return 0
1286         else
1287                 # program is not running
1288                 echo "$status"
1289                 return 3
1290         fi
1291         # TODO: other statuses
1292 }
1293
1294 _upstart_controlled() {
1295         # If the service is to be handled by upstart
1296         # execute the start/stop/etc. commands the upstart way
1297         if ! use_upstart; then
1298                 return 0
1299         fi
1300         local script=$1
1301         shift
1302         local command=$1
1303         [ $# -gt 0 ] && shift
1304         local name=$(basename "$script")
1305         if [ ! -f /etc/init/${name}.conf ] ; then
1306                 return 0
1307         fi
1308         local commands
1309         local extra_commands
1310         local has_configtest
1311         if [ "$1" = "--except" ] ; then
1312                 shift
1313                 commands="$*"
1314                 for cmd in $commands ; do
1315                         if [ "$command" = "$cmd" ] ; then
1316                                 return 0
1317                         fi
1318                         case "$cmd" in
1319                                 start|stop|status|reload|restart|try-restart|force-reload)
1320                                         ;;
1321                                 configtest)
1322                                         has_configtest=yes
1323                                         extra_commands="|$cmd"
1324                                         ;;
1325                                 *)
1326                                         extra_commands="|$cmd"
1327                                         ;;
1328                         esac
1329                 done
1330         elif [ -n "$*" ] ; then
1331                 commands="$*"
1332                 local cmd
1333                 local found=0
1334                 # is there a better way
1335                 for cmd in $commands ; do
1336                         if [ "$command" = "$cmd" ] ; then
1337                                 found=1
1338                                 break;
1339                         fi
1340                 done
1341                 if [ $found = 0 ] ; then
1342                         # let the script handle it
1343                         return 0
1344                 fi
1345         fi
1346         case "$command" in
1347                 start)
1348                         upstart_start $name
1349                         exit $?
1350                         ;;
1351                 stop)
1352                         upstart_stop $name
1353                         exit $?
1354                         ;;
1355                 status)
1356                         upstart_status $name
1357                         exit $?
1358                         ;;
1359                 restart)
1360                         if is_yes "$has_configtest" ; then
1361                                 "$script" configtest || exit 1
1362                         fi
1363                         upstart_stop $name
1364                         upstart_start $name
1365                         exit $?
1366                         ;;
1367                 try-restart)
1368                         if ! is_upstart_running "$name" ; then
1369                                 exit 0
1370                         fi
1371                         if is_yes "$has_configtest" ; then
1372                                 "$script" configtest || exit 1
1373                         fi
1374                         upstart_stop $name
1375                         upstart_start $name
1376                         exit $?
1377                         ;;
1378                 reload)
1379                         if is_yes "$has_configtest" ; then
1380                                 "$script" configtest || exit 1
1381                         fi
1382                         if is_upstart_task "$name" ; then
1383                                 nls "$command not implemented for $name"
1384                                 exit 3
1385                         else
1386                                 upstart_reload "$name"
1387                                 exit $?
1388                         fi
1389                         ;;
1390                 force-reload)
1391                         if is_yes "$has_configtest" ; then
1392                                 "$script" configtest || exit 1
1393                         fi
1394                         if is_upstart_task "$name" ; then
1395                                 upstart_stop "$name"
1396                                 upstart_start "$name"
1397                                 exit $?
1398                         else
1399                                 upstart_reload "$name"
1400                                 exit $?
1401                         fi
1402                         ;;
1403                 *)
1404                         msg_usage "$0 {start|stop|restart|reload|force-reload|status$extra_commands}"
1405                         exit 3
1406                         ;;
1407         esac
1408         return 1 # should not happen
1409 }
1410
1411 # Usage:
1412 #       somewhere at the begining of init script:
1413 #     upstart_controlled
1414 #               - to pass implement all upstart commands via initctl
1415 #                 start, stop, status, restart, reload and force_reload
1416 #                 are implemented
1417 #     upstart_controlled command...
1418 #               - to pass handle only specific commands the upstart way
1419 #                 and leave the rest to the script
1420 #
1421 alias upstart_controlled='_upstart_controlled $0 "$@"'
1422
1423 rc_gettext_init
1424 rc_cache_init
1425
1426 #/*
1427 # * Local variables:
1428 # * mode: sh
1429 # * indent-tabs-mode: notnil
1430 # * End:
1431 # *
1432 # */
This page took 0.132884 seconds and 4 git commands to generate.