rc.subr revision 1.34
1# $NetBSD: rc.subr,v 1.34 2001/05/07 07:07:11 lukem Exp $
2#
3# Copyright (c) 1997-2000 The NetBSD Foundation, Inc.
4# All rights reserved.
5#
6# This code is derived from software contributed to The NetBSD Foundation
7# by Luke Mewburn.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12# 1. Redistributions of source code must retain the above copyright
13#    notice, this list of conditions and the following disclaimer.
14# 2. Redistributions in binary form must reproduce the above copyright
15#    notice, this list of conditions and the following disclaimer in the
16#    documentation and/or other materials provided with the distribution.
17# 3. All advertising materials mentioning features or use of this software
18#    must display the following acknowledgement:
19#        This product includes software developed by the NetBSD
20#        Foundation, Inc. and its contributors.
21# 4. Neither the name of The NetBSD Foundation nor the names of its
22#    contributors may be used to endorse or promote products derived
23#    from this software without specific prior written permission.
24#
25# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35# POSSIBILITY OF SUCH DAMAGE.
36#
37# rc.subr
38#	functions used by various rc scripts
39#
40
41#
42#	functions
43#	---------
44
45#
46# checkyesno var
47#	Test $1 variable, and warn if not set to YES or NO.
48#	Return 0 if it's "yes" (et al), nonzero otherwise.
49#
50checkyesno()
51{
52	eval _value=\$${1}
53	case $_value in
54
55		#	"yes", "true", "on", or "1"
56	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
57		return 0
58		;;
59
60		#	"no", "false", "off", or "0"
61	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
62		return 1
63		;;
64	*)
65		warn "\$${1} is not set properly."
66		return 1
67		;;
68	esac
69}
70
71#
72# mount_critical_filesystems
73#	Go through the list of critical filesystems, checking each one
74#	to see if it is mounted, and if it is not, mounting it.
75#
76mount_critical_filesystems()
77{
78	if [ $1 = local ]; then
79		_fslist=$critical_filesystems_beforenet
80	else
81		_fslist=$critical_filesystems
82	fi
83	for _fs in $_fslist; do
84		mount | (
85			_ismounted=no
86			while read what _on on _type type; do
87				if [ $on = $_fs ]; then
88					_ismounted=yes
89				fi
90			done
91			if [ $_ismounted = no ]; then 
92				mount $_fs >/dev/null 2>&1
93			fi
94		)  
95	done
96}
97
98#
99# check_pidfile pidfile procname
100#	Parses the first line of pidfile for a pid, and ensures
101#	that the process is running and matches procname.
102#	Prints the matching pid upon success, nothing otherwise.
103#
104check_pidfile()
105{
106	_pidfile=$1
107	_procname=$2
108	if [ -z "$_pidfile" -o -z "$_procname" ]; then
109		err 3 'USAGE: check_pidfile pidfile procname'
110	fi
111	if [ ! -f $_pidfile ]; then
112		return
113	fi
114	read _pid _junk < $_pidfile
115	if [ -z "$_pid" ]; then
116		return
117	fi
118	_procnamebn=${_procname##*/}
119	ps -p $_pid -o 'pid,command' | while read _npid _arg0 _argv; do
120		case "$_npid" in
121		    PID)
122			continue ;;
123		esac
124		case "$_arg0" in
125		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")
126			echo $_npid
127			return
128			;;
129		esac
130	done
131}
132
133#
134# check_process procname
135#	Ensures that a process (or processes) named procname is running.
136#	Prints a list of matching pids.
137#
138check_process()
139{
140	_procname=$1
141	if [ -z "$_procname" ]; then
142		err 3 'USAGE: check_process procname'
143	fi
144	_procnamebn=${_procname##*/}
145	_pref=
146	ps -ax -o 'pid,command' | while read _npid _arg0 _argv; do
147		case "$_npid" in
148		    PID)
149			continue ;;
150		esac
151		case "$_arg0" in
152		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")
153			echo -n "$_pref$_npid"
154			_pref=" "
155			;;
156		esac
157	done
158}
159
160#
161# wait_for_pids pid [pid ...]
162#	spins until none of the pids exist or loop finally terminates
163#	(~ 65 seconds)
164#
165wait_for_pids()
166{
167	_list=$*
168	if [ -z "$_list" ]; then
169		return
170	fi
171	echo -n "Waiting for PIDs: $_list"
172	for _i in 1 1 1 1 2 2 2 3 3 4 5 6 7 8 9 10; do
173		_nlist="";
174		for _j in $_list; do
175			if kill -0 $_j 2>/dev/null; then
176				_nlist="${_nlist}${_nlist:+ }$_j"
177			fi
178		done
179		if [ -z "$_nlist" ]; then
180			break
181		fi
182		_list=$_nlist
183		sleep $_i
184		echo -n ", $_list"
185	done
186	echo "."
187}
188
189#
190# run_rc_command arg
191#	Search for arg in the list of supported commands, which is:
192#		"start stop restart rcvar status poll ${extra_commands}"
193#	If there's a match, run ${arg}_cmd or the default command (see below).
194#
195#	If arg has a given prefix, then change the operation as follows:
196#		prefix	operation
197#		------	---------
198#		fast	Skip the pid check.
199#		force	Set ${rcvar} to YES.
200#
201#	The following globals are used:
202#
203#	name		needed	function
204#	----		------	--------
205#	name		y	Name of script.
206#
207#	command		n	Full path to command.
208#				Not needed if ${arg}_cmd is set for
209#				each keyword.
210#
211#	command_args	n	Optional args/shell directives for command.
212#
213#	extra_commands	n	List of extra commands supported.
214#
215#	pidfile		n	If set, use check_pidfile $pidfile, else if
216#				$command is set, use check_process $command.
217#
218#	rcvar		n	This is checked with checkyesno to determine
219#				if the action should be run.
220#
221#	${name}_chroot	n	Directory to chroot to before running ${command}
222#
223#	${name}_chdir	n	Directory to cd to before running ${command}
224#				(if not using ${name}_chroot).
225#
226#	${name}_flags	n	Arguments to call ${command} with.
227#				NOTE:	$flags from the parent environment
228#					can be used to override this.
229#
230#	${name}_nice	n	Nice level to run ${command} at.
231#
232#	${name}_user	n	User to run ${command} as, using su(1) if not
233#				using ${name}_chroot.
234#
235#	${name}_group	n	Group to run chrooted ${command} as.
236#
237#	${name}_groups	n	Comma separated list of supplementary groups
238#				to run the chrooted ${command} with.
239#
240#	${_arg}_cmd	n	If set, use this as the action when invoked;
241#				$_arg is available to the action to use.
242#				Otherwise, use default command (see below)
243#
244#	${_arg}_precmd	n	If set, run just before performing the main
245#				action in the default command (i.e, after
246#				checking for required bits and process
247#				(non)existance).
248#				If this completes with a non-zero exit code,
249#				don't run ${_arg}_cmd.
250#
251#	required_dirs	n	If set, check for the existence of the given
252#				directories before running the default
253#				(re)start command.
254#
255#	required_files	n	If set, check for the readability of the given
256#				files before running the default (re)start
257#				command.
258#
259#	required_vars	n	If set, perform checkyesno on each of the
260#				listed variables before running the default
261#				(re)start command.
262#
263#	Default commands for a given arg:
264#
265#	arg		default
266#	---		-------
267#	start		if !running && checkyesno ${rcvar}
268#				${command}
269#
270#	stop		if ${pidfile}
271#				kill $sig_stop `check_pidfile $pidfile`
272#			else
273#				kill $sig_stop `check_process $command`
274#			$sig_stop defaults to TERM.
275#
276#	reload		As stop, except use $sig_reload instead.
277#			$sig_reload defaults to HUP.
278#
279#	restart		Run `stop' then `start'.
280#
281#	status		Show if ${command} is running, etc.
282#
283#	poll		Wait for ${command} to exit.
284#
285#	rcvar		Display what rc.conf variable is used (if any).
286#
287#
288#
289run_rc_command()
290{
291	_arg=$1
292	if [ -z "$name" ]; then
293		err 3 'run_rc_command: $name is not set.'
294	fi
295
296	case "$_arg" in
297	fast*)				# "fast" prefix; don't check pid
298		_arg=${_arg#fast}
299		_rc_fast_run=YES
300		;;
301	force*)				# "force prefix; always start
302		_arg=${_arg#force}
303		_rc_force_run=YES
304		if [ -n "${rcvar}" ]; then
305			eval ${rcvar}=YES
306		fi
307		;;
308	esac
309
310	_keywords="start stop restart rcvar $extra_commands"
311	_pid=
312	_pidcmd=
313					# setup pid check command if not fast
314	if [ -z "$_rc_fast_run" ]; then
315		if [ -n "$pidfile" ]; then
316			_pidcmd='_pid=`check_pidfile '$pidfile' '$command'`'
317		elif [ -n "$command" ]; then
318			_pidcmd='_pid=`check_process '$command'`'
319		fi
320		if [ -n "$_pidcmd" ]; then
321			_keywords="${_keywords} status poll"
322		fi
323	fi
324
325	if [ -z "$_arg" ]; then
326		rc_usage "$_keywords"
327	fi
328
329	if [ -n "$flags" ]; then	# allow override from environment
330		_flags=$flags
331	else
332		eval _flags=\$${name}_flags
333	fi
334	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
335	    _nice=\$${name}_nice	_user=\$${name}_user \
336	    _group=\$${name}_group	_groups=\$${name}_groups
337
338					# if ${rcvar} is set, and $1 is not
339					# "rcvar" or "status", then run
340					#	checkyesno ${rcvar}
341					# and return if that failed
342					#
343	# XXXX use case?
344	if [ -n "${rcvar}" -a "$_arg" != "rcvar" -a "$_arg" != "status" ]; then
345		if ! checkyesno ${rcvar}; then
346			return 0
347		fi
348	fi
349
350	eval $_pidcmd			# determine the pid if necessary
351
352	for _elem in $_keywords; do
353		if [ "$_elem" != "$_arg" ]; then
354			continue
355		fi
356
357					# if there's a custom ${XXX_cmd},
358					# run that instead of the default
359					#
360		eval _cmd=\$${_arg}_cmd _precmd=\$${_arg}_precmd
361		if [ -n "$_cmd" ]; then
362					# if the precmd failed and force
363					# isn't set, exit
364					#
365			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
366				return 1
367			fi
368
369			eval $_cmd
370			return 0
371		fi
372
373		case "$_arg" in		# default operations...
374
375		status)
376			if [ -n "$_pid" ]; then
377				echo "${name} is running as pid $_pid."
378			else
379				echo "${name} is not running."
380				return 1
381			fi
382			;;
383
384		start)
385			if [ -n "$_pid" ]; then
386				echo "${name} already running? (pid=$_pid)."
387				exit 1
388			fi
389
390			if [ ! -x $command ]; then
391				return 0
392			fi
393
394					# check for required variables,
395					# directories, and files
396					#
397			for _f in $required_vars; do
398				if ! checkyesno $_f; then
399					warn "\$${_f} is not set."
400					if [ -z "$_rc_force_run" ]; then
401						return 1
402					fi
403				fi
404			done
405			for _f in $required_dirs; do
406				if [ ! -d "${_f}/." ]; then
407					warn "${_f} is not a directory."
408					if [ -z "$_rc_force_run" ]; then
409						return 1
410					fi
411				fi
412			done
413			for _f in $required_files; do
414				if [ ! -r "${_f}" ]; then
415					warn "${_f} is not readable."
416					if [ -z "$_rc_force_run" ]; then
417						return 1
418					fi
419				fi
420			done
421
422					# if the precmd failed and force
423					# isn't set, exit
424					#
425			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
426				return 1
427			fi
428
429
430					# setup the command to run, and run it
431					#
432			echo "Starting ${name}."
433			if [ -n "$_chroot" ]; then
434				_doit="\
435${_nice:+nice -n $_nice }\
436chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
437$_chroot $command $_flags $command_args"
438			else
439				_doit="\
440${_chdir:+cd $_chdir; }\
441${_nice:+nice -n $_nice }\
442$command $_flags $command_args"
443				if [ -n "$_user" ]; then
444				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
445				fi
446			fi
447			eval $_doit
448			;;
449
450		stop)
451			if [ -z "$_pid" ]; then
452				if [ -n "$pidfile" ]; then
453					echo \
454				    "${name} not running? (check $pidfile)."
455				else
456					echo "${name} not running?"
457				fi
458				exit 1
459			fi
460
461			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
462				return 1
463			fi
464			echo "Stopping ${name}."
465			_doit="kill -${sig_stop:-TERM} $_pid"
466			if [ -n "$_user" ]; then
467				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
468			fi
469			eval $_doit
470			;;
471
472		reload)
473			if [ -z "$_pid" ]; then
474				if [ -n "$pidfile" ]; then
475					echo \
476				    "${name} not running? (check $pidfile)."
477				else
478					echo "${name} not running?"
479				fi
480				exit 1
481			fi
482			echo "Reloading ${name} config files."
483			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
484				return 1
485			fi
486			_doit="kill -${sig_reload:-HUP} $_pid"
487			if [ -n "$_user" ]; then
488				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
489			fi
490			eval $_doit
491			;;
492
493		restart)
494			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
495				return 1
496			fi
497					# prevent restart being called more
498					# than once by any given script
499					#
500			if [ -n "$_rc_restart_done" ]; then
501				return 0
502			fi
503			_rc_restart_done=YES
504
505			( $0 ${_rc_force_run:+force}stop )
506			( $0 ${_rc_force_run:+force}poll )
507			$0 ${_rc_force_run:+force}start
508
509			;;
510
511		poll)
512			if [ -n "$_pid" ]; then
513				wait_for_pids $_pid
514			fi
515			;;
516
517		rcvar)
518			echo "# $name"
519			if [ -n "$rcvar" ]; then
520				if checkyesno ${rcvar}; then
521					echo "\$${rcvar}=YES"
522				else
523					echo "\$${rcvar}=NO"
524				fi
525			fi
526			;;
527
528		*)
529			rc_usage "$_keywords"
530			;;
531
532		esac
533		return 0
534	done
535
536	echo 1>&2 "$0: unknown directive '$_arg'."
537	rc_usage "$_keywords"
538	exit 1
539}
540
541#
542# run_rc_script file arg
543#	Start the script `file' with `arg', and correctly handle the
544#	return value from the script.  If `file' ends with `.sh', it's
545#	sourced into the current environment.  Otherwise it's run as
546#	a child process.
547#
548#	Note: because `.sh' files are sourced into the current environment
549#	run_rc_command shouldn't be used because its difficult to ensure
550#	that the global variable state before and after the sourcing of 
551#	the .sh file won't adversely affect other scripts.
552#
553run_rc_script()
554{
555	_file=$1
556	_arg=$2
557	if [ -z "$_file" -o -z "$_arg" ]; then
558		err 3 'USAGE: run_rc_script file arg'
559	fi
560
561	if [ -n "$rc_fast_and_loose" ]; then
562		unset name command command_args extra_commands pidfile rcvar
563		unset required_dirs required_files required_vars
564		eval unset ${_arg}_cmd ${_arg}_precmd
565		set $_arg ; . $_file
566	else
567		case "$_file" in
568		*.sh)				# run in current shell
569			set $_arg ; . $_file
570			;;
571		*)				# run in subshell
572			( set $_arg ; . $_file )
573			;;
574		esac
575	fi
576}
577
578#
579# load_rc_config
580#	Source in the configuration file for a given command.
581#
582load_rc_config()
583{
584	_command=$1
585	if [ -z "$_command" ]; then
586		err 3 'USAGE: load_rc_config command'
587	fi
588
589	if [ -z "$_rc_conf_loaded" ]; then
590		. /etc/rc.conf
591		_rc_conf_loaded=YES
592	fi
593	if [ -f /etc/rc.conf.d/"$_command" ]; then
594		. /etc/rc.conf.d/"$_command"
595	fi
596}
597
598
599#
600# rc_usage commands
601#	Print a usage string for $0, with `commands' being a list of
602#	valid commands.
603#
604rc_usage()
605{
606	echo -n 1>&2 "Usage: $0 [fast|force]("
607
608	_sep=
609	for _elem in $*; do
610		echo -n 1>&2 "$_sep$_elem"
611		_sep="|"
612	done
613	echo 1>&2 ")"
614	exit 1
615}
616
617#
618# err exitval message
619#	Display message to stderr and log to the syslog, and exit with exitval.
620#
621err()
622{
623	exitval=$1
624	shift
625
626	logger "$0: ERROR: $*"
627	echo 1>&2 "$0: ERROR: $*"
628	exit $exitval
629}
630
631#
632# warn message
633#	Display message to stderr and log to the syslog.
634#
635warn()
636{
637	logger "$0: WARNING: $*"
638	echo 1>&2 "$0: WARNING: $*"
639}
640
641#
642# backup_file action file cur backup
643#	Make a backup copy of `file' into `cur', and save the previous
644#	version of `cur' as `backup' or use rcs for archiving.
645#
646#	This routine checks the value of the backup_uses_rcs variable,
647#	which can be either YES or NO.
648#
649#	The `action' keyword can be one of the following:
650#
651#	add		`file' is now being backed up (and is possibly
652#			being reentered into the backups system).  `cur'
653#			is created and RCS files, if necessary, are
654#			created as well.
655#
656#	update		`file' has changed and needs to be backed up.
657#			If `cur' exists, it is copied to to `back' or
658#			checked into RCS (if the repository file is old),
659#			and then `file' is copied to `cur'.  Another RCS
660#			check in done here if RCS is being used.
661#
662#	remove		`file' is no longer being tracked by the backups
663#			system.  If RCS is not being used, `cur' is moved
664#			to `back', otherwise an empty file is checked in,
665#			and then `cur' is removed.
666#
667#
668backup_file()
669{
670	_action=$1
671	_file=$2
672	_cur=$3
673	_back=$4
674
675	if checkyesno backup_uses_rcs; then
676		_msg0="backup archive"
677		_msg1="update"
678
679		# ensure after switching to rcs that the
680		# current backup is not lost
681		if [ -f $_cur ]; then
682			# no archive, or current newer than archive
683			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
684				ci -q -f -l -t-"$_msg0" -m"$_msg1" $_cur
685				rcs -q -kb $_cur
686			fi
687		fi
688
689		case $_action in
690		add|update)
691			cp -p $_file $_cur
692			ci -q -f -l -t-"$_msg0" -m"$_msg1" $_cur
693			rcs -q -kb $_cur
694			chown root:wheel $_cur $_cur,v
695			;;
696		remove)
697			cp /dev/null $_cur
698			ci -q -f -l -t-"$_msg0" -m"$_msg1" $_cur
699			rcs -q -kb $_cur
700			chown root:wheel $_cur $_cur,v
701			rm $_cur
702			;;
703		esac
704	else
705		case $_action in
706		add|update)
707			if [ -f $_cur ]; then
708				cp -p $_cur $_back
709			fi
710			cp -p $_file $_cur
711			chown root:wheel $_cur
712			;;
713		remove)
714			mv -f $_cur $_back
715			;;
716		esac
717	fi
718}
719