rc.subr revision 1.20.2.4
1# $NetBSD: rc.subr,v 1.20.2.4 2000/10/02 01:02:49 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=`basename $_procname`
119	ps -p $_pid -o 'pid,command' | while read _npid _arg0 _argv; do
120		if [ "$_npid" = "PID" ]; then
121			continue
122		fi
123		if [   "$_arg0" = "$_procname" \
124		    -o "$_arg0" = "$_procnamebn" \
125		    -o "$_arg0" = "${_procnamebn}:" \
126		    -o "$_arg0" = "(${_procnamebn})" ]; then
127			echo $_npid
128			return
129		fi
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=`basename $_procname`
145	_pref=
146	ps -ax -o 'pid,command' | while read _npid _arg0 _argv; do
147		if [ "$_npid" = "PID" ]; then
148			continue
149		fi
150		if [   "$_arg0" = "$_procname" \
151		    -o "$_arg0" = "$_procnamebn" \
152		    -o "$_arg0" = "${_procnamebn}:" \
153		    -o "$_arg0" = "(${_procnamebn})" ]; then
154			echo -n "$_pref$_npid"
155			_pref=" "
156		fi
157	done
158}
159
160#
161# run_rc_command arg
162#	Search for arg in the list of supported commands, which is:
163#		"start stop restart rcvar status ${extra_commands}"
164#	If there's a match, run ${arg}_cmd or the default command (see below).
165#
166#	If arg has a given prefix, then change the operation as follows:
167#		prefix	operation
168#		------	---------
169#		fast	Skip the pid check.
170#		force	Set ${rcvar} to YES.
171#
172#	The following globals are used:
173#
174#	name		needed	function
175#	----		------	--------
176#	name		y	Name of script.
177#
178#	command		n	Full path to command.
179#				Not needed if ${arg}_cmd is set for
180#				each keyword.
181#
182#	command_args	n	Optional args/shell directives for command.
183#
184#	extra_commands	n	List of extra commands supported.
185#
186#	pidfile		n	If set, use check_pidfile $pidfile, else if
187#				$command is set, use check_process $command.
188#
189#	rcvar		n	This is checked with checkyesno to determine
190#				if the action should be run.
191#
192#	${name}_chroot	n	Directory to chroot to before running ${command}
193#
194#	${name}_chdir	n	Directory to cd to before running ${command}
195#				(if not using ${name}_chroot).
196#
197#	${name}_flags	n	Arguments to call ${command} with.
198#				NOTE:	$flags from the parent environment
199#					can be used to override this.
200#
201#	${name}_nice	n	Nice level to run ${command} at.
202#
203#	${name}_user	n	User to run ${command} as, using su(1) if not
204#				using ${name}_chroot.
205#
206#	${name}_group	n	Group to run chrooted ${command} as.
207#
208#	${name}_groups	n	Supplementary group list to run chrooted
209#				${command} with.
210#
211#	${_arg}_cmd	n	If set, use this as the action when invoked;
212#				$_arg is available to the action to use.
213#				Otherwise, use default command (see below)
214#
215#	${_arg}_precmd	n	If set, run just before performing the main
216#				action in the default command (i.e, after
217#				checking for required bits and process
218#				(non)existance).
219#				If this completes with a non-zero exit code,
220#				don't run ${_arg}_cmd.
221#
222#	required_dirs	n	If set, check for the existence of the given
223#				directories before running the default
224#				(re)start command.
225#
226#	required_files	n	If set, check for the readability of the given
227#				files before running the default (re)start
228#				command.
229#
230#	required_vars	n	If set, perform checkyesno on each of the
231#				listed variables before running the default
232#				(re)start command.
233#
234#	Default commands for a given arg:
235#
236#	arg		default
237#	---		-------
238#	status		Show if ${command} is running, etc.
239#
240#	start		if !running && checkyesno ${rcvar}
241#				${command}
242#
243#	stop		if ${pidfile}
244#				kill $sig_stop `check_pidfile $pidfile`
245#			else
246#				kill $sig_stop `check_process $command`
247#			$sig_stop defaults to TERM.
248#
249#	reload		As stop, except use $sig_reload instead.
250#			$sig_reload defaults to HUP.
251#
252#	restart		Run `stop' then `start'.
253#
254#
255run_rc_command()
256{
257	_arg=$1
258	if [ -z "$name" ]; then
259		err 3 '$name is not set.'
260	fi
261
262	case "$_arg" in
263	fast*)				# "fast" prefix; don't check pid
264		_arg=${_arg#fast}
265		_rc_fast_run=YES
266		;;
267	force*)				# "force prefix; always start
268		_arg=${_arg#force}
269		_rc_force_run=YES
270		eval ${rcvar}=YES
271		;;
272	esac
273
274	_keywords="start stop restart rcvar $extra_commands"
275	_pid=
276	_pidcmd=
277					# setup pid check command if not fast
278	if [ -z "$_rc_fast_run" ]; then
279		if [ -n "$pidfile" ]; then
280			_pidcmd='_pid=`check_pidfile '$pidfile' '$command'`'
281		elif [ -n "$command" ]; then
282			_pidcmd='_pid=`check_process '$command'`'
283		fi
284		if [ -n "$_pidcmd" ]; then
285			_keywords="${_keywords} status"
286		fi
287	fi
288
289	if [ -z "$_arg" ]; then
290		rc_usage "$_keywords"
291	fi
292
293	if [ -n "$flags" ]; then	# allow override from environment
294		_flags=$flags
295	else
296		eval _flags=\$${name}_flags
297	fi
298	eval _chdir=\$${name}_chdir
299	eval _chroot=\$${name}_chroot
300	eval _nice=\$${name}_nice
301	eval _user=\$${name}_user
302	eval _group=\$${name}_group
303	eval _groups=\$${name}_groups
304
305					# if ${rcvar} is set and we're not
306					# running `rcvar', then check it
307					#
308	if [ -n "${rcvar}" -a "$_arg" != "rcvar" ]; then
309		if ! checkyesno ${rcvar}; then
310			return 0
311		fi
312	fi
313
314	eval $_pidcmd			# determine the pid if necessary
315
316	for _elem in $_keywords; do
317		if [ "$_elem" != "$_arg" ]; then
318			continue
319		fi
320
321					# if there's a custom ${XXX_cmd},
322					# run that instead of the default
323					#
324		eval _cmd=\$${_arg}_cmd
325		eval _precmd=\$${_arg}_precmd
326		if [ -n "$_cmd" ]; then
327					# if the precmd failed and force
328					# isn't set, exit
329					#
330			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
331				return 1
332			fi
333
334			eval $_cmd
335			return 0
336		fi
337
338		case "$_arg" in		# default operations...
339
340		status)
341			if [ -n "$_pid" ]; then
342				echo "${name} is running as pid $_pid."
343			else
344				echo "${name} is not running."
345			fi
346			;;
347
348		start)
349			if [ -n "$_pid" ]; then
350				echo "${name} already running? (pid=$_pid)."
351				exit 1
352			fi
353
354			if [ ! -x $command ]; then
355				return 0
356			fi
357
358					# check for required variables,
359					# directories, and files
360					#
361			for _f in $required_vars; do
362				if ! checkyesno $_f; then
363					warn "\$${_f} is not set."
364					if [ -z "$_rc_force_run" ]; then
365						return 1
366					fi
367				fi
368			done
369			for _f in $required_dirs; do
370				if [ ! -d "${_f}/." ]; then
371					warn "${_f} is not a directory."
372					if [ -z "$_rc_force_run" ]; then
373						return 1
374					fi
375				fi
376			done
377			for _f in $required_files; do
378				if [ ! -r "${_f}" ]; then
379					warn "${_f} is not readable."
380					if [ -z "$_rc_force_run" ]; then
381						return 1
382					fi
383				fi
384			done
385
386					# if the precmd failed and force
387					# isn't set, exit
388					#
389			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
390				return 1
391			fi
392
393
394					# setup the command to run, and run it
395			echo "Starting ${name}."
396			if [ -n "$_chroot" ]; then
397				_doit="\
398${_nice:+nice -n $_nice }\
399chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
400$_chroot $command $_flags $command_args"
401			else
402				_doit="\
403${_user:+su -m $_user -c 'sh -c \"}\
404${_chdir:+cd $_chdir; }\
405${_nice:+nice -n $_nice }\
406$command $_flags $command_args\
407${_user:+\"'}"
408			fi
409			eval $_doit
410			;;
411
412		stop)
413			if [ -z "$_pid" ]; then
414				if [ -n "$pidfile" ]; then
415					echo \
416				    "${name} not running? (check $pidfile)."
417				else
418					echo "${name} not running?"
419				fi
420				exit 1
421			fi
422
423			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
424				return 1
425			fi
426			echo "Stopping ${name}."
427			_doit=\
428"${_user:+su -m $_user -c '}kill -${sig_stop:-TERM} $_pid${_user:+'}"
429			eval $_doit
430			;;
431
432		reload)
433			if [ -z "$_pid" ]; then
434				if [ -n "$pidfile" ]; then
435					echo \
436				    "${name} not running? (check $pidfile)."
437				else
438					echo "${name} not running?"
439				fi
440				exit 1
441			fi
442			echo "Reloading ${name} config files."
443			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
444				return 1
445			fi
446			_doit=\
447"${_user:+su -m $_user -c '}kill -${sig_reload:-HUP} $_pid${_user:+'}"
448			eval $_doit
449			;;
450
451		restart)
452			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
453				return 1
454			fi
455			( $0 stop )
456			sleep 1
457			$0 start
458
459			;;
460
461		rcvar)
462			echo "# $name"
463			if [ -n "$rcvar" ]; then
464				if checkyesno ${rcvar}; then
465					echo "\$${rcvar}=YES"
466				else
467					echo "\$${rcvar}=NO"
468				fi
469			fi
470			;;
471
472		*)
473			rc_usage "$_keywords"
474			;;
475
476		esac
477		return 0
478	done
479
480	echo 1>&2 "$0: unknown directive '$_arg'."
481	rc_usage "$_keywords"
482	exit 1
483}
484
485#
486# run_rc_script file arg
487#	Start the script `file' with `arg', and correctly handle the
488#	return value from the script.  If `file' ends with `.sh', it's
489#	sourced into the current environment.  Otherwise it's run as
490#	a child process.
491#
492#	Note: because `.sh' files are sourced into the current environment
493#	run_rc_command shouldn't be used because its difficult to ensure
494#	that the global variable state before and after the sourcing of 
495#	the .sh file won't adversely affect other scripts.
496#
497run_rc_script()
498{
499	_file=$1
500	_arg=$2
501	if [ -z "$_file" -o -z "$_arg" ]; then
502		err 3 'USAGE: run_rc_script file arg'
503	fi
504
505	case "$_file" in
506	*.sh)				# run in current shell
507		set $_arg ; . $_file
508		;;
509	*)				# run in subshell
510		( set $_arg ; . $_file )
511		;;
512	esac
513}
514
515#
516# load_rc_config
517#	Source in the configuration file for a given command.
518#
519load_rc_config()
520{
521	_command=$1
522	if [ -z "$_command" ]; then
523		err 3 'USAGE: load_rc_config command'
524	fi
525
526	. /etc/rc.conf
527	if [ -f /etc/rc.conf.d/"$_command" ]; then
528		. /etc/rc.conf.d/"$_command"
529	fi
530}
531
532
533#
534# rc_usage commands
535#	Print a usage string for $0, with `commands' being a list of
536#	valid commands.
537#
538rc_usage()
539{
540	echo -n 1>&2 "Usage: $0 [fast|force]("
541
542	_sep=
543	for _elem in $*; do
544		echo -n 1>&2 "$_sep$_elem"
545		_sep="|"
546	done
547	echo 1>&2 ")"
548	exit 1
549}
550
551#
552# err exitval message
553#	Display message to stderr and log to the syslog, and exit with exitval.
554#
555err()
556{
557	exitval=$1
558	shift
559
560	logger "$0: ERROR: $*"
561	echo 1>&2 "$0: ERROR: $*"
562	exit $exitval
563}
564
565#
566# warn message
567#	Display message to stderr and log to the syslog.
568#
569warn()
570{
571	logger "$0: WARNING: $*"
572	echo 1>&2 "$0: WARNING: $*"
573}
574