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