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