]> git.pld-linux.org Git - projects/rc-scripts.git/blob - lib/functions
improve fedora compatibility:
[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                         user=$1
577                         ;;
578                 --fork)
579                         fork=1
580                         end='&'
581                         ;;
582                 --chdir)
583                         shift
584                         chdir=$1
585                         ;;
586                 --closefds)
587                         closefds=1
588                         ;;
589                 --redirfds)
590                         redirfds=1
591                         ;;
592                 --waitforname)
593                         shift
594                         waitname="$1"
595                         ;;
596                 --waitfortime)
597                         shift
598                         waittime="$1"
599                         ;;
600                 --pidfile=?*)
601                         pidfile="${1#--pidfile=}"
602                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
603                         ;;
604                 --pidfile)
605                         shift
606                         pidfile="$1"
607                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
608                         ;;
609                 --makepid)
610                         makepid=1
611                         ;;
612                 -*|+*)
613                         nice=$1
614                         shift
615                         break
616                         ;;
617                 *)
618                         break
619                         ;;
620                 esac
621                 shift
622         done
623         if [ -n "$user" -a "$user" != "root" ]; then
624                 prog="/bin/su $user -s /bin/sh -c \""
625         fi
626         if [ "$fork" = "1" ]; then
627                 prog="/usr/bin/setsid ${prog:-sh -c \"}"
628         fi
629         # If command to execute ends with quotation mark, add remaining
630         # arguments and close quotation.
631         if [ "$prog" != "${prog%\"}" ]; then
632                 prog="$prog $*$end\""
633         else
634                 prog="$prog $*$end"
635         fi
636
637         _daemon_set_ulimits
638
639         [ -z "$DEFAULT_SERVICE_UMASK" ] && DEFAULT_SERVICE_UMASK=022
640         [ -z "$DEFAULT_SERVICE_RUN_NICE_LEVEL" ] && DEFAULT_SERVICE_RUN_NICE_LEVEL=0
641
642         # And start it up.
643         busy
644         cd $chdir
645         [ -n "$SERVICE_CPUSET" ] && is_yes "$CPUSETS" && echo $$ > "/dev/cpuset/${SERVICE_CPUSET}/tasks"
646         if errors=$(
647                 umask ${SERVICE_UMASK:-$DEFAULT_SERVICE_UMASK};
648                 export USER=root HOME=/tmp TMPDIR=/tmp
649
650                 nice=${nice:-$DEFAULT_SERVICE_RUN_NICE_LEVEL}
651                 nice=${nice:-0}
652
653                 # make nice level absolute, not to be dependant of nice level of shell where service started
654                 nice=$(($nice - $(nice)))
655
656                 if [ "$closefds" = 1 ]; then
657                         exec 1>&-
658                         exec 2>&-
659                         exec 0>&-
660                 elif [ "$redirfds" = 1 ]; then
661                         exec 1>/dev/null
662                         exec 2>/dev/null
663                         exec 0>/dev/null
664                 else
665                         exec 2>&1
666                 fi
667
668                 if is_no "$RC_LOGGING"; then
669                         prog=$1; shift
670                         if [ ! -x $prog ]; then
671                                 logger -t rc-scripts -p daemon.debug "daemon: Searching PATH for $prog, consider using full path in initscript"
672                                 local a o=$IFS
673                                 IFS=:
674                                 for a in $PATH; do
675                                         if [ -x $a/$prog ]; then
676                                                 prog=$a/$prog
677                                                 break
678                                         fi
679                                 done
680                                 IFS=$o
681                         fi
682                         /sbin/start-stop-daemon -q --start \
683                                 --nicelevel $nice \
684                                 ${pidfile:+--pidfile $pidfile} \
685                                 ${makepid:+--make-pidfile} \
686                                 ${user:+--chuid $user} \
687                                 ${chdir:+--chdir "$chdir"} \
688                                 ${fork:+--background} \
689                                 ${waitname:+--name $waitname} \
690                                 ${SERVICE_DROPCAPS:+--dropcap $SERVICE_DROPCAPS} \
691                                 --exec "$prog" \
692                                 -- ${1:+"$@"}
693                 else
694                         nice -n $nice initlog -c "$prog" 2>&1 </dev/null
695                 fi
696                 ); then
697
698                 if [ -n "$waitname" -a -n "$waittime" ]; then
699                         # Save basename.
700                         base=${waitname##*/}
701                         # Find pid.
702                         pid=$(pidofproc "$waitname" "$pidfile")
703                         [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
704                         i=0
705                         while [ "$i" -lt "$waittime" ]; do
706                                 i=$((i + 1))
707                                 checkpid $pid && sleep 1 || break
708                         done
709                 fi
710                 log_success "$1 startup"
711                 ok
712         else
713                 exit_code=1
714                 fail
715                 log_failed "$1 startup"
716                 [ -n "$errors" ] && echo >&2 "$errors"
717         fi
718         return $exit_code
719 }
720
721 # A function to stop a program.
722 killproc() {
723         local notset killlevel base pid pidfile result delay=3 try
724         # Test syntax.
725         if [ $# = 0 ]; then
726                 msg_usage " killproc [--pidfile|-p PIDFILE] [-d DELAY] {program} [-SIGNAME]"
727                 return 2
728         fi
729
730         while [ "$1" != "${1##-}" ]; do
731                 case $1 in
732                 -d)
733                         delay="$2"
734                         shift 2
735                         ;;
736                 --pidfile|-p)
737                         pidfile="$2"
738                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
739                         shift 2
740                         ;;
741                 --waitforname)
742                         waitname="$2"
743                         shift 2
744                         ;;
745                 --waitfortime)
746                         waittime="$2"
747                         shift 2
748                         ;;
749                 esac
750         done
751
752         busy
753
754         local notset=0
755         # check for second arg to be kill level
756         if [ -n "$2" ]; then
757                 killlevel=$2
758         else
759                 notset=1
760         fi
761
762         # experimental start-stop-daemon based killing.
763         # works only with pidfile
764         if is_no "$RC_LOGGING" && [ "$pidfile" ]; then
765                 local sig=${killlevel:--TERM} retry
766                 # retry only if signal is not specified,
767                 # as otherwise impossible to send HUP if process pid stays in pidfile.
768                 if [ "${killlevel+set}" = "set" ]; then
769                         # if we send HUP it's ok if process does not die
770                         retry="--oknodo"
771                 else
772                         retry="--retry ${sig#-}/10/${sig#-}/60/KILL/10"
773                 fi
774                 /sbin/start-stop-daemon -q --stop \
775                         $retry \
776                         -s ${sig#-} \
777                         ${pidfile:+--pidfile $pidfile}
778                 result=$?
779                 if [ "$result" -eq 0 ]; then
780                         ok
781                 else
782                         fail
783                 fi
784                 return $result
785         fi
786
787
788         # Save basename.
789         base=${1##*/}
790
791         # Find pid.
792         pid=$(pidofproc "$1" "$pidfile")
793         [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
794
795         # Kill it.
796         if [ -n "$pid" -a "$pid" != "$$" ] && checkpid $pid 2>&1; then
797                 if [ "$notset" = "1" ]; then
798                         if checkpid $pid 2>&1; then
799                                 # TERM first, then KILL if not dead
800                                 kill -TERM $pid
801                                 usleep 50000
802
803                                 try=0
804                                 while [ $try -lt $delay ]; do
805                                         checkpid $pid || break
806                                         sleep 1
807                                         try=$((try+1))
808                                 done
809                                 if checkpid $pid; then
810                                         # XXX: SIGKILL is sent already on 4th second!
811                                         # HARMFUL for example to mysqld (which is already workarounded)
812                                         kill -KILL $pid
813                                         usleep 50000
814                                 fi
815                         fi
816                         checkpid $pid
817                         result=$?
818                         if [ "$result" -eq 0 ]; then
819                                 fail
820                                 log_failed "$1 shutdown"
821                         else
822                                 ok
823                                 log_success "$1 shutdown"
824                         fi
825                         result=$(( ! $result ))
826                 else
827                         # use specified level only
828                         if checkpid $pid > /dev/null 2>&1; then
829                                 kill $killlevel $pid
830                                 result=$?
831                                 if [ "$result" -eq 0 ]; then
832                                         ok
833                                         log_success "$1 got $killlevel"
834                                 else
835                                         result=7
836                                         fail
837                                         log_failed "$1 didn't get $killlevel"
838                                 fi
839                         else
840                                 result=7
841                                 died
842                                 log_failed "$1 shutdown"
843                         fi
844                 fi
845         else
846                 died
847                 log_failed "$1 shutdown"
848                 result=7
849         fi
850
851         if [ -n "$waitname" -a -n "$waittime" ]; then
852                 # Save basename.
853                 base=${waitname##*/}
854                 # Find pid.
855                 pid=$(pidofproc "$waitname" "$pidfile")
856                 [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
857                 i=0
858                 while [ "$i" -lt "$waittime" ]; do
859                         i=$(( i + 1 ))
860                         checkpid $pid && sleep 1 || break
861                 done
862         fi
863
864         # Remove pid file if any.
865         if [ "$notset" = "1" ]; then
866                 rm -f /var/run/${base}.pid
867         fi
868
869         return $result
870 }
871
872 # A function to find the pid of a program.
873 pidofproc() {
874         local pid pidfile base=${1##*/}
875         pidfile="$base.pid"
876         [ -n "$2" ] && pidfile="$2"
877
878         # Test syntax.
879         if [ $# = 0 ]; then
880                 msg_usage " pidofproc {program}"
881                 return 2
882         fi
883
884         # First try pidfile or "/var/run/*.pid"
885         case "$pidfile" in
886                 /*)pidfile="${pidfile}";;
887                 *) pidfile="/var/run/$pidfile";;
888         esac
889         if [ -f "${pidfile}" ]; then
890                 local p pid=""
891                 for p in $(< "${pidfile}"); do
892                         [ -z "$(echo "$p" | awk '{gsub(/[0-9]/,"");print;}')" ] && pid="$pid $p"
893                 done
894         fi
895
896         # Next try "pidof"
897         [ -z "$pid" ] && pidof -o $$ -o $PPID -o %PPID -x "$1"
898         pid=$(filter_chroot "$pid")
899         echo $pid
900 }
901
902 # status [--pidfile PIDFILE] {subsys} [{daemon}]"
903 status() {
904         local pid subsys daemon cpuset_msg pidfile
905         if [ "$1" = "--pidfile" -o "$1" = "-p" ]; then
906                 pidfile=$2
907                 case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
908                 shift 2
909         fi
910
911         subsys=$1
912         daemon=${2:-$subsys}
913
914         # Test syntax.
915         if [ $# = 0 ]; then
916                 msg_usage " status [--pidfile PIDFILE] {subsys} [{daemon}]"
917                 return 2
918         fi
919
920         # if pidfile specified, pid must be there
921         if [ "$pidfile" ]; then
922                 [ -f "$pidfile" ] && read pid < $pidfile
923                 # filter_chroot does not filter out dead pids, so this extra check, see t/status-pidfile.sh
924                 if [ ! -d "/proc/$pid" ]; then
925                         pid=
926                 fi
927         else
928                 pid=$(pidof -o $$ -o $PPID -o %PPID -x $daemon)
929         fi
930         pid=$(filter_chroot "$pid")
931
932         if [ "$pid" ]; then
933                 cpuset_msg="..."
934                 if [ -n "$SERVICE_CPUSET" ] && is_yes "$CPUSETS"; then
935                         if grep -q "$pid" "/dev/cpuset/${SERVICE_CPUSET}/tasks"; then
936                                 cpuset_msg=$(nls " in cpuset %s..." "$SERVICE_CPUSET")
937                         else
938                                 cpuset_msg=$(nls " outside of configured cpuset %s..." "$SERVICE_CPUSET")
939                         fi
940                 fi
941                 nls "%s (pid %s) is running%s" "$daemon" "$pid" "$cpuset_msg"
942                 return 0
943         fi
944
945         # Next try "/var/run/*.pid" files; if pidfile is not set
946         local base=${daemon##*/}
947         if [ -z "$pidfile" -a -f /var/run/${base}.pid ]; then
948                 read pid < /var/run/${base}.pid
949                 pid=$(filter_chroot "$pid")
950                 if [ "$pid" ]; then
951                         nls "%s dead but pid file (%s) exists" "$subsys" /var/run/${base}.pid
952                         return 1
953                 fi
954         fi
955
956         # See if /var/lock/subsys/$subsys exists
957         if [ -f /var/lock/subsys/$subsys ]; then
958                 nls "daemon %s dead but subsys (%s) locked" "$daemon" "$subsys"
959                 return 2
960         fi
961         nls "%s is stopped" "$subsys"
962         return 3
963 }
964
965 # Confirm whether we really want to run this service
966 confirm() {
967         local answer
968         nls -n "Start service %s (Y)es/(N)o/(C)ontinue? [Y] " "$1"
969         read answer
970         case $answer in
971         y|Y|t|T|j|J|"")
972                 return 0
973                 ;;
974         c|C|k|K|w|W)
975                 return 2
976                 ;;
977         n|N)
978                 return 1
979                 ;;
980         *)
981                 confirm $1
982                 return $?
983                 ;;
984         esac
985 }
986
987 # module is needed (ie. is requested, is available and isn't loaded already)
988 is_module() {
989         # module name without .o at end
990         if ! lsmod | grep -q "$1"; then
991                 if ls -1R /lib/modules/$(uname -r)/ 2> /dev/null | grep -q "^${1}.\(\|k\)o\(\|.gz\)"; then
992                         # true
993                         return 0
994                 fi
995         fi
996         # false
997         return 1
998 }
999
1000 _modprobe() {
1001         local parsed single die args foo result
1002         parsed=no
1003         while is_no "$parsed"; do
1004                 case "$1" in
1005                 "single")
1006                         single=yes
1007                         shift
1008                         ;;
1009                 "die")
1010                         die=yes
1011                         shift
1012                         ;;
1013                 -*)
1014                         args="$args $1"
1015                         shift
1016                         ;;
1017                 *)
1018                         parsed=yes
1019                         ;;
1020                 esac
1021         done
1022         if is_yes "${single}"; then
1023                 foo="$@"
1024                 show "Loading %s kernel module(s)" "$foo"
1025                 busy
1026         fi
1027         if [ -x /sbin/modprobe ]; then
1028                 /sbin/modprobe -s $args "$@"
1029                 result=$?
1030         else
1031                 deltext; fail
1032                 result=1
1033         fi
1034         if is_yes "${single}"; then
1035                 deltext
1036                 if [ $result = "0" ]; then
1037                         is_yes "$single" && ok
1038                 else
1039                         fail
1040                         if is_yes "$die"; then
1041                                 nls "Could not load %s kernel module(s)" "$@"
1042                                 exit 1
1043                         fi
1044                 fi
1045         fi
1046 }
1047
1048 if is_no "$RC_LOGGING"; then
1049         log_success() {
1050                 :
1051         }
1052
1053         log_failed() {
1054                 :
1055         }
1056 else
1057         log_success() {
1058                 initlog -n $0 -s "$1 $2" -e 1
1059         }
1060
1061         log_failed() {
1062                 initlog -n $0 -s "$1 $2" -e 2
1063         }
1064 fi
1065
1066 # Check if any flavor of portmapper is running
1067 check_portmapper() {
1068         if [ -x /usr/sbin/rpcinfo ]; then
1069                 if /usr/sbin/rpcinfo -p localhost >/dev/null 2>/dev/null; then
1070                         return 0
1071                 else
1072                         return 1
1073                 fi
1074         elif [ -z "$(pidof portmap)" -a -z "$(pidof rpcbind)" ]; then
1075                 return 1
1076         fi
1077         return 0
1078 }
1079
1080 # is_fsmounted fstype mntpoint
1081 # Check if filesystem fstype is mounted on mntpoint
1082 is_fsmounted() {
1083         local fstype=$1
1084         local mntpoint=$2
1085
1086         [ -n "$fstype" -a -n "$mntpoint" ] || return 1
1087
1088         if [ -r /proc/mounts ]; then
1089                 grep -qE "[[:blank:]]$mntpoint[[:blank:]]+$fstype[[:blank:]]" /proc/mounts
1090                 return $?
1091         else
1092                 if [ "$(stat -L -f -c %T $mntpoint 2>/dev/null)" = "$fstype" ]; then
1093                         return 0
1094                 else
1095                         return 1
1096                 fi
1097         fi
1098 }
1099
1100 # __umount_loop awk_program fstab_file first_msg retry_msg umount_args
1101 # awk_program should process fstab_file and return a list of fstab-encoded
1102 # paths; it doesn't have to handle comments in fstab_file.
1103 __umount_loop() {
1104         local remaining sig=
1105         local retry=3 count
1106
1107         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1108         while [ -n "$remaining" -a "$retry" -gt 0 ]; do
1109                 if [ "$retry" -eq 3 ]; then
1110                         run_cmd "$3" fstab-decode umount $5 $remaining
1111                 else
1112                         run_cmd "$4" fstab-decode umount $5 $remaining
1113                 fi
1114                 count=4
1115                 remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1116                 while [ "$count" -gt 0 ]; do
1117                         [ -z "$remaining" ] && break
1118                         count=$(($count-1))
1119                         usleep 500000
1120                         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1121                 done
1122                 [ -z "$remaining" ] && break
1123                 fstab-decode /bin/fuser -k -m $sig $remaining >/dev/null
1124                 sleep 3
1125                 retry=$(($retry -1))
1126                 sig=-9
1127         done
1128 }
1129
1130 # Similar to __umount loop above, specialized for loopback devices
1131 __umount_loopback_loop() {
1132         local remaining devremaining sig=
1133         local retry=3
1134
1135         remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
1136         devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
1137         while [ -n "$remaining" -a "$retry" -gt 0 ]; do
1138                 if [ "$retry" -eq 3 ]; then
1139                         run_cmd "Unmounting loopback filesystems: " \
1140                                 fstab-decode umount $remaining
1141                 else
1142                         run_cmd "Unmounting loopback filesystems (retry):" \
1143                                 fstab-decode umount $remaining
1144                 fi
1145                 for dev in $devremaining ; do
1146                         losetup $dev > /dev/null 2>&1 && \
1147                                 run_cmd "Detaching loopback device $dev: " \
1148                                 losetup -d $dev
1149                 done
1150                 remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
1151                 devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
1152                 [ -z "$remaining" ] && break
1153                 fstab-decode /bin/fuser -k -m $sig $remaining >/dev/null
1154                 sleep 3
1155                 retry=$(($retry -1))
1156                 sig=-9
1157         done
1158 }
1159
1160 rc_cache_init() {
1161         # If we have cachefile, use it.
1162         # If we don't, create memory variables and try to save silently,
1163         local cachefile='/var/cache/rc-scripts/msg.cache'
1164
1165         local term
1166         if is_yes "$ISATTY"; then
1167                 term=$TERM
1168         else
1169                 term=dumb
1170         fi
1171
1172         # We create $check variable which is used to invalidate the cache.
1173         # The $check contains user locale and terminal.
1174         local check="$term.$LC_MESSAGES.$INIT_COL"
1175
1176         if [ -f "$cachefile" -a "$cachefile" -nt /etc/sysconfig/system -a "$cachefile" -nt /etc/sysconfig/init-colors ]; then
1177                 if . "$cachefile" 2>/dev/null; then
1178                         if [ "$check" = "$_check" ]; then
1179                                 return
1180                         fi
1181                 fi
1182         fi
1183
1184         # primitive caching
1185         _busy=$(progress "BUSY" "$CBUSY")
1186         _ok=$(progress "DONE")
1187         _started=$(progress "WORK")
1188         _fail=$(progress "FAIL" "$CFAIL")
1189         _died=$(progress "DIED" "$CFAIL")
1190
1191         # we don't use heredoc, as ksh attempts to create tempfile then
1192         (> "$cachefile" ) 2>/dev/null || return
1193         echo "_busy='$_busy';" >> "$cachefile"
1194         echo "_ok='$_ok';" >> "$cachefile"
1195         echo "_started='$_started';" >> "$cachefile"
1196         echo "_fail='$_fail';" >> "$cachefile"
1197         echo "_died='$_died';" >> "$cachefile"
1198         echo "_check='$check';" >> "$cachefile"
1199 }
1200
1201 rc_gettext_init() {
1202         if [ -z "$GETTEXT" ]; then
1203                 if [ -x /bin/gettext -o -x /usr/bin/gettext ]; then
1204                         GETTEXT=yes
1205                 else
1206                         GETTEXT=no
1207                 fi
1208         fi
1209
1210         if [ -z "$TPUT" ]; then
1211                 if [ -d /usr/share/terminfo ] && [ -x /usr/bin/tput -o -x /bin/tput ]; then
1212                         TPUT=yes
1213                         # check if we are on proper terminal
1214                         tput longname >/dev/null 2>&1 || TPUT=no
1215                 else
1216                         TPUT=no
1217                 fi
1218         fi
1219 }
1220
1221 use_upstart () {
1222         # True when upstart-event-based boot should be used
1223         is_yes "$USE_UPSTART" && return 0
1224         is_no "$USE_UPSTART" && return 1
1225         if [ ! -x /sbin/initctl ] ; then
1226                 USE_UPSTART="no"
1227                 return 1
1228         fi
1229         local cmdline=$(cat /proc/cmdline 2>/dev/null)
1230         if strstr "$cmdline" "pld.no-upstart" ; then
1231                 USE_UPSTART="no"
1232                 return 1
1233         else
1234                 USE_UPSTART="yes"
1235                 return 0
1236         fi
1237 }
1238
1239 emit () {
1240         # emit upstart signal
1241         # only when 'upstart' boot is enabled
1242         use_upstart || return 0
1243         /sbin/initctl emit "$@"
1244 }
1245
1246 is_upstart_task() {
1247         # Return 0 if the given service is an upstart task.
1248         grep -q '^task' "/etc/init/$1.conf"
1249 }
1250 is_upstart_running() {
1251         # Return 0 if the given service is running via upstart
1252         initctl status "$1" 2>/dev/null | grep -q running
1253 }
1254 upstart_start() {
1255         local service=$1
1256         if is_upstart_running "${service}"; then
1257                 msg_already_running "$service"
1258                 return 0
1259         fi
1260
1261         msg_starting "${service}"
1262         if errors=$(/sbin/initctl start ${service} 2>&1) ; then
1263                 ok
1264                 return 0
1265         else
1266                 fail
1267                 echo "$errors" >&2
1268                 return 1
1269         fi
1270 }
1271 upstart_stop() {
1272         local service=$1
1273         if ! is_upstart_running "${service}"; then
1274                 msg_not_running "$name"
1275                 return 0
1276         fi
1277         msg_stopping "${service}"
1278         if errors=$(/sbin/initctl stop ${service}) ; then
1279                 ok
1280                 return 0
1281         else
1282                 fail
1283                 echo "$errors" >&2
1284                 return 1
1285         fi
1286 }
1287 upstart_reload() {
1288         local service=$1
1289         if ! is_upstart_running "${service}" && ! is_upstart_task "${service}" ; then
1290                 return 0
1291         fi
1292         msg_reloading "${service}"
1293         if errors=$(/sbin/initctl reload ${service}) ; then
1294                 ok
1295                 return 0
1296         else
1297                 fail
1298                 echo "$errors" >&2
1299                 return 1
1300         fi
1301 }
1302 upstart_status() {
1303         # get service status
1304         # should be compliant with
1305         # http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1306         local service=$1
1307         local status
1308         if is_upstart_task "${service}" ; then
1309                 # we probably should have a way to handle task status
1310                 return 0
1311         fi
1312         if ! status=$(/sbin/initctl status "${service}") ; then
1313                 # program or service status is not known
1314                 return 4
1315         fi
1316         if strstr "$status" "running" ; then
1317                 # program is running or service is OK
1318                 echo "$status"
1319                 return 0
1320         else
1321                 # program is not running
1322                 echo "$status"
1323                 return 3
1324         fi
1325         # TODO: other statuses
1326 }
1327
1328 _upstart_controlled() {
1329         # If the service is to be handled by upstart
1330         # execute the start/stop/etc. commands the upstart way
1331         if ! use_upstart; then
1332                 return 0
1333         fi
1334         local script=$1
1335         shift
1336         local command=$1
1337         [ $# -gt 0 ] && shift
1338         local name=$(basename "$script")
1339         if [ ! -f /etc/init/${name}.conf ] ; then
1340                 return 0
1341         fi
1342         local commands
1343         local extra_commands
1344         local has_configtest
1345         if [ "$1" = "--except" ] ; then
1346                 shift
1347                 commands="$*"
1348                 for cmd in $commands ; do
1349                         if [ "$command" = "$cmd" ] ; then
1350                                 return 0
1351                         fi
1352                         case "$cmd" in
1353                                 start|stop|status|reload|restart|try-restart|force-reload)
1354                                         ;;
1355                                 configtest)
1356                                         has_configtest=yes
1357                                         extra_commands="|$cmd"
1358                                         ;;
1359                                 *)
1360                                         extra_commands="|$cmd"
1361                                         ;;
1362                         esac
1363                 done
1364         elif [ -n "$*" ] ; then
1365                 commands="$*"
1366                 local cmd
1367                 local found=0
1368                 # is there a better way
1369                 for cmd in $commands ; do
1370                         if [ "$command" = "$cmd" ] ; then
1371                                 found=1
1372                                 break;
1373                         fi
1374                 done
1375                 if [ $found = 0 ] ; then
1376                         # let the script handle it
1377                         return 0
1378                 fi
1379         fi
1380         case "$command" in
1381                 start)
1382                         upstart_start $name
1383                         exit $?
1384                         ;;
1385                 stop)
1386                         upstart_stop $name
1387                         exit $?
1388                         ;;
1389                 status)
1390                         upstart_status $name
1391                         exit $?
1392                         ;;
1393                 restart)
1394                         if is_yes "$has_configtest" ; then
1395                                 "$script" configtest || exit 1
1396                         fi
1397                         upstart_stop $name
1398                         upstart_start $name
1399                         exit $?
1400                         ;;
1401                 try-restart)
1402                         if ! is_upstart_running "$name" ; then
1403                                 exit 0
1404                         fi
1405                         if is_yes "$has_configtest" ; then
1406                                 "$script" configtest || exit 1
1407                         fi
1408                         upstart_stop $name
1409                         upstart_start $name
1410                         exit $?
1411                         ;;
1412                 reload)
1413                         if is_yes "$has_configtest" ; then
1414                                 "$script" configtest || exit 1
1415                         fi
1416                         if is_upstart_task "$name" ; then
1417                                 nls "$command not implemented for $name"
1418                                 exit 3
1419                         else
1420                                 upstart_reload "$name"
1421                                 exit $?
1422                         fi
1423                         ;;
1424                 force-reload)
1425                         if is_yes "$has_configtest" ; then
1426                                 "$script" configtest || exit 1
1427                         fi
1428                         if is_upstart_task "$name" ; then
1429                                 upstart_stop "$name"
1430                                 upstart_start "$name"
1431                                 exit $?
1432                         else
1433                                 upstart_reload "$name"
1434                                 exit $?
1435                         fi
1436                         ;;
1437                 *)
1438                         msg_usage "$0 {start|stop|restart|reload|force-reload|status$extra_commands}"
1439                         exit 3
1440                         ;;
1441         esac
1442         return 1 # should not happen
1443 }
1444
1445 # Usage:
1446 #       somewhere at the begining of init script:
1447 #     upstart_controlled
1448 #               - to pass implement all upstart commands via initctl
1449 #                 start, stop, status, restart, reload and force_reload
1450 #                 are implemented
1451 #     upstart_controlled command...
1452 #               - to pass handle only specific commands the upstart way
1453 #                 and leave the rest to the script
1454 #
1455 alias upstart_controlled='_upstart_controlled $0 "$@"'
1456
1457 rc_gettext_init
1458 rc_cache_init
1459
1460 #/*
1461 # * Local variables:
1462 # * mode: sh
1463 # * indent-tabs-mode: notnil
1464 # * End:
1465 # *
1466 # */
This page took 0.130325 seconds and 4 git commands to generate.