91ae86d3eb2cd75e8f7ab957efe0063b27f3af4b
[nagcollect.git] / server / bin / nagios-submit-service
1 #!/bin/sh
2 # nagios-submit-service -- Submit passive service check result
3 # 2009-12-11, alex@barton.de
4
5 NAME=`basename "$0"`
6 CREATE=
7
8 Usage() {
9         echo "$NAME [-c] <host> <service> <code> [<text>]"; echo
10         echo "  -c         create new service, if necessary"
11         echo "  <host>     Nagios host ID"
12         echo "  <service>  Nagios service ID"
13         echo "  <code>     Status code: 0=OK, 1=Warning, 2=Error, 3=Unknown"
14         echo "  <text>     Optional status message"
15         echo; exit 1
16 }
17
18 Error() {
19         echo "$NAME: $*"
20         exit 1
21 }
22
23 [ -r "/etc/nagios3/system.cfg" ] || Error "Can't read /etc/nagios3/system.cfg!"
24 . /etc/nagios3/system.cfg 
25
26 # Validate command line arguments
27 if [ "$1" = "-c" ]; then
28         CREATE=1; shift
29 fi
30 [ $# -ge 3 -a $# -le 4 ] || Usage
31 [ "$3" = 0 -o "$3" = "1" -o "$3" = "2" -o "$3" = "3" ] || Usage
32
33 # Validate configuration
34 [ -w "$CMDFILE" ] || Error "Can't write to \"$CMDFILE\"!"
35
36 time_t=`date +%s`
37 host="$1"
38 service="$2"
39 code="$3"
40 text="${4:-}"
41
42 cfg=`grep -lE "^[[:space:]]+host_name[[:space:]]+${host}\$" "$CFGDIR"/*.cfg`
43 [ -n "$cfg" ] || Error "Host \"$host\" not configured!?"
44
45 case "$service" in
46         *"_p")
47                 # Passive service check; does it exist already?
48                 grep -E "^[[:space:]]+service_description[[:space:]]+${service}\$" \
49                         "$cfg" >/dev/null 2>&1
50                 if [ $? -ne 0 ]; then
51                         [ -n "$CREATE" ] || \
52                                 Error "Service \"$service\" not configured on \"$host\"!?"
53                         echo "Creating new Nagios host configuration for \"$host\" ..."
54                         cat >>"$cfg" <<EOF
55
56 define service {
57         use                     ${SERVICE_TEMPLATE_PASSIVE}
58         service_description     $service
59         check_command           ${SERVICE_PASSIVE_CMD}
60         host                    $host
61 }
62 EOF
63                         chmod "$CFG_MODE" "$cfg" || Error "chmod(1) failed!"
64                         echo "Reloading Nagios configuration ..."
65                         "$RCFILE" reload || Error "Failed to reload Nagios configuration!"
66                         sleep 1
67                 fi
68                 ;;
69 esac
70
71 cmd="[$time_t] PROCESS_SERVICE_CHECK_RESULT;$host;$service;$code;$text"
72 echo "$cmd" >>"$CMDFILE"