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