]> git.pld-linux.org Git - projects/rc-scripts.git/blob - rc.d/init.d/functions
Support for handling processes inside and outside of chrooted systems based on rc...
[projects/rc-scripts.git] / rc.d / init.d / functions
1 # functions     This file contains functions to be used by most or all
2 #               shell scripts in the /etc/init.d directory.
3 #
4 # $Id$
5 #
6 # Author:       Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
7 # Hacked by:    Greg Galloway and Marc Ewing
8 # Modified for PLD by:
9 #               Marek Obuchowicz <elephant@pld-linux.org>
10 #               Arkadiusz Mi¶kiewicz <misiek@pld-linux.org>
11 #               Micha³ Kochanowicz <mkochano@pld-linux.org>
12
13 # First set up a default search path.
14 export PATH="/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin"
15
16 # Set defaults
17 INIT_COL=67
18
19 # Source configuration if available - may override default values
20 [ -r /etc/sysconfig/system ] && . /etc/sysconfig/system
21 [ -r /etc/sysconfig/bootsplash ] && . /etc/sysconfig/bootsplash
22
23 [ -z "$COLUMNS" ] && COLUMNS=80
24
25 is_yes()
26 {
27         # Test syntax
28         if [ $# = 0 ] ; then
29                 msg_usage " is_yes {value}"
30                 return 2
31         fi
32
33         # Check value
34         case "$1" in
35           yes|Yes|YES|true|True|TRUE|on|On|ON|Y|y|1)
36                 # true returns zero
37                 return 0
38                 ;;
39           *)
40                 # false returns one
41                 return 1
42                 ;;
43         esac
44 }
45
46 is_no()
47 {
48         # Test syntax
49         if [ $# = 0 ] ; then
50                 msg_usage " is_no {value}"
51                 return 2
52         fi
53
54         case "$1" in
55           no|No|NO|false|False|FALSE|off|Off|OFF|N|n|0)
56                 # true returns zero
57                 return 0
58                 ;;
59           *)
60                 # false returns one
61                 return 1
62                 ;;
63         esac
64 }
65
66 if is_yes "$FASTRC"; then
67         INIT_DOTS=$(awk "BEGIN{for(\$i=0;\$i<$INIT_COL;\$i++)printf(\".\");}")
68         initlog()
69         {
70                 RESULT=0
71                 while [ "$1" != "${1##-}" ] || [ "$1" != "${1##+}" ]; do
72                         case $1 in
73                                 -c)
74                                         shift
75                                         $1
76                                         RESULT=$?
77                                         break
78                                         ;;
79                                  *)
80                                         shift
81                                         ;;
82                         esac
83                 done
84                 return $RESULT
85         }
86 fi
87
88 kernelver()
89 {
90         awk '{split($3,v,"."); printf("%03d%03d%03d\n", v[1],v[2],v[3]);}' /proc/version
91 }
92
93 kernelverser()
94 {
95         awk '{split($3,v,"."); printf("%03d%03d\n", v[1],v[2]);}' /proc/version
96 }
97
98 kernelvermser()
99 {
100         awk '{split($3,v,"."); printf("%03d\n", v[1]);}' /proc/version
101 }
102
103 # Colors workaround
104 termput()
105 {
106         if is_yes "$FASTRC" || [ ! -d /usr/share/terminfo ] || \
107            [ ! -x /usr/bin/tput -a ! -x /bin/tput ]; then
108                 case "$1" in
109                   hpa)
110                         echo -ne "\033[$(($2+1))G"
111                         ;;
112                   cuu*)
113                         echo -ne "\033[${2}A"
114                         ;;
115                   el)
116                         echo -ne "\033[0K"
117                         ;;
118                   setaf)
119                         is_yes "$COLOR_INIT" && echo -ne "\033[0;3${2}m"
120                         ;;
121                   op)
122                         termput setaf 9
123                         ;;
124                 esac
125         else
126                 # check if we are on proper terminal
127                 tput longname > /dev/null 2>&1 || return
128
129                 case "$1" in
130                   hpa | cuu* | el)
131                         tput "$@"
132                         ;;
133                   setaf)
134                         is_yes "$COLOR_INIT" && tput "$@"
135                         ;;
136                   op)
137                         tput setaf 9
138                         ;;
139                 esac
140         fi
141 }
142
143 # printf equivalent
144 printf_()
145 {
146         typeset text m
147         text="$1" ;
148         shift ;
149         if [ $# -gt 0 ]; then
150                 m="$1";
151                 shift;
152                 while [ $# -gt 0 ]; do
153                         m="$m\",\"$1" ;
154                         shift ;
155                 done
156         fi
157         awk "BEGIN {printf \"$text\", \"$m\"; }"
158 }
159
160 # National language support function
161 nls()
162 {
163         typeset msg_echo old_nls_domain text message
164         msg_echo='\n'
165         old_nls_domain="$NLS_DOMAIN"
166         # parse command line
167         # don't use -o instead || here - this will break ksh --misiek
168         while [ "$1" != "${1##-}" ] || [ "$1" != "${1##+}" ]; do
169                 case "$1" in
170                   --nls-domain)
171                         shift
172                         NLS_DOMAIN="$1"
173                         shift
174                         ;;
175                   -n)
176                         msg_echo=''
177                         shift
178                         ;;
179                 esac
180         done
181         message="$1"
182         shift
183         # empty message, so we return --misiek
184         if [ -z "$message" ]; then
185                 NLS_DOMAIN="$old_nls_domain"
186                 echo -en "$msg_echo"
187                 return
188         fi
189
190         if is_yes "$FASTRC"; then
191                 printf "$message" "$@"
192         elif [ -x /bin/gettext -o -x /usr/bin/gettext ]; then
193                 text=$(TEXTDOMAINDIR="/etc/sysconfig/locale" gettext -e --domain="${NLS_DOMAIN:-rc-scripts}" "$message")
194                 printf_ "$text" "$@"
195         else
196                 printf_ "$message" "$@"
197         fi
198
199         echo -en "$msg_echo"
200         NLS_DOMAIN="$old_nls_domain"
201 }
202
203 rc_splash()
204 {
205         typeset action
206
207         action="$1"
208
209         if ! is_no "$BOOT_SPLASH"; then
210                 [ -x /bin/splash ] && /bin/splash "$action"
211         fi
212
213         : $((progress++))
214 }
215
216 msg_network_down()
217 {
218         nls "ERROR: Networking is down. %s can't be run." "$1" >&2
219 }
220
221 msg_starting()
222 {
223         show "Starting %s service" "$1"
224 }
225
226 msg_already_running()
227 {
228         nls "%s service is already running." "$1"
229 }
230
231 msg_stopping()
232 {
233         show "Stopping %s service" "$1"
234 }
235
236 msg_not_running()
237 {
238         nls "%s service is not running." "$1"
239 }
240
241 msg_reloading()
242 {
243         show "Reloading %s service" "$1"
244 }
245
246 msg_usage()
247 {
248         nls "Usage: %s" "$*"
249 }
250
251 # Some functions to handle PLD-style messages
252 show()
253 {
254         typeset text
255
256         if is_yes "$FASTRC"; then
257                 echo -n "$INIT_DOTS"
258                 termput hpa 0
259                 printf "$@"
260                 termput hpa $INIT_COL
261         else
262                 text=$(nls "$@")
263                 echo -n "$text"
264                 awk "BEGIN { for (j=length(\"$text\"); j<$INIT_COL; j++) printf \".\" }"
265         fi
266 }
267
268 # Displays message in square brackests ("[ DONE ]"). Takes two arguments.
269 # First is the text to display, second is color number to use (argument to
270 # tput setaf). If second argument is not given, default (2, green) will be
271 # used).
272 progress()
273 {
274         typeset COLOR
275         if [ -n "$2" ]; then COLOR="$2"; else COLOR="2"; fi
276         deltext
277         echo -n "$(termput setaf 6)[$(termput setaf "$COLOR") $(nls --nls-domain rc-scripts "$1") $(termput setaf 6)]$(termput op)"
278 }
279
280 busy()
281 {
282         progress "BUSY" 5
283 }
284
285 ok()
286 {
287         progress "DONE"
288         echo
289 }
290
291 started()
292 {
293         progress "WORK"
294         echo
295 }
296
297 fail()
298 {
299         progress "FAIL" 1
300         echo
301         return 1
302 }
303
304 died()
305 {
306         progress "DIED" 1
307         echo
308         return 1
309 }
310
311 deltext()
312 {
313         termput hpa $INIT_COL
314 }
315
316 # Check if $pid (could be plural) are running
317 checkpid()
318 {
319         while [ "$1" ]; do
320                 [ -d "/proc/$1" ] && return 0
321                 shift
322         done
323         return 1
324 }
325
326 # outside chroot get only thsese processes which are outside chroot.
327 # inside chroot get only these processes which are inside of chroot.
328 # (note: some processes like named are chrooted but run outside chroot)
329 filter_chroot()
330 {
331         [ $# -lt 1 ] && return
332         good_pids=""
333         for root_pid in $@; do
334                 root_dir=$(resolvesymlink /proc/${root_pid}/root)
335                 if [ -n "$root_dir" ]; then
336                         for r_dir in ${SYSTEM_CHROOTS}; do
337                                 [ "$rewt" = "$CHROOT_TO_DIR" ] && good_pids="$good_pids $root_pid"
338                         done
339                         [ "$root_dir" = "/" -o "$root_dir" = "/usr/share/empty" ] && good_pids="$good_pids $root_pid"
340                 fi
341        done
342        echo $good_pids
343 }
344
345 # Usage run_cmd Message command_to_run
346 run_cmd()
347 {
348         typeset exit_code errors message force_err
349         typeset -i force_err=0
350         typeset -i exit_code=0
351         case "$1" in
352           -a)
353                 force_err=1
354                 shift
355                 ;;
356         esac
357         message=$1
358         show "$message"; busy
359         shift
360         if errors=$(HOME=/tmp TMPDIR=/tmp initlog -c "$*" 2>&1); then
361                 ok
362                 log_success "$1 $message"
363         else
364                 fail
365                 log_failed "$1 $message"
366                 exit_code=1
367         fi
368         [ -n "$errors" ] && [ $exit_code -eq 1 -o $force_err -eq 1 ] && echo "$errors"
369         return $exit_code
370 }
371
372 # A function to start a program (now it's useful on read-only filesystem too)
373 daemon()
374 {
375         typeset errors="" prog="" limits=""
376         typeset -i exit_code=0
377         [ -z "$DEFAULT_SERVICE_RUN_NICE_LEVEL" ] && DEFAULT_SERVICE_RUN_NICE_LEVEL=0
378         # "-u unlimited" (-p for ksh) to make sure daemons will be able to fork.
379         # "-c 0" to make sure it doesn't core dump anywhere; while this could mask
380         # problems with the daemon, it also closes some security problems.
381         # Users' limits are set via pam_limits.
382         [ -z "$DEFAULT_SERVICE_LIMITS" ] && DEFAULT_SERVICE_LIMITS_HARD="-u unlimited -c 0"
383         # Test syntax. Don't use -o instead || here - this will break ksh --misiek
384         while [ "$1" != "${1##-}" ] || [ "$1" != "${1##+}" ]; do
385                 case $1 in
386                   '')
387                         msg_usage " daemon [--user user] [+/-nicelevel] {program}"
388                         return 2
389                         ;;
390                   --check)
391                         # for compatibility with redhat/mandrake
392                         nls "warning: --check option is ignored!"
393                         shift
394                         shift
395                         ;;
396                   --user)
397                         shift
398                         [ "$1" != "root" ] && prog="/bin/su $1 -c \""
399                         shift
400                         ;;
401                   -*|+*) SERVICE_RUN_NICE_LEVEL=$1
402                         shift;;
403                 esac
404         done
405         # If command to execute ends with quotation mark, add remaining
406         # arguments and close quotation.
407         if [ "$prog" != "${prog%\"}" ]; then
408                 prog="$prog $*\""
409         else
410                 prog="$prog $*"
411         fi
412
413         if [ -n "$KSH_VERSION" ]; then
414                 limits="`echo "${SERVICE_LIMITS:-$DEFAULT_SERVICE_LIMITS}" | awk '/-Su/ {sub(/-Su/,"-Sp");} /-Hu/ {sub(/-Hu/,"-Hp");} /-u/ {sub(/-u/,"-p");} {print;}'`"
415         elif [ -n "$ZSH_VERSION" ]; then
416                 limits="${SERVICE_LIMITS:-$DEFAULT_SERVICE_LIMITS}"
417         elif [ -n "$BASH_VERSION" ]; then
418                 limits="${SERVICE_LIMITS:-$DEFAULT_SERVICE_LIMITS}"
419 #       elif [ -n "`$SH -c 'echo ${.sh.version}' 2>/dev/null`" ]; then
420         fi
421
422         [ -n "$limits" ] && eval `echo "$limits" | awk 'BEGIN {RS="[-\n]";} !/^ *$/ { print "ulimit -" $0; }'`
423
424         # And start it up.
425         busy
426         if errors=$(USER=root HOME=/tmp TMPDIR=/tmp nice -n ${SERVICE_RUN_NICE_LEVEL:-$DEFAULT_SERVICE_RUN_NICE_LEVEL} initlog -c "$prog" 2>&1); then
427                 log_success "$1 startup"
428                 ok
429         else
430                 exit_code=1
431                 fail
432                 log_failed "$1 startup"
433                 [ -n "$errors" ] && echo "$errors"
434         fi
435         return $exit_code
436 }
437
438 # A function to stop a program.
439 killproc()
440 {
441         typeset notset killlevel base pid result
442         # Test syntax.
443         if [ $# = 0 ]; then
444                 msg_usage " killproc {program} [signal]"
445                 return 2
446         fi
447
448         busy
449
450         typeset -i notset=0
451         # check for second arg to be kill level
452         if [ -n "$2" ] ; then
453                 killlevel=$2
454         else
455                 notset=1
456                 killlevel="-9"
457         fi
458
459         # Save basename.
460         base=$(basename "$1")
461
462         # Find pid.
463         pid=$(pidofproc "$1")
464         [ -z "$pid" ] && pid=$(pidofproc "$base")
465
466         # Kill it.
467         if [ -n "$pid" -a "$pid" != "$$" ] && checkpid $pid 2>&1 ; then
468                 if [ "$notset" = "1" ] ; then
469                         if checkpid $pid 2>&1; then
470                                 # TERM first, then KILL if not dead
471                                 kill -TERM $pid
472                                 usleep 100000
473                                 if checkpid $pid && sleep 1 &&
474                                         checkpid $pid && sleep 3 &&
475                                         checkpid $pid; then
476                                         kill -KILL $pid
477                                         usleep 100000
478                                 fi
479                         fi
480                         checkpid $pid
481                         result=$?
482                         if [ "$result" -eq 0 ]; then
483                                 fail
484                                 log_failed "$1 shutdown"
485                         else
486                                 ok
487                                 log_success "$1 shutdown"
488                         fi
489                         result=$(( ! $result ))
490                 else
491                         # use specified level only
492                         if checkpid $pid > /dev/null 2>&1; then
493                                 kill $killlevel $pid
494                                 result=$?
495                                 if [ "$result" -eq 0 ]; then
496                                         ok
497                                         log_success "$1 got $killlevel"
498                                 else
499                                         result=7
500                                         fail
501                                         log_failed "$1 didn't get $killlevel"
502                                 fi
503                         else
504                                 result=7
505                                 died
506                                 log_failed "$1 shutdown"
507                         fi
508                 fi
509         else
510                 died
511                 log_failed "$1 shutdown"
512                 result=7
513         fi
514
515         # Remove pid file if any.
516         if [ "$notset" = "1" ]; then
517                 rm -f /var/run/${base}.pid
518         fi
519
520         return $result
521 }
522
523 # A function to find the pid of a program.
524 pidofproc()
525 {
526         typeset pid base
527         base=$(basename "$1")
528
529         # Test syntax.
530         if [ $# = 0 ] ; then
531                 msg_usage " pidofproc {program}"
532                 return 2
533         fi
534
535         # First try "/var/run/*.pid" files
536         if [ -f /var/run/${base}.pid ] ; then
537                 typeset line p pid
538                 pid=
539                 read line < /var/run/${base}.pid
540                 for p in $line; do
541                         [ -z "$(echo "$p" | awk '{gsub(/[0-9]/,"");print;}')" ] && pid="$pid $p"
542                 done
543         fi
544
545         # Next try "pidof"
546         [ -z "$pid" ] && pidof -o $$ -o $PPID -o %PPID -x "$1"
547         pid=$(filter_chroot "$pid")
548         echo $pid
549 }
550
551 status()
552 {
553         typeset base pid subsys daemon
554         subsys=$1
555         daemon=${2:-$subsys}
556         base=$(basename $daemon)
557
558         # Test syntax.
559         if [ $# = 0 ] ; then
560                 msg_usage " status {subsys} [{daemon}]"
561                 return 2
562         fi
563
564         # First try "pidof"
565         pid=$(pidof -o $$ -o $PPID -o %PPID -x $daemon)
566         pid=$(filter_chroot "$pid")
567
568         if [ "$pid" != "" ]; then
569                 nls "%s (pid %s) is running..." "$daemon" "$pid"
570                 return 0
571 #       else
572 #               pid=`ps ax | awk 'BEGIN { prog=ARGV[1]; ARGC=1 }
573 #                    { if ((prog == $5) || (("(" prog ")") == $5) ||
574 #                         (("[" prog "]") == $5) ||
575 #                         ((prog ":") == $5)) { print $1 ; exit 0 } }' $1`
576 #               if [ "$pid" != "" ]; then
577 #                       nls "%s (pid %s) is running..." "$daemon" "$pid"
578 #                       return 0
579 #               fi
580         fi
581
582         # Next try "/var/run/*.pid" files
583         if [ -f /var/run/${base}.pid ]; then
584                 read pid < /var/run/${base}.pid
585                 pid=$(filter_chroot "$pid")
586                 if [ "$pid" != "" ]; then
587                         nls "%s dead but pid file exists" "$subsys"
588                         return 1
589                 fi
590         fi
591
592         # See if /var/lock/subsys/$subsys exists
593         if [ -f /var/lock/subsys/$subsys ]; then
594                 nls "%s dead but subsys locked" "$subsys"
595                 return 2
596         fi
597         nls "%s is stopped" "$subsys"
598         return 3
599 }
600
601 # Confirm whether we really want to run this service
602 confirm() {
603         typeset answer
604         nls -n "Start service %s (Y)es/(N)o/(C)ontinue? [Y] " "$1"
605         read answer
606         case $answer in
607           y|Y|t|T|j|J|"")
608                 return 0
609                 ;;
610           c|C|k|K|w|W)
611                 return 2
612                 ;;
613           n|N)
614                 return 1
615                 ;;
616           *)
617                 confirm $1
618                 return $?
619                 ;;
620         esac
621 }
622
623 # module is needed (ie. is requested, is available and isn't loaded already)
624 is_module()
625 {
626         # module name without .o at end
627         if ! (lsmod | grep -q "$1"); then
628                 if (ls -R /lib/modules/$(uname -r)/ 2> /dev/null | grep -q "${1}.\(\|k\)o\(\|.gz\)"); then
629                         # true
630                         return 0
631                 fi
632         fi
633         # false
634         return 1
635 }
636
637 _modprobe()
638 {
639         typeset parsed single die args foo result
640         parsed=no
641         while is_no "$parsed" ; do
642                 case "$1" in
643                   "single")
644                         single=yes
645                         shift
646                         ;;
647                   "die")
648                         die=yes
649                         shift
650                         ;;
651                   -*)
652                         args="$args $1"
653                         shift
654                         ;;
655                   *)
656                         parsed=yes
657                         ;;
658                 esac
659         done
660         if is_yes "${single}" ; then
661                 foo="$@"
662                 show "Loading %s kernel module(s)" "$foo"
663                 busy
664         fi
665         if [ -x /sbin/modprobe ] ; then
666                 /sbin/modprobe -s $args "$@"
667                 result=$?
668         else
669                 deltext ; fail
670                 result=1
671         fi
672         if is_yes "${single}" ; then
673                 deltext
674                 if [ $result == "0" ] ; then
675                         is_yes "$single" && ok
676                 else
677                         fail
678                         if is_yes "$die" ; then
679                                 nls "Could not load %s kernel module(s)" "$@"
680                                 exit 1
681                         fi
682                 fi
683         fi
684 }
685
686 log_success ()
687 {
688         initlog -n $0 -s "$1 $2" -e 1
689 }
690
691 log_failed ()
692 {
693         initlog -n $0 -s "$1 $2" -e 2
694 }
695
696 # RedHat/Mandrake specific functions
697 action () { STRING=$1; shift; run_cmd "$STRING" "$*"; }
698 success () { return 0; }
699 failure () { return 1; }
700
701 # TO BE REMOVED IN AC. --ankry
702 msg_Network_Down () { msg_network_down "$*"; }
703 msg_Already_Running () { msg_already_running "$*"; }
704 msg_Not_Running () { msg_not_running "$*"; }
705 msg_Usage () { msg_usage "$*"; }
706
707 #/*
708 # * Local variables:
709 # * mode: sh
710 # * indent-tabs-mode: notnil
711 # * End:
712 # *
713 # */
714 # vi: syntax=sh:shiftwidth=8:
This page took 0.082777 seconds and 3 git commands to generate.